<?php
require 'db.php';
$response = [];

// راس المال
$fund = $conn->query("SELECT SUM(value) AS total FROM financialMH WHERE `AttachmentPath` IS NULL")->fetch_assoc()['total'] ?? 0;
$response['fund'] = number_format($fund);

// الرصيد = مدخل - مخرج
$in = $conn->query("SELECT SUM(value) AS total FROM TransactionsMH WHERE type = 'مدخل'")->fetch_assoc()['total'] ?? 0;
$out = $conn->query("SELECT SUM(value) AS total FROM TransactionsMH WHERE type = 'مخرج'")->fetch_assoc()['total'] ?? 0;
$balance = $in - $out;
$response['balance'] = number_format($balance);

// الإيرادات
$revenues = $conn->query("SELECT SUM(value) AS total FROM revenuesMH")->fetch_assoc()['total'] ?? 0;
$response['revenues'] = number_format($revenues);

// المصروفات
$expenses = $conn->query("SELECT SUM(total_price) AS total FROM expensesMH")->fetch_assoc()['total'] ?? 0;
$response['expenses'] = number_format($expenses);

// الأرباح
$profit = $revenues - $expenses;
$percentage = $fund > 0 ? round(($profit / $fund) * 100, 2) : 0;
$response['profits'] = number_format($profit);
$response['profits_percentage'] = "<i class='fas fa-arrow-up'></i> {$percentage}%";

// العهدة
$custodyQuery = "
  SELECT 
    c.PID,
    c.EmpID,
    SUM(c.CAmount) AS total_custody,
    IFNULL((
      SELECT SUM(e.total_price)
      FROM expensesMH e
      WHERE e.project_id = c.PID
        AND e.payment_method = 'عهده'
        AND e.EmpID = c.EmpID
    ), 0) AS total_expense
  FROM custodyMH c
  GROUP BY c.PID, c.EmpID
";

$custodyResult = $conn->query($custodyQuery);
$custodyBalance = 0;

while ($row = $custodyResult->fetch_assoc()) {
  $custodyBalance += ($row['total_custody'] - $row['total_expense']);
}

$response['custody'] = number_format($custodyBalance);

// المشاريع النشطة
$projects = [];
$projectQuery = "SELECT id, project_name, project_status FROM PrjectsMH WHERE project_status != 'منتهي';";
$result = $conn->query($projectQuery);
while ($row = $result->fetch_assoc()) {
  $projects[] = [
    'id' => $row['id'],
    'project_name' => $row['project_name'],
    'project_status' => $row['project_status']
  ];
}
$response['projects'] = $projects;

echo json_encode($response);

ini_set('display_errors', 1);
error_reporting(E_ALL);
