<?php
declare(strict_types=1);

require_once __DIR__ . '/_layout.php';

$pdo = financial_db();

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if (isset($_GET['branch_id'])) {
    $selectedBranchId = (int)$_GET['branch_id'];
    if (in_array($selectedBranchId, [1, 2], true)) {
        $_SESSION['financial_branch_id'] = $selectedBranchId;
        $_SESSION['branch_id'] = $selectedBranchId;
    }
}

$branchId = (int)($_SESSION['financial_branch_id'] ?? $_SESSION['branch_id'] ?? 1);
if (!in_array($branchId, [1, 2], true)) {
    $branchId = 1;
}

financial_page_start('لوحة الإدارة المالية');

function fmoney(float $v): string {
    return number_format($v, 2) . ' د.إ';
}

function get_branch_name(PDO $pdo, int $branchId): string {
    try {
        $st = $pdo->prepare("SELECT name_ar FROM branches WHERE id = ? LIMIT 1");
        $st->execute([$branchId]);
        $name = $st->fetchColumn();
        if ($name) return (string)$name;
    } catch (Throwable $e) {}

    return match ($branchId) {
        1 => 'أبوظبي',
        2 => 'دبي',
        default => 'غير معروف',
    };
}

$incomeToday = 0.0;
$incomeMonth = 0.0;
$incomeYear  = 0.0;

$expenseToday = 0.0;
$expenseMonth = 0.0;
$expenseYear  = 0.0;

$incomeCountToday  = 0;
$expenseCountToday = 0;

$latestIncome = [];
$latestExpenses = [];

$hasIncomeAttachment  = financial_has_column($pdo, 'financial_income', 'attachment_path');
$hasExpenseAttachment = financial_has_column($pdo, 'financial_expenses', 'attachment_path');

$hasIncomeCreatedAt  = financial_has_column($pdo, 'financial_income', 'created_at');
$hasExpenseCreatedAt = financial_has_column($pdo, 'financial_expenses', 'created_at');

$incomeDateCol  = $hasIncomeCreatedAt ? 'created_at' : 'income_date';
$expenseDateCol = $hasExpenseCreatedAt ? 'created_at' : 'expense_date';

$incomeAttachmentSelect  = $hasIncomeAttachment ? ', attachment_path' : '';
$expenseAttachmentSelect = $hasExpenseAttachment ? ', attachment_path' : '';

