<?php
declare(strict_types=1);

require_once __DIR__ . '/_layout.php';

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


$year = (int)($_GET['year'] ?? date('Y'));
if ($year < 2000 || $year > 2100) {
    $year = (int)date('Y');
}

$dateFrom = sprintf('%04d-01-01', $year);
$dateTo   = sprintf('%04d-12-31', $year);

$totalIncome   = 0.0;
$totalExpenses = 0.0;
$netProfit     = 0.0;
$profitMargin  = 0.0;

$msg = (string)($_GET['msg'] ?? '');
$err = (string)($_GET['err'] ?? '');

if (!function_exists('fy_money')) {
    function fy_money(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;

/*
  حفظ الجرد:
  إذا كان موجودًا لنفس الفرع ونفس السنة ونفس النوع yearly يتم تحديثه
  وإذا لم يكن موجودًا يتم إدراجه
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_snapshot'])) {
    try {
        $periodLabel = 'السنة ' . $year;

        $check = $pdo->prepare("
            SELECT id
            FROM financial_snapshots
            WHERE branch_id = ?
              AND report_type = 'yearly'
              AND date_from = ?
              AND date_to = ?
            LIMIT 1
        ");
        $check->execute([$branchId, $dateFrom, $dateTo]);
        $existingId = (int)($check->fetchColumn() ?: 0);

        if ($existingId > 0) {
            $up = $pdo->prepare("
                UPDATE financial_snapshots
                SET period_label = ?,
                    total_income = ?,
                    total_expenses = ?,
                    net_profit = ?,
                    created_by = ?
                WHERE id = ?
            ");
            $up->execute([
                $periodLabel,
                $totalIncome,
                $totalExpenses,
                $netProfit,
                $userId,
                $existingId
            ]);

            header('Location: ' . financial_u('yearly.php?year=' . $year . '&msg=' . urlencode('تم تحديث الجرد السنوي بنجاح')));
            exit;
        } else {
            $ins = $pdo->prepare("
                INSERT INTO financial_snapshots
                (branch_id, report_type, period_label, date_from, date_to, total_income, total_expenses, net_profit, created_by)
                VALUES
                (?, 'yearly', ?, ?, ?, ?, ?, ?, ?)
            ");
            $ins->execute([
                $branchId,
                $periodLabel,
                $dateFrom,
                $dateTo,
                $totalIncome,
                $totalExpenses,
                $netProfit,
                $userId
            ]);

            header('Location: ' . financial_u('yearly.php?year=' . $year . '&msg=' . urlencode('تم حفظ الجرد السنوي بنجاح')));
            exit;
        }
    } catch (Throwable $e) {
        header('Location: ' . financial_u('yearly.php?year=' . $year . '&err=' . urlencode('تعذر حفظ الجرد السنوي')));
        exit;
    }
}
?>
<?php financial_page_start('الجرد السنوي'); ?>

<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;
  }

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

<div class="panel no-print">
  <div class="panel-head">تحديد سنة الجرد</div>
  <div class="panel-body">
    <?php if ($msg !== ''): ?>
      <div class="msg ok"><?= financial_h($msg) ?></div>
    <?php endif; ?>

    <?php if ($err !== ''): ?>
      <div class="msg err"><?= financial_h($err) ?></div>
    <?php endif; ?>

    <form method="get">
      <div class="form-grid">
        <div class="field">
          <label>السنة</label>
          <input class="input" type="number" name="year" min="2000" max="2100" value="<?= (int)$year ?>" required>
        </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"><?= (int)$year ?></div>
  </div>

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

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

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

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

  <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)$branchId === 2 ? 'دبي' : 'أبوظبي' ?></div>
  </div>

  <div class="card">
    <div class="k">نوع الجرد</div>
    <div class="v" style="font-size:20px;">سنوي</div>
  </div>
</div>

<div class="panel">
  <div class="panel-head">ملخص الجرد السنوي</div>
  <div class="panel-body">
    <div style="line-height:2;font-size:15px;">
      <div>الفترة المعتمدة: <?= financial_h($dateFrom) ?> إلى <?= financial_h($dateTo) ?></div>
      <div>إجمالي المدخولات خلال السنة: <?= financial_h(fy_money($totalIncome)) ?></div>
      <div>إجمالي المصروفات خلال السنة: <?= financial_h(fy_money($totalExpenses)) ?></div>
      <div>صافي الربح السنوي: <?= financial_h(fy_money($netProfit)) ?></div>
      <div>نسبة الربحية: <?= financial_h(number_format($profitMargin, 1) . '%') ?></div>
    </div>
  </div>
</div>

<div class="panel no-print">
  <div class="panel-head">حفظ الجرد</div>
  <div class="panel-body">
    <form method="post">
      <div class="actions">
        <button class="btn primary" type="submit" name="save_snapshot" value="1">حفظ / تحديث الجرد السنوي</button>
      </div>
    </form>
  </div>
</div>

<?php financial_page_end(); ?>