<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

ob_end_clean();
header("Content-Type: application/json; charset=UTF-8");

require_once "db.php";

$projectId = $_GET['project_id'] ?? 'All';
$range     = $_GET['range'] ?? 'week';
$from      = $_GET['from'] ?? null;
$to        = $_GET['to'] ?? null;

$whereRevenues = "WHERE 1";
$whereExpenses = "WHERE 1";

if ($projectId !== 'All' && $projectId !== '0' && $projectId !== 0) {
  $whereRevenues .= " AND PID = '$projectId'";
  $whereExpenses .= " AND project_id = '$projectId'";
}

switch ($range) {
  case 'week':
    $whereRevenues .= " AND date >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
    $whereExpenses .= " AND date >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
    $groupBy     = "DAYOFWEEK(date)";
    $labelFields = "DAYNAME(date) AS label";
    break;

  case 'month':
    $whereRevenues .= " AND date >= DATE_SUB(NOW(), INTERVAL 1 MONTH)";
    $whereExpenses .= " AND date >= DATE_SUB(NOW(), INTERVAL 1 MONTH)";
    $groupBy     = "WEEK(date)";
    $labelFields = "CONCAT('الأسبوع ', WEEK(date)) AS label";
    break;

  case 'year':
    $whereRevenues .= " AND date >= DATE_SUB(NOW(), INTERVAL 1 YEAR)";
    $whereExpenses .= " AND date >= DATE_SUB(NOW(), INTERVAL 1 YEAR)";
    $groupBy     = "MONTH(date)";
    $labelFields = "MONTHNAME(date) AS label";
    break;

  case 'custom':
    if ($from && $to) {
      $whereRevenues .= " AND date BETWEEN '$from' AND '$to'";
      $whereExpenses .= " AND date BETWEEN '$from' AND '$to'";
      $groupBy     = "DATE(date)";
      $labelFields = "DATE(date) AS label";
    } else {
      echo json_encode(["error" => "تاريخ مخصص غير صالح"]);
      exit;
    }
    break;

  case 'all':
    $revenues = $conn->query("SELECT SUM(value) AS total FROM revenuesMH $whereRevenues")->fetch_assoc()['total'] ?? 0;
    $expenses = $conn->query("SELECT SUM(total_price) AS total FROM expensesMH $whereExpenses")->fetch_assoc()['total'] ?? 0;
    $profits  = $revenues - $expenses;

    echo json_encode([
      "labels"   => ["الكل"],
      "revenues" => [floatval($revenues)],
      "expenses" => [floatval($expenses)],
      "profits"  => [floatval($profits)]
    ], JSON_UNESCAPED_UNICODE);
    exit;

  default:
    echo json_encode(["error" => "فلتر غير معروف"]);
    exit;
}

// الإيرادات
$revenuesQuery = $conn->query("
  SELECT $labelFields, SUM(value) AS total
  FROM revenuesMH
  $whereRevenues
  GROUP BY $groupBy
");

$revenuesData = [];
while ($row = $revenuesQuery->fetch_assoc()) {
  $revenuesData[$row['label']] = floatval($row['total']);
}

// المصروفات
$expensesQuery = $conn->query("
  SELECT $labelFields, SUM(total_price) AS total
  FROM expensesMH
  $whereExpenses
  GROUP BY $groupBy
");

$expensesData = [];
while ($row = $expensesQuery->fetch_assoc()) {
  $expensesData[$row['label']] = floatval($row['total']);
}

// دمج النتائج
$allLabels = array_unique(array_merge(array_keys($revenuesData), array_keys($expensesData)));
sort($allLabels);

$labels   = [];
$revenues = [];
$expenses = [];
$profits  = [];

foreach ($allLabels as $label) {
  $r = $revenuesData[$label] ?? 0;
  $e = $expensesData[$label] ?? 0;
  $p = $r - $e;

  $labels[]   = $label;
  $revenues[] = $r;
  $expenses[] = $e;
  $profits[]  = $p;
}

echo json_encode([
  "labels"   => $labels,
  "revenues" => $revenues,
  "expenses" => $expenses,
  "profits"  => $profits
], JSON_UNESCAPED_UNICODE);
exit;
