<?php
declare(strict_types=1);

require_once __DIR__ . '/_layout.php';

$pdo      = financial_db();
$branchId = financial_branch_id();
$msg      = (string)($_GET['msg'] ?? '');
$err      = (string)($_GET['err'] ?? '');

financial_page_start('المصروفات');

$rows = [];

$hasAttachmentPath = financial_has_column($pdo, 'financial_expenses', 'attachment_path');
$selectAttachment  = $hasAttachmentPath ? ', attachment_path' : '';

try {
    $st = $pdo->prepare("
        SELECT id, title, category, amount, expense_date, notes{$selectAttachment}
        FROM financial_expenses
        WHERE branch_id = ?
        ORDER BY expense_date DESC, id DESC
        LIMIT 100
    ");
    $st->execute([$branchId]);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $rows = [];
}
?>

<style>
.fin-upload-box{
  width:100%;
  min-height:48px;
  display:flex;
  align-items:center;
  padding:8px 10px;
  border-radius:14px;
  border:1px dashed rgba(212,175,55,.45);
  background:rgba(255,255,255,.04);
}

.fin-upload-box input[type="file"]{
  width:100%;
  color:rgba(255,255,255,.75);
  cursor:pointer;
}

.fin-upload-box input[type="file"]::file-selector-button{
  border:0;
  background:linear-gradient(135deg,#f8d56b,#d4af37);
  color:#102326;
  padding:9px 14px;
  margin-inline-end:10px;
  border-radius:10px;
  font-weight:900;
  cursor:pointer;
}

.fin-upload-hint{
  display:block;
  margin-top:7px;
  color:rgba(255,255,255,.55);
  font-size:12px;
}

.fin-table-wrap{
  width:100%;
  overflow:hidden;
}

.fin-table{
  width:100%;
  table-layout:auto;
  border-collapse:collapse;
}

.fin-table th,
.fin-table td{
  padding:14px 10px;
  vertical-align:middle;
  white-space:nowrap;
  text-align:center;
}

.fin-table th{
  font-weight:800;
}

.fin-table .notes-cell{
  white-space:normal;
  line-height:1.8;
  max-width:260px;
}

.fin-table .actions-cell{
  width:170px;
}

.fin-table .row-actions{
  display:flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  flex-wrap:wrap;
}

.fin-table .row-actions form{
  margin:0;
}

.fin-table .row-actions .btn,
.fin-table .row-actions button.btn{
  min-width:62px;
  height:38px;
  padding:0 12px;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  border-radius:12px;
}

.fin-table .delete-btn{
  border-color:#ef4444 !important;
  color:#ffb4b4 !important;
}
</style>

<div class="panel">
  <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 action="<?= financial_h(financial_u('expense_save.php')) ?>" method="post" enctype="multipart/form-data">
      <div class="form-grid">

        <div class="field">
          <label>عنوان المصروف</label>
          <input class="input" type="text" name="title" required>
        </div>

        <div class="field">
          <label>التصنيف</label>
          <select class="select" name="category" required>
            <option value="">اختر التصنيف</option>
            <option value="إيجار">إيجار</option>
            <option value="رواتب">رواتب</option>
            <option value="رسوم حكومية">رسوم حكومية</option>
            <option value="تسويق">تسويق</option>
            <option value="تقنية">تقنية</option>
            <option value="مكتبية">مكتبية</option>
            <option value="مصاريف محاكم">مصاريف محاكم</option>
            <option value="مواصلات">مواصلات</option>
            <option value="صيانة">صيانة</option>
            <option value="برامج">برامج</option>
            <option value="فواتير">فواتير</option>
            <option value="تنقل">تنقل</option>
            <option value="أخرى">أخرى</option>
          </select>
        </div>

        <div class="field">
          <label>المبلغ</label>
          <input class="input" type="number" step="0.01" min="0" name="amount" required>
        </div>

        <div class="field">
          <label>تاريخ المصروف</label>
          <input class="input" type="date" name="expense_date" value="<?= financial_h(date('Y-m-d')) ?>" required>
        </div>

        <?php if ($hasAttachmentPath): ?>
          <div class="field">
            <label>إرفاق ملف</label>
            <div class="fin-upload-box">
              <input type="file" name="attachment" accept=".pdf,.jpg,.jpeg,.png,.webp">
            </div>
            <small class="fin-upload-hint">الصيغ المسموحة: PDF, JPG, JPEG, PNG, WEBP</small>
          </div>
        <?php endif; ?>

        <div class="field" style="grid-column:1/-1;">
          <label>ملاحظات</label>
          <textarea class="textarea" name="notes"></textarea>
        </div>

      </div>

      <div class="actions" style="margin-top:14px;">
        <button class="btn primary" type="submit">حفظ المصروف</button>
      </div>
    </form>

  </div>
</div>
<div class="panel">
  <div class="panel-head">استيراد المصروفات من Excel / CSV</div>

  <div class="panel-body">

    <form action="<?= financial_h(financial_u('expense_import.php')) ?>"
          method="post"
          enctype="multipart/form-data">

      <div class="field">
        <label>ملف Excel أو CSV</label>

        <div class="fin-upload-box">
          <input type="file"
                 name="csv_file"
                 accept=".csv,.xlsx,.xls"
                 required>
        </div>

        <small class="fin-upload-hint">
          الصيغ المدعومة: CSV / XLSX / XLS
        </small>
      </div>

      <div class="actions" style="margin-top:14px;">
        <button class="btn primary" type="submit">
          استيراد المصروفات
        </button>
      </div>

    </form>

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

    <div class="fin-table-wrap">
      <table class="fin-table">
        <thead>
          <tr>
            <th>التاريخ</th>
            <th>العنوان</th>
            <th>التصنيف</th>
            <th>المبلغ</th>
            <?php if ($hasAttachmentPath): ?>
              <th>المرفق</th>
            <?php endif; ?>
            <th>الملاحظات</th>
            <th>الإجراءات</th>
          </tr>
        </thead>

        <tbody>
          <?php if (!$rows): ?>
            <tr>
              <td colspan="<?= $hasAttachmentPath ? 7 : 6 ?>">لا توجد مصروفات حتى الآن.</td>
            </tr>
          <?php else: ?>
            <?php foreach ($rows 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(number_format((float)($row['amount'] ?? 0), 2) . ' د.إ') ?></td>

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

                <td class="notes-cell"><?= financial_h((string)($row['notes'] ?? '—')) ?></td>

                <td class="actions-cell">
                  <div class="row-actions">
                    <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('هل أنت متأكد من حذف هذا المصروف؟');">
                      <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                      <button class="btn delete-btn" type="submit">حذف</button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>

      </table>
    </div>

  </div>
</div>

<?php financial_page_end(); ?>