<?php
session_start();
header('Content-Type: application/json');
include '../config/database.php';

if(!isset($_SESSION['user_id']) || $_SESSION['role'] != 'gembala'){
    die(json_encode(['status'=>'error','message'=>'Akses ditolak']));
}

$db = new Database();
$conn = $db->getConnection();

$action = $_REQUEST['action']?? 'get';
$gereja_id = $_SESSION['gereja_id'];
$uploadDir = '../uploads/inventaris_gereja/';

if(!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

if($action == 'get'){
    $stmt = $conn->prepare("SELECT * FROM inventaris WHERE gereja_id = ? ORDER BY nama_barang ASC");
    $stmt->execute([$gereja_id]);
    echo json_encode(['data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

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

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

    if(isset($_FILES['foto']) && $_FILES['foto']['error'] == 0){
        $ext = pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION);
        $nama_foto = 'gereja_'.$gereja_id.'_'.time().'_'.rand(100,999).'.'.$ext;
        move_uploaded_file($_FILES['foto']['tmp_name'], $uploadDir.$nama_foto);

        if(!empty($id)){
            $cek = $conn->prepare("SELECT foto FROM inventaris WHERE id=? AND gereja_id=?");
            $cek->execute([$id, $gereja_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'], $gereja_id
    ];

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

if($action == 'hapus'){
    $cek = $conn->prepare("SELECT foto FROM inventaris WHERE id=? AND gereja_id=?");
    $cek->execute([$_GET['id'], $gereja_id]);
    $foto = $cek->fetchColumn();
    if($foto && file_exists($uploadDir.$foto)) unlink($uploadDir.$foto);

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