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

$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

if ($action === 'list') {
    $sql = "SELECT id AS __backendId, issue_ref, personnel_id, personnel_name, ppe_id, ppe_name, size, quantity, status, issued_at FROM ppe_issuance ORDER BY id DESC";
    $result = $mysqli->query($sql);
    $data = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }
    echo json_encode($data);
} elseif ($action === 'create') {
    $personnel_name = $_POST['personnel_name'] ?? '';
    $ppe_name = $_POST['ppe_name'] ?? '';
    $quantity = $_POST['quantity'] ?? 0;
    $department = $_POST['department'] ?? '';
    $size = $_POST['size'] ?? '';
    
    $stmt = $mysqli->prepare("INSERT INTO ppe_issuance (personnel_name, ppe_name, quantity, department, size, status) VALUES (?, ?, ?, ?, ?, 'Active')");
    $stmt->bind_param("ssisss", $personnel_name, $ppe_name, $quantity, $department, $size);
    $ok = $stmt->execute();
    $insert_id = $stmt->insert_id;
    
    echo json_encode(['success' => $ok, 'insert_id' => $insert_id]);
} elseif ($action === 'delete') {
    $id = $_GET['id'] ?? null;
    if (!$id) { 
        echo json_encode(['success' => false]); 
        exit; 
    }
    $stmt = $mysqli->prepare("DELETE FROM ppe_issuance WHERE id=?");
    $stmt->bind_param("i", $id);
    $ok = $stmt->execute();
    echo json_encode(['success' => $ok]);
}
?>
