<?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']);

// تجهيز الاستعلام
if ($PID === 0) {
    $sql = "SELECT r.id, r.PID, p.project_name AS project_name, r.RafranceNumber, r.value, r.date, r.notes, r.AttachmentPath
            FROM revenuesMH r
            JOIN PrjectsMH p ON r.PID = p.id
            ORDER BY r.date DESC";
    $stmt = $conn->prepare($sql);
} else {
    $sql = "SELECT id, RafranceNumber, value, date, notes, AttachmentPath
            FROM revenuesMH
            WHERE PID = ?
            ORDER BY date DESC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $PID);
}

// تنفيذ الاستعلام
if (!$stmt->execute()) {
    echo json_encode(["status" => "error", "message" => "❌ فشل في تنفيذ الاستعلام"]);
    exit;
}

$result = $stmt->get_result();
$revenues = [];

while ($row = $result->fetch_assoc()) {
    $revenues[] = $row;
}

// إرسال الرد
echo json_encode(["status" => "success", "data" => $revenues]);

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