<?php
declare(strict_types=1);

require_once __DIR__ . '/_layout.php';

$pdo      = financial_db();
$branchId = financial_branch_id();

financial_page_start('التقارير المالية');

$dateFrom = trim((string)($_GET['date_from'] ?? date('Y-01-01')));
$dateTo   = trim((string)($_GET['date_to'] ?? date('Y-m-d')));

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateFrom)) {
    $dateFrom = date('Y-01-01');
}
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateTo)) {
    $dateTo = date('Y-m-d');
}

/* لو التاريخ من أكبر من إلى، بدّلهم */
if ($dateFrom > $dateTo) {
    [$dateFrom, $dateTo] = [$dateTo, $dateFrom];
}

$totalIncome       = 0.0;
$totalExpenses     = 0.0;
$netProfit         = 0.0;
$profitMargin      = 0.0;
$monthlyIncome     = [];
$monthlyExpenses   = [];
$expenseCategories = [];

if (!function_exists('fmoney_report')) {
    function fmoney_report(float $v): string {
        return number_format($v, 2) . ' د.إ';
    }
}

try {
    $st = $pdo->prepare("
        SELECT COALESCE(SUM(amount), 0)
        FROM financial_income
        WHERE branch_id = ? AND income_date BETWEEN ? AND ?
    ");
    $st->execute([$branchId, $dateFrom, $dateTo]);
    $totalIncome = (float)$st->fetchColumn();
} catch (Throwable $e) {
    $totalIncome = 0.0;
}

try {
    $st = $pdo->prepare("
        SELECT COALESCE(SUM(amount), 0)
        FROM financial_expenses
        WHERE branch_id = ? AND expense_date BETWEEN ? AND ?
    ");
    $st->execute([$branchId, $dateFrom, $dateTo]);
    $totalExpenses = (float)$st->fetchColumn();
} catch (Throwable $e) {
    $totalExpenses = 0.0;
}

$netProfit = $totalIncome - $totalExpenses;
$profitMargin = ($totalIncome > 0) ? (($netProfit / $totalIncome) * 100) : 0.0;

try {
    $st = $pdo->prepare("
        SELECT DATE_FORMAT(income_date, '%Y-%m') AS ym, COALESCE(SUM(amount), 0) AS total
        FROM financial_income
        WHERE branch_id = ? AND income_date BETWEEN ? AND ?
        GROUP BY ym
        ORDER BY ym DESC
    ");
    $st->execute([$branchId, $dateFrom, $dateTo]);
    $monthlyIncome = $st->fetchAll();
} catch (Throwable $e) {
    $monthlyIncome = [];
}

try {
    $st = $pdo->prepare("
        SELECT DATE_FORMAT(expense_date, '%Y-%m') AS ym, COALESCE(SUM(amount), 0) AS total
        FROM financial_expenses
        WHERE branch_id = ? AND expense_date BETWEEN ? AND ?
        GROUP BY ym
        ORDER BY ym DESC
    ");
    $st->execute([$branchId, $dateFrom, $dateTo]);
    $monthlyExpenses = $st->fetchAll();
} catch (Throwable $e) {
    $monthlyExpenses = [];
}

try {
    $st = $pdo->prepare("
        SELECT category, COALESCE(SUM(amount), 0) AS total
        FROM financial_expenses
        WHERE branch_id = ? AND expense_date BETWEEN ? AND ?
        GROUP BY category
        ORDER BY total DESC
    ");
    $st->execute([$branchId, $dateFrom, $dateTo]);
    $expenseCategories = $st->fetchAll();
} catch (Throwable $e) {
    $expenseCategories = [];
}
?>

<style>
@media print {
  body{
    background:#fff !important;
  }

  .top,
  .layout > aside,
  .nav,
  .finance-hero,
  .no-print{
    display:none !important;
  }

  .layout{
    display:block !important;
  }

  .content,
  .wrap{
    max-width:100% !important;
    width:100% !important;
    padding:0 !important;
    margin:0 !important;
  }

  .panel,
  .card{
    box-shadow:none !important;
    border:1px solid #ddd !important;
    break-inside:avoid;
    page-break-inside:avoid;
  }

  .cards{
    grid-template-columns:repeat(4,1fr) !important;
    gap:10px !important;
  }

  table{
    width:100% !important;
    border-collapse:collapse !important;
  }

  th, td{
    border:1px solid #ddd !important;
    white-space:normal !important;
  }

  @page{
    size:A4;
    margin:12mm;
  }
}
</style>

<div class="panel no-print">
  <div class="panel-head">فلترة التقرير</div>
  <div class="panel-body">
    <form method="get">
      <div class="form-grid">
        <div class="field">
          <label>من تاريخ</label>
          <input class="input" type="date" name="date_from" value="<?= financial_h($dateFrom) ?>">
        </div>

        <div class="field">
          <label>إلى تاريخ</label>
          <input class="input" type="date" name="date_to" value="<?= financial_h($dateTo) ?>">
        </div>
      </div>

      <div class="actions" style="margin-top:14px;">
        <button class="btn primary" type="submit">عرض التقرير</button>
        <button class="btn" type="button" onclick="window.print()">طباعة التقرير</button>
      </div>
    </form>
  </div>
</div>

<div class="cards">
  <div class="card">
    <div class="k">إجمالي المدخولات</div>
    <div class="v"><?= financial_h(fmoney_report($totalIncome)) ?></div>
  </div>

  <div class="card">
    <div class="k">إجمالي المصروفات</div>
    <div class="v"><?= financial_h(fmoney_report($totalExpenses)) ?></div>
  </div>

  <div class="card">
    <div class="k">صافي الربح</div>
    <div class="v"><?= financial_h(fmoney_report($netProfit)) ?></div>
  </div>

  <div class="card">
    <div class="k">الفترة</div>
    <div class="v" style="font-size:18px;"><?= financial_h($dateFrom . ' → ' . $dateTo) ?></div>
  </div>
</div>

<div class="cards" style="margin-top:14px;">
  <div class="card">
    <div class="k">نسبة الربحية</div>
    <div class="v"><?= financial_h(number_format($profitMargin, 1) . '%') ?></div>
  </div>

  <div class="card">
    <div class="k">عدد شهور المدخول</div>
    <div class="v"><?= (int)count($monthlyIncome) ?></div>
  </div>

  <div class="card">
    <div class="k">عدد شهور المصروف</div>
    <div class="v"><?= (int)count($monthlyExpenses) ?></div>
  </div>

  <div class="card">
    <div class="k">عدد التصنيفات</div>
    <div class="v"><?= (int)count($expenseCategories) ?></div>
  </div>
</div>

<div class="panel">
  <div class="panel-head">المدخولات الشهرية</div>
  <div class="panel-body">
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>الشهر</th>
            <th>الإجمالي</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$monthlyIncome): ?>
            <tr>
              <td colspan="2">لا توجد بيانات.</td>
            </tr>
          <?php else: ?>
            <?php foreach ($monthlyIncome as $row): ?>
              <tr>
                <td><?= financial_h((string)$row['ym']) ?></td>
                <td><?= financial_h(fmoney_report((float)$row['total'])) ?></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="table-wrap">
      <table>
        <thead>
          <tr>
            <th>الشهر</th>
            <th>الإجمالي</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$monthlyExpenses): ?>
            <tr>
              <td colspan="2">لا توجد بيانات.</td>
            </tr>
          <?php else: ?>
            <?php foreach ($monthlyExpenses as $row): ?>
              <tr>
                <td><?= financial_h((string)$row['ym']) ?></td>
                <td><?= financial_h(fmoney_report((float)$row['total'])) ?></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="table-wrap">
      <table>
        <thead>
          <tr>
            <th>التصنيف</th>
            <th>الإجمالي</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$expenseCategories): ?>
            <tr>
              <td colspan="2">لا توجد بيانات.</td>
            </tr>
          <?php else: ?>
            <?php foreach ($expenseCategories as $row): ?>
              <tr>
                <td><?= financial_h((string)$row['category']) ?></td>
                <td><?= financial_h(fmoney_report((float)$row['total'])) ?></td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php financial_page_end(); ?>