<?php
error_reporting(0);
ini_set('display_errors', 0);
session_start();
header('Content-Type: application/json');

try {
    include '../config/database.php';
    $db = new Database();
    $conn = $db->getConnection();

    $action = $_REQUEST['action']?? 'get';
    $uploadDir = '../uploads/inventaris_dpw/';

    // Bikin folder kalo belum ada
    if(!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

    if($action == 'get'){
        $stmt = $conn->query("SELECT * FROM inventaris_dpw ORDER BY id DESC");
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['data' => $data]);
        exit;
    }

    if($action == 'detail'){
        $stmt = $conn->prepare("SELECT * FROM inventaris_dpw WHERE id=?");
        $stmt->execute([$_GET['id']]);
        echo json_encode(['status'=>'success', 'data'=>$stmt->fetch(PDO::FETCH_ASSOC)]);
        exit;
    }

    if($action == 'simpan'){
        $id = $_POST['id'];
        $nama_gambar = null;

        // Handle upload gambar
        if(isset($_FILES['gambar']) && $_FILES['gambar']['error'] == 0){
            $ext = pathinfo($_FILES['gambar']['name'], PATHINFO_EXTENSION);
            $nama_gambar = 'dpw_'.time().'_'.rand(100,999).'.'.$ext;
            move_uploaded_file($_FILES['gambar']['tmp_name'], $uploadDir.$nama_gambar);

            // Hapus gambar lama kalo edit
            if(!empty($id)){
                $cek = $conn->prepare("SELECT gambar FROM inventaris_dpw WHERE id=?");
                $cek->execute([$id]);
                $old = $cek->fetchColumn();
                if($old && file_exists($uploadDir.$old)) unlink($uploadDir.$old);
            }
        }

        $data = [
            $_POST['nama_barang'],
            $_POST['kategori'],
            $_POST['jumlah'],
            $_POST['kondisi'],
            $_POST['tgl_beli']?: NULL,
            $_POST['harga_beli']?: 0,
            $_POST['lokasi'],
            $_POST['keterangan']
        ];

        if(empty($id)){
            $sql = "INSERT INTO inventaris_dpw (nama_barang,kategori,jumlah,kondisi,tgl_beli,harga_beli,lokasi,keterangan,gambar) VALUES (?,?,?,?,?,?,?,?,?)";
            $data[] = $nama_gambar;
        } else {
            if($nama_gambar){
                $sql = "UPDATE inventaris_dpw SET nama_barang=?,kategori=?,jumlah=?,kondisi=?,tgl_beli=?,harga_beli=?,lokasi=?,keterangan=?,gambar=? WHERE id=?";
                $data[] = $nama_gambar;
            } else {
                $sql = "UPDATE inventaris_dpw SET nama_barang=?,kategori=?,jumlah=?,kondisi=?,tgl_beli=?,harga_beli=?,lokasi=?,keterangan=? WHERE id=?";
            }
            $data[] = $id;
        }
        $stmt = $conn->prepare($sql);
        $stmt->execute($data);
        echo json_encode(['status'=>'sukses', 'message'=>'Data berhasil disimpan']);
        exit;
    }

    if($action == 'hapus'){
        // Hapus file gambar dulu
        $cek = $conn->prepare("SELECT gambar FROM inventaris_dpw WHERE id=?");
        $cek->execute([$_GET['id']]);
        $gambar = $cek->fetchColumn();
        if($gambar && file_exists($uploadDir.$gambar)) unlink($uploadDir.$gambar);

        $stmt = $conn->prepare("DELETE FROM inventaris_dpw WHERE id=?");
        $stmt->execute([$_GET['id']]);
        echo json_encode(['status'=>'sukses', 'message'=>'Data berhasil dihapus']);
        exit;
    }

} catch (Exception $e) {
    echo json_encode(['status'=>'error', 'message'=>$e->getMessage(), 'data'=>[]]);
}
?>