<?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('income.php?err=' . urlencode('رقم المدخول غير صحيح')));
    exit;
}

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

try {
    $st = $pdo->prepare("SELECT id, case_id, client_name, service_type, amount, payment_method, income_date, notes{$selectAttachment} FROM financial_income 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('income.php?err=' . urlencode('المدخول غير موجود')));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $clientName    = trim((string)($_POST['client_name'] ?? ''));
    $serviceType   = trim((string)($_POST['service_type'] ?? ''));
    $amount        = (float)($_POST['amount'] ?? 0);
    $paymentMethod = trim((string)($_POST['payment_method'] ?? ''));
    $incomeDate    = trim((string)($_POST['income_date'] ?? ''));
    $caseId        = (int)($_POST['case_id'] ?? 0);
    $notes         = trim((string)($_POST['notes'] ?? ''));

    if ($clientName === '' || $serviceType === '' || $amount <= 0 || $paymentMethod === '' || $incomeDate === '') {
        $err = 'يرجى تعبئة جميع الحقول المطلوبة بشكل صحيح';
    } elseif (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $incomeDate)) {
        $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', 'income');
                if ($uploaded !== null) {
                    if ($oldAttachment !== '') {
                        financial_delete_attachment_file($oldAttachment);
                    }
                    $newAttachment = $uploaded;
                } else {
                    $newAttachment = ($oldAttachment !== '' ? $oldAttachment : null);
                }
            }

            $sets = [
                'case_id = ?',
                'client_name = ?',
                'service_type = ?',
                'amount = ?',
                'payment_method = ?',
                'income_date = ?',
                'notes = ?'
            ];
            $params = [
                $caseId > 0 ? $caseId : null,
                $clientName,
                $serviceType,
                $amount,
                $paymentMethod,
                $incomeDate,
                $notes !== '' ? $notes : null,
            ];

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

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

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

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

    $row = array_merge($row, [
        'id'             => $id,
        'case_id'        => $caseId > 0 ? $caseId : null,
        'client_name'    => $clientName,
        'service_type'   => $serviceType,
        'amount'         => $amount,
        'payment_method' => $paymentMethod,
        'income_date'    => $incomeDate,
        'notes'          => $notes,
    ]);
}

financial_page_start('تعديل مدخول');

$services = ['استشارة قانونية','أتعاب قضية','صياغة عقد','تسجيل شركة','علامة تجارية','خدمة قانونية أخرى'];
$methods = ['نقدي','تحويل بنكي','بطاقة','رابط دفع','cash','bank'];
?>

<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('income_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="client_name" value="<?= financial_h((string)$row['client_name']) ?>" required>
        </div>

        <div class="field">
          <label>نوع الخدمة</label>
          <select class="select" name="service_type" required>
            <option value="">اختر الخدمة</option>
            <?php foreach ($services as $service): ?>
              <option value="<?= financial_h($service) ?>" <?= ((string)$row['service_type'] === $service) ? 'selected' : '' ?>><?= financial_h($service) ?></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>
          <select class="select" name="payment_method" required>
            <?php foreach ($methods as $method): ?>
              <option value="<?= financial_h($method) ?>" <?= ((string)$row['payment_method'] === $method) ? 'selected' : '' ?>><?= financial_h($method) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

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

        <div class="field">
          <label>رقم القضية اختياري</label>
          <input class="input" type="number" name="case_id" min="1" value="<?= financial_h((string)($row['case_id'] ?? '')) ?>">
        </div>

       <?php if ($hasAttachmentPath): ?>
  <div class="field" style="grid-column:1/-1;">
    <label>المرفق</label>

    <?php if (!empty($row['attachment_path'])): ?>
      <div class="attachment-box">

        <a class="btn soft"
           href="<?= financial_h((string)$row['attachment_path']) ?>"
           target="_blank">
          عرض المرفق الحالي
        </a>

        <label class="remove-attachment-label">
          <input type="checkbox"
                 name="remove_attachment"
                 value="1">

          حذف المرفق الحالي
        </label>

      </div>
    <?php endif; ?>

    <input
      class="input"
      type="file"
      name="attachment"
      accept=".pdf,.jpg,.jpeg,.png,.webp"
    >

    <small class="hint">
      عند اختيار ملف جديد سيتم استبدال الملف القديم تلقائياً.
    </small>

  </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('income.php')) ?>">رجوع</a>
      </div>
    </form>
  </div>
</div>
<style>
.attachment-box{
  display:flex;
  align-items:center;
  gap:12px;
  flex-wrap:wrap;
  margin-bottom:10px;
}

.remove-attachment-label{
  display:flex;
  align-items:center;
  gap:6px;
  padding:10px 14px;
  border-radius:12px;
  border:1px solid rgba(239,68,68,.4);
  background:rgba(239,68,68,.08);
  color:#fecaca;
  cursor:pointer;
}

.hint{
  display:block;
  margin-top:8px;
  color:rgba(255,255,255,.65);
  font-size:12px;
}
</style>
<?php financial_page_end(); ?>
