<?php
declare(strict_types=1);

require_once __DIR__ . '/_layout.php';

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

$id  = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$err = '';

if ($id <= 0) {
    header('Location: ' . financial_u('expenses.php?err=' . urlencode('رقم المصروف غير صحيح')));
    exit;
}

$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 id = ? AND branch_id = ? LIMIT 1");
    $st->execute([$id, $branchId]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $row = null;
}

if (!$row) {
    header('Location: ' . financial_u('expenses.php?err=' . urlencode('المصروف غير موجود')));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title       = trim((string)($_POST['title'] ?? ''));
    $category    = trim((string)($_POST['category'] ?? ''));
    $amount      = (float)($_POST['amount'] ?? 0);
    $expenseDate = trim((string)($_POST['expense_date'] ?? ''));
    $notes       = trim((string)($_POST['notes'] ?? ''));

    if ($title === '' || $category === '' || $amount <= 0 || $expenseDate === '') {
        $err = 'يرجى تعبئة جميع الحقول المطلوبة بشكل صحيح';
    } elseif (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $expenseDate)) {
        $err = 'تاريخ المصروف غير صحيح';
    } else {
        try {
            $newAttachment = null;
            $oldAttachment = (string)($row['attachment_path'] ?? '');

            if ($hasAttachmentPath) {
                if (!empty($_POST['remove_attachment']) && $oldAttachment !== '') {
                    financial_delete_attachment_file($oldAttachment);
                    $oldAttachment = '';
                }

                $uploaded = financial_upload_attachment('attachment', 'expense');
                if ($uploaded !== null) {
                    if ($oldAttachment !== '') {
                        financial_delete_attachment_file($oldAttachment);
                    }
                    $newAttachment = $uploaded;
                } else {
                    $newAttachment = ($oldAttachment !== '' ? $oldAttachment : null);
                }
            }

            $sets = ['title = ?', 'category = ?', 'amount = ?', 'expense_date = ?', 'notes = ?'];
            $params = [$title, $category, $amount, $expenseDate, $notes !== '' ? $notes : null];

            if ($hasAttachmentPath) {
                $sets[] = 'attachment_path = ?';
                $params[] = $newAttachment;
            }

            $params[] = $id;
            $params[] = $branchId;

            $sql = 'UPDATE financial_expenses SET ' . implode(', ', $sets) . ' WHERE id = ? AND branch_id = ?';
            $st = $pdo->prepare($sql);
            $st->execute($params);

            header('Location: ' . financial_u('expenses.php?msg=' . urlencode('تم تحديث المصروف بنجاح')));
            exit;
        } catch (Throwable $e) {
            $err = $e->getMessage() ?: 'تعذر تحديث المصروف';
        }
    }

    $row = array_merge($row, [
        'id'           => $id,
        'title'        => $title,
        'category'     => $category,
        'amount'       => $amount,
        'expense_date' => $expenseDate,
        'notes'        => $notes,
    ]);
}

financial_page_start('تعديل مصروف');

$categories = ['إيجار','رواتب','رسوم حكومية','تسويق','تقنية','مكتبية','مصاريف محاكم','مواصلات','صيانة','برامج','فواتير','تنقل','أخرى'];
?>

<div class="panel">
  <div class="panel-head">تعديل المصروف</div>
  <div class="panel-body">
    <?php if ($err !== ''): ?>
      <div class="msg err"><?= financial_h($err) ?></div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data" action="<?= financial_h(financial_u('expense_edit.php?id=' . (int)$row['id'])) ?>">
      <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

      <div class="form-grid">
        <div class="field">
          <label>عنوان المصروف</label>
          <input class="input" type="text" name="title" value="<?= financial_h((string)$row['title']) ?>" required>
        </div>

        <div class="field">
          <label>التصنيف</label>
          <select class="select" name="category" required>
            <option value="">اختر التصنيف</option>
            <?php foreach ($categories as $category): ?>
              <option value="<?= financial_h($category) ?>" <?= ((string)$row['category'] === $category) ? 'selected' : '' ?>><?= financial_h($category) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="field">
          <label>المبلغ</label>
          <input class="input" type="number" step="0.01" min="0" name="amount" value="<?= financial_h((string)$row['amount']) ?>" required>
        </div>

        <div class="field">
          <label>تاريخ المصروف</label>
          <input class="input" type="date" name="expense_date" value="<?= financial_h((string)$row['expense_date']) ?>" required>
        </div>

        <?php if ($hasAttachmentPath): ?>
          <div class="field" style="grid-column:1/-1;">
            <label>المرفق</label>
            <?php if (!empty($row['attachment_path'])): ?>
              <div class="actions" style="margin-bottom:8px;">
                <a class="btn soft" href="<?= financial_h((string)$row['attachment_path']) ?>" target="_blank">عرض المرفق الحالي</a>
                <label class="btn" style="border-color:#ef4444;color:#fecaca;">
                  <input type="checkbox" name="remove_attachment" value="1" style="margin-inline-end:6px;"> حذف المرفق
                </label>
              </div>
            <?php endif; ?>
            <input class="input" type="file" name="attachment" accept=".pdf,.jpg,.jpeg,.png,.webp">
          </div>
        <?php endif; ?>

        <div class="field" style="grid-column:1/-1;">
          <label>ملاحظات</label>
          <textarea class="textarea" name="notes"><?= financial_h((string)($row['notes'] ?? '')) ?></textarea>
        </div>
      </div>

      <div class="actions" style="margin-top:14px;">
        <button class="btn primary" type="submit">حفظ التعديل</button>
        <a class="btn" href="<?= financial_h(financial_u('expenses.php')) ?>">رجوع</a>
      </div>
    </form>
  </div>
</div>

<?php financial_page_end(); ?>
