<?php
declare(strict_types=1);

require_once __DIR__ . '/_layout.php';

finance_shell_start('dashboard');
page_header('لوحة المالية');

$month = (string)($_GET['m'] ?? date('Y-m'));
if (!preg_match('/^\d{4}-\d{2}$/', $month)) $month = date('Y-m');

/* ===== salaries: last record per employee ===== */
$totalSalary = (float)$pdo->query("
SELECT COALESCE(SUM(x.total),0) FROM (
  SELECT s.employee_id,
         (COALESCE(s.basic_salary,0) + COALESCE(s.housing_allowance,0) + COALESCE(s.transport_allowance,0) + COALESCE(s.other_allowance,0)) AS total
  FROM employee_salaries s
  INNER JOIN (
    SELECT employee_id, MAX(id) AS max_id
    FROM employee_salaries
    GROUP BY employee_id
  ) m ON m.employee_id = s.employee_id AND m.max_id = s.id
) x
")->fetchColumn();

/* ===== bonuses/deductions by month ===== */
$st = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM employee_bonuses WHERE payroll_month = ?");
$st->execute([$month]);
$totalBonuses = (float)$st->fetchColumn();

$st = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM employee_deductions WHERE payroll_month = ?");
$st->execute([$month]);
$totalDeductions = (float)$st->fetchColumn();

$net = $totalSalary + $totalBonuses - $totalDeductions;
?>

<div class="card" style="margin-bottom:12px">
  <form class="row" method="get" action="">
    <select class="select" name="m">
      <?php
        for($i=0;$i<12;$i++){
          $m = date('Y-m', strtotime(date('Y-m-01') . " -$i months"));
          $sel = ($m===$month) ? 'selected' : '';
          echo "<option $sel value='".h($m)."'>".h($m)."</option>";
        }
      ?>
    </select>
    <button class="btn" type="submit">عرض</button>
    <a class="btn secondary" href="index.php">اليوم</a>
  </form>
</div>

<div class="grid">
  <div class="card kpi">
    <div class="k">إجمالي الرواتب والبدلات</div>
    <div class="v"><?= number_format($totalSalary,2) ?> AED</div>
    <div class="s">آخر راتب لكل موظف</div>
  </div>

  <div class="card kpi">
    <div class="k">إجمالي المكافآت</div>
    <div class="v"><?= number_format($totalBonuses,2) ?> AED</div>
    <div class="s">شهر: <?= h($month) ?></div>
  </div>

  <div class="card kpi">
    <div class="k">إجمالي الخصومات</div>
    <div class="v"><?= number_format($totalDeductions,2) ?> AED</div>
    <div class="s">شهر: <?= h($month) ?></div>
  </div>

  <div class="card kpi">
    <div class="k">الصافي</div>
    <div class="v"><?= number_format($net,2) ?> AED</div>
    <div class="s">رواتب + مكافآت - خصومات</div>
  </div>

  <div class="card" style="grid-column: span 12">
    <h3>ملاحظة</h3>
    <div style="color:#64748b;font-size:13px">
      الحسابات الشهرية تعتمد على payroll_month في المكافآت والخصومات.
    </div>
  </div>
</div>

<?php finance_shell_end(); ?>