<?php
header("Content-Type: application/json; charset=UTF-8");
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once "db.php";

// استقبال البيانات
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);

// تحقق من وصول البيانات
if (!$data || !isset($data['PID'])) {
    echo json_encode(["status" => "error", "message" => "❌ لم يتم استلام رقم المشروع"]);
    exit;
}

$PID = intval($data['PID']);

$sql = ($PID === 0)
    ? "SELECT 
            e.id, e.project_id, p.project_name,
            e.invoice_number, e.date, e.item_price, e.unit, e.quantity, e.total_price,
            e.supplier, e.payment_method, e.notes, e.AttachmentPath,
            e.EmpID, u.username AS employee_name
        FROM expensesMH e
        LEFT JOIN PrjectsMH p ON e.project_id = p.id
        LEFT JOIN USEUSERSMH u ON e.EmpID = u.id
        ORDER BY e.date DESC"
    : "SELECT 
            e.id, e.project_id, p.project_name,
            e.invoice_number, e.date, e.item_price, e.unit, e.quantity, e.total_price,
            e.supplier, e.payment_method, e.notes, e.AttachmentPath,
            e.EmpID, u.username AS employee_name
        FROM expensesMH e
        LEFT JOIN PrjectsMH p ON e.project_id = p.id
        LEFT JOIN USEUSERSMH u ON e.EmpID = u.id
        WHERE e.project_id = ?
        ORDER BY e.date DESC";

$stmt = $conn->prepare($sql);
if ($PID !== 0) {
    $stmt->bind_param("i", $PID);
}
$stmt->execute();
$result = $stmt->get_result();

$expenses = [];
while ($row = $result->fetch_assoc()) {
    $expenses[] = [
        "id" => $row["id"],
        "project_name" => $row["project_name"] ?? "غير محدد",
        "invoice_number" => $row["invoice_number"],
        "date" => $row["date"],
        "item_price" => $row["item_price"],
        "unit" => $row["unit"],
        "quantity" => $row["quantity"],
        "total_price" => $row["total_price"],
        "supplier" => $row["supplier"],
        "payment_method" => $row["payment_method"],
        "employee_name" => isset($row["employee_name"]) && $row["employee_name"] !== null
            ? $row["employee_name"]
            : "-",
        "AttachmentPath" => $row["AttachmentPath"] ?? "",
        "notes" => $row["notes"]
    ];
}

echo json_encode(["status" => "success", "data" => $expenses]);

$stmt->close();
$conn->close();
?>