try {
    $st = $pdo->prepare("
    SELECT
        COALESCE(SUM(CASE
            WHEN DATE($incomeDateCol) = CURDATE()
            THEN amount ELSE 0 END), 0) AS income_today,

        COALESCE(SUM(CASE
            WHEN $incomeDateCol >= DATE_FORMAT(CURDATE(), '%Y-%m-01')
             AND $incomeDateCol < DATE_ADD(LAST_DAY(CURDATE()), INTERVAL 1 DAY)
            THEN amount ELSE 0 END), 0) AS income_month,

        COALESCE(SUM(CASE
            WHEN $incomeDateCol >= MAKEDATE(YEAR(CURDATE()), 1)
             AND $incomeDateCol < MAKEDATE(YEAR(CURDATE()) + 1, 1)
            THEN amount ELSE 0 END), 0) AS income_year,

        COUNT(CASE
            WHEN DATE($incomeDateCol) = CURDATE()
            THEN 1 END) AS income_count_today
    FROM financial_income
    WHERE branch_id = ?
      AND (
        notes IS NULL
        OR notes NOT LIKE '%رقم السطر%'
      )
");
    $st->execute([$branchId]);
    $incomeStats = $st->fetch(PDO::FETCH_ASSOC) ?: [];

    $incomeToday      = (float)($incomeStats['income_today'] ?? 0);
    $incomeMonth      = (float)($incomeStats['income_month'] ?? 0);
    $incomeYear       = (float)($incomeStats['income_year'] ?? 0);
    $incomeCountToday = (int)($incomeStats['income_count_today'] ?? 0);

    $st = $pdo->prepare("
        SELECT
            id,
            client_name,
            service_type,
            amount,
            payment_method,
            income_date
            $incomeAttachmentSelect
        FROM financial_income
        WHERE branch_id = ?
        ORDER BY $incomeDateCol DESC, id DESC
        LIMIT 8
    ");
    $st->execute([$branchId]);
    $latestIncome = $st->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {
    $latestIncome = [];
}

try {
    $st = $pdo->prepare("
        SELECT
            COALESCE(SUM(CASE
                WHEN DATE($expenseDateCol) = CURDATE()
                THEN amount ELSE 0 END), 0) AS expense_today,

            COALESCE(SUM(CASE
                WHEN $expenseDateCol >= DATE_FORMAT(CURDATE(), '%Y-%m-01')
                 AND $expenseDateCol < DATE_ADD(LAST_DAY(CURDATE()), INTERVAL 1 DAY)
                THEN amount ELSE 0 END), 0) AS expense_month,

            COALESCE(SUM(CASE
                WHEN $expenseDateCol >= MAKEDATE(YEAR(CURDATE()), 1)
                 AND $expenseDateCol < MAKEDATE(YEAR(CURDATE()) + 1, 1)
                THEN amount ELSE 0 END), 0) AS expense_year,

            COUNT(CASE
                WHEN DATE($expenseDateCol) = CURDATE()
                THEN 1 END) AS expense_count_today
        FROM financial_expenses
        WHERE branch_id = ?
    ");
    $st->execute([$branchId]);
    $expenseStats = $st->fetch(PDO::FETCH_ASSOC) ?: [];

    $expenseToday      = (float)($expenseStats['expense_today'] ?? 0);
    $expenseMonth      = (float)($expenseStats['expense_month'] ?? 0);
    $expenseYear       = (float)($expenseStats['expense_year'] ?? 0);
    $expenseCountToday = (int)($expenseStats['expense_count_today'] ?? 0);

    $st = $pdo->prepare("
        SELECT
            id,
            title,
            category,
            amount,
            expense_date,
            notes
            $expenseAttachmentSelect
        FROM financial_expenses
        WHERE branch_id = ?
        ORDER BY $expenseDateCol DESC, id DESC
        LIMIT 8
    ");
    $st->execute([$branchId]);
    $latestExpenses = $st->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {
    $latestExpenses = [];
}

$netToday = $incomeToday - $expenseToday;
$netMonth = $incomeMonth - $expenseMonth;
$netYear  = $incomeYear - $expenseYear;
?>

<div class="actions" style="width:100%; margin-bottom:12px; gap:10px; flex-wrap:wrap;">
  <a class="btn <?= $branchId === 1 ? 'primary' : 'soft' ?>" href="dashboard.php?branch_id=1">فرع أبوظبي</a>
  <a class="btn <?= $branchId === 2 ? 'primary' : 'soft' ?>" href="dashboard.php?branch_id=2">فرع دبي</a>
  <span class="btn soft">الفرع الحالي: <?= financial_h(get_branch_name($pdo, $branchId)) ?></span>
</div>

<div class="cards">

  <div class="card"><div class="k">مدخولات اليوم</div><div class="v"><?= financial_h(fmoney($incomeToday)) ?></div></div>
  <div class="card"><div class="k">مصروفات اليوم</div><div class="v"><?= financial_h(fmoney($expenseToday)) ?></div></div>
  <div class="card"><div class="k">صافي اليوم</div><div class="v"><?= financial_h(fmoney($netToday)) ?></div></div>
  <div class="card"><div class="k">عدد عمليات المدخول اليوم</div><div class="v"><?= (int)$incomeCountToday ?></div></div>

  <div class="card"><div class="k">مدخولات هذا الشهر</div><div class="v"><?= financial_h(fmoney($incomeMonth)) ?></div></div>
  <div class="card"><div class="k">مصروفات هذا الشهر</div><div class="v"><?= financial_h(fmoney($expenseMonth)) ?></div></div>
  <div class="card"><div class="k">صافي هذا الشهر</div><div class="v"><?= financial_h(fmoney($netMonth)) ?></div></div>
  <div class="card"><div class="k">عدد عمليات المصروف اليوم</div><div class="v"><?= (int)$expenseCountToday ?></div></div>

  <div class="card"><div class="k">مدخولات السنة</div><div class="v"><?= financial_h(fmoney($incomeYear)) ?></div></div>
  <div class="card"><div class="k">مصروفات السنة</div><div class="v"><?= financial_h(fmoney($expenseYear)) ?></div></div>
  <div class="card"><div class="k">صافي السنة</div><div class="v"><?= financial_h(fmoney($netYear)) ?></div></div>
  <div class="card"><div class="k">الفرع الحالي</div><div class="v"><?= financial_h(get_branch_name($pdo, $branchId)) ?></div></div>

</div>

<div class="panel">
  <div class="panel-head">آخر المدخولات</div>
  <div class="panel-body">

    <div class="actions" style="margin-bottom:14px; gap:10px; flex-wrap:wrap;">
      <a class="btn primary" href="<?= financial_h(financial_u('income.php')) ?>">إضافة مدخول</a>
      <a class="btn soft" href="<?= financial_h(financial_u('import_files.php')) ?>">📑 الكشوفات المالية</a>
    </div>

    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>التاريخ</th>
            <th>العميل</th>
            <th>الخدمة</th>
            <th>المبلغ</th>
            <th>طريقة الدفع</th>
            <th>المرفق</th>
            <th>الإجراءات</th>
          </tr>
        </thead>

        <tbody>
          <?php if (empty($latestIncome)): ?>
            <tr><td colspan="7">لا توجد بيانات مدخولات حتى الآن.</td></tr>
          <?php else: ?>
            <?php foreach ($latestIncome as $row): ?>
              <tr>
                <td><?= financial_h((string)($row['income_date'] ?? '')) ?></td>
                <td><?= financial_h((string)($row['client_name'] ?? '—')) ?></td>
                <td><?= financial_h((string)($row['service_type'] ?? '—')) ?></td>
                <td><?= financial_h(fmoney((float)($row['amount'] ?? 0))) ?></td>
                <td><?= financial_h((string)($row['payment_method'] ?? '—')) ?></td>

                <td>
                  <?php if ($hasIncomeAttachment && !empty($row['attachment_path'])): ?>
                    <a class="btn soft" href="<?= financial_h((string)$row['attachment_path']) ?>" target="_blank">عرض</a>
                  <?php else: ?>
                    —
                  <?php endif; ?>
                </td>

                <td>
                  <div class="actions" style="gap:8px; flex-wrap:wrap;">
                    <a class="btn" href="<?= financial_h(financial_u('income_edit.php?id=' . (int)$row['id'])) ?>">تعديل</a>

                    <form action="<?= financial_h(financial_u('income_delete.php')) ?>" method="post" onsubmit="return confirm('هل أنت متأكد من حذف هذا المدخول؟');" style="display:inline;">
                      <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                      <button class="btn" type="submit" style="border-color:#ef4444;color:#b91c1c;">حذف</button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>

      </table>
    </div>
  </div>
</div>

<div class="panel">
  <div class="panel-head">آخر المصروفات</div>
  <div class="panel-body">

    <div class="actions" style="margin-bottom:14px; gap:10px; flex-wrap:wrap;">
      <a class="btn primary" href="<?= financial_h(financial_u('expenses.php')) ?>">إضافة مصروف</a>

      <a class="btn soft"
         href="<?= financial_h(financial_u('import_files.php')) ?>"
         style="background:rgba(212,175,55,.10);border:1px solid rgba(212,175,55,.35);color:#f8d56b;font-weight:800;">
        📑 الكشوفات المالية
      </a>
    </div>

    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>التاريخ</th>
            <th>العنوان</th>
            <th>التصنيف</th>
            <th>المبلغ</th>
            <th>الملاحظات</th>
            <th>المرفق</th>
            <th>الإجراءات</th>
          </tr>
        </thead>

        <tbody>
          <?php if (empty($latestExpenses)): ?>
            <tr><td colspan="7">لا توجد بيانات مصروفات حتى الآن.</td></tr>
          <?php else: ?>
            <?php foreach ($latestExpenses as $row): ?>
              <tr>
                <td><?= financial_h((string)($row['expense_date'] ?? '')) ?></td>
                <td><?= financial_h((string)($row['title'] ?? '—')) ?></td>
                <td><?= financial_h((string)($row['category'] ?? '—')) ?></td>
                <td><?= financial_h(fmoney((float)($row['amount'] ?? 0))) ?></td>
                <td><?= financial_h((string)($row['notes'] ?? '—')) ?></td>

                <td>
                  <?php if ($hasExpenseAttachment && !empty($row['attachment_path'])): ?>
                    <a class="btn soft" href="<?= financial_h((string)$row['attachment_path']) ?>" target="_blank">عرض</a>
                  <?php else: ?>
                    —
                  <?php endif; ?>
                </td>

                <td>
                  <div class="actions" style="gap:8px; flex-wrap:wrap;">
                    <a class="btn" href="<?= financial_h(financial_u('expense_edit.php?id=' . (int)$row['id'])) ?>">تعديل</a>

                    <form action="<?= financial_h(financial_u('expense_delete.php')) ?>" method="post" onsubmit="return confirm('هل أنت متأكد من حذف هذا المصروف؟');" style="display:inline;">
                      <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                      <button class="btn" type="submit" style="border-color:#ef4444;color:#b91c1c;">حذف</button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>

      </table>
    </div>
  </div>
</div>

<?php financial_page_end(); ?>