<?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, request_ref, requester_name, ppe_name, quantity, status, created_at FROM ppe_requests 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') {
    $requester_name = $_POST['requester_name'] ?? '';
    $ppe_name = $_POST['ppe_name'] ?? '';
    $quantity = $_POST['quantity'] ?? 0;
    $status = $_POST['status'] ?? 'pending';
    $notes = $_POST['notes'] ?? '';
    
    $stmt = $mysqli->prepare("INSERT INTO ppe_requests (requester_name, ppe_name, quantity, status, notes) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("ssis", $requester_name, $ppe_name, $quantity, $status, $notes);
    $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_requests WHERE id=?");
    $stmt->bind_param("i", $id);
    $ok = $stmt->execute();
    echo json_encode(['success' => $ok]);
} elseif ($action === 'update_status') {
    $id = $_POST['id'] ?? null;
    $status = $_POST['status'] ?? 'pending';
    if (!$id) { 
        echo json_encode(['success' => false]); 
        exit; 
    }
    $stmt = $mysqli->prepare("UPDATE ppe_requests SET status=? WHERE id=?");
    $stmt->bind_param("si", $status, $id);
    $ok = $stmt->execute();
    echo json_encode(['success' => $ok]);
}
?>
