<?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 
            p.id AS project_id,
            p.project_name,
            IFNULL((
                SELECT SUM(value) FROM revenuesMH WHERE PID = p.id
            ), 0) AS total_revenue,
            IFNULL((
                SELECT SUM(total_price) FROM expensesMH WHERE project_id = p.id
            ), 0) AS total_expense
        FROM PrjectsMH p
        ORDER BY p.project_name ASC
    ";

    $stmt = $conn->prepare($sql);
} else {
    // جلب أرباح مشروع معين بدون تكرار
    $sql = "
        SELECT 
            p.id AS project_id,
            p.project_name,
            IFNULL((
                SELECT SUM(value) FROM revenuesMH WHERE PID = p.id
            ), 0) AS total_revenue,
            IFNULL((
                SELECT SUM(total_price) FROM expensesMH WHERE project_id = p.id
            ), 0) AS total_expense
        FROM PrjectsMH p
        WHERE p.id = ?
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $PID);
}

// تنفيذ الاستعلام
$stmt->execute();
$result = $stmt->get_result();

$profits = [];
while ($row = $result->fetch_assoc()) {
    $revenue = floatval($row['total_revenue']);
    $expense = floatval($row['total_expense']);
    $profit = $revenue - $expense;

    $percentage = $expense > 0 ? round(($profit / $expense) * 100, 2) : 0;

    $profits[] = [
        "project_name" => $row['project_name'],
        "total_expense" => $expense,
        "total_revenue" => $revenue,
        "profit" => $profit,
        "percentage" => $percentage,
        "notes" => ""
    ];
}

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

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