<?php
require_once __DIR__ . '/../includes/functions.php';
require_role('employee');

$user = current_user();
$claim_id = (int)($_GET['id'] ?? $_POST['claim_id'] ?? 0);

$stmt = $pdo->prepare("SELECT * FROM claims WHERE id = ? AND user_id = ?");
$stmt->execute([$claim_id, $user['id']]);
$claim = $stmt->fetch();

if (!$claim || $claim['status'] !== 'needs_correction') {
    $_SESSION['flash_error'] = 'این درخواست قابل ویرایش نیست.';
    header('Location: ' . base_url('employee/history.php'));
    exit;
}

$rows = $pdo->query("SELECT * FROM insurance_rows WHERE is_active = 1 ORDER BY sort_order")->fetchAll();
$row = null;
foreach ($rows as $r) { if ($r['id'] == $claim['row_id']) { $row = $r; break; } }

$doc_stmt = $pdo->prepare("SELECT * FROM claim_documents WHERE claim_id = ?");
$doc_stmt->execute([$claim_id]);
$existingDocs = $doc_stmt->fetchAll();

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $amount = (float)preg_replace('/[^0-9]/', '', $_POST['amount'] ?? '0');
    $description = trim($_POST['description'] ?? '');
    $medical_center = trim($_POST['medical_center'] ?? '');
    $service_date = trim($_POST['service_date'] ?? '');
    $receipt_number = trim($_POST['receipt_number'] ?? '');

    $requiredItems = [];
    if ($row && trim((string)$row['required_documents']) !== '') {
        $requiredItems = array_values(array_filter(array_map('trim', explode("\n", $row['required_documents']))));
    }

    if ($amount <= 0) {
        $error = 'مبلغ درخواستی را به‌درستی وارد کنید.';
    } elseif ($medical_center === '') {
        $error = 'نام مرکز درمانی الزامی است.';
    } elseif ($service_date === '' || !is_jalali_date_not_future($service_date)) {
        $error = 'تاریخ انجام خدمت نامعتبر است یا در آینده است.';
    }

    if (!$error) {
        try {
            $pdo->beginTransaction();

            $stmt2 = $pdo->prepare("
                UPDATE claims
                SET amount_requested = ?, description = ?, medical_center = ?, service_date = ?, receipt_number = ?,
                    status = 'pending', admin_note = NULL, reviewed_at = NULL, reviewed_by = NULL
                WHERE id = ?
            ");
            $stmt2->execute([$amount, $description, $medical_center, $service_date, $receipt_number ?: null, $claim_id]);

            // آپلود مدارک جدید در صورت انتخاب (برای رفع نقص مدارک)
            $docStmt = $pdo->prepare("INSERT INTO claim_documents (claim_id, file_path, original_name, item_label) VALUES (?, ?, ?, ?)");
            if ($requiredItems) {
                foreach ($requiredItems as $idx => $item) {
                    if (empty($_FILES['item_docs']['name'][$idx])) continue;
                    $single = [
                        'name' => $_FILES['item_docs']['name'][$idx],
                        'type' => $_FILES['item_docs']['type'][$idx],
                        'tmp_name' => $_FILES['item_docs']['tmp_name'][$idx],
                        'error' => $_FILES['item_docs']['error'][$idx],
                        'size' => $_FILES['item_docs']['size'][$idx],
                    ];
                    $up = handle_document_upload($single, $claim_id);
                    if ($up) {
                        $docStmt->execute([$claim_id, $up['file_path'], $up['original_name'], $item]);
                    }
                }
            } else {
                $count = count($_FILES['documents']['name'] ?? []);
                for ($i = 0; $i < $count; $i++) {
                    if ($_FILES['documents']['error'][$i] === UPLOAD_ERR_NO_FILE) continue;
                    $single = [
                        'name' => $_FILES['documents']['name'][$i],
                        'type' => $_FILES['documents']['type'][$i],
                        'tmp_name' => $_FILES['documents']['tmp_name'][$i],
                        'error' => $_FILES['documents']['error'][$i],
                        'size' => $_FILES['documents']['size'][$i],
                    ];
                    $up = handle_document_upload($single, $claim_id);
                    if ($up) {
                        $docStmt->execute([$claim_id, $up['file_path'], $up['original_name'], null]);
                    }
                }
            }

            $pdo->commit();
            log_activity($pdo, 'resubmit_claim', 'اصلاح و ارسال مجدد درخواست', $claim_id);
            $_SESSION['flash_success'] = 'درخواست اصلاح‌شده دوباره برای بررسی ارسال شد.';
            header('Location: ' . base_url('employee/history.php'));
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = 'خطا: ' . $e->getMessage();
        }
    }
}

$page_title = 'اصلاح درخواست';
include __DIR__ . '/../includes/header.php';
?>

<h4 class="mb-4">اصلاح درخواست #<?= fa_num($claim['id']) ?></h4>

<div class="alert alert-danger">دلیل بازگشت توسط مدیر: <?= htmlspecialchars($claim['admin_note'] ?? '-') ?></div>
<?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>

<div class="card p-4">
<form method="post" enctype="multipart/form-data" novalidate>
  <?= csrf_field() ?>
  <input type="hidden" name="claim_id" value="<?= $claim['id'] ?>">

  <div class="mb-3">
    <label class="form-label">ردیف درمانی</label>
    <input type="text" class="form-control" value="<?= htmlspecialchars($row['name'] ?? '') ?>" disabled>
  </div>

  <div class="row g-2">
    <div class="col-md-6 mb-3">
      <label class="form-label">مبلغ درخواستی (ریال)</label>
      <input type="text" name="amount" class="form-control money-input" required value="<?= (int)$claim['amount_requested'] ?>">
    </div>
    <div class="col-md-6 mb-3">
      <label class="form-label">نام مرکز درمانی</label>
      <input type="text" name="medical_center" class="form-control" required value="<?= htmlspecialchars($claim['medical_center'] ?? '') ?>">
    </div>
    <div class="col-md-6 mb-3">
      <label class="form-label">تاریخ انجام خدمت (شمسی)</label>
      <input type="text" name="service_date" class="form-control jalali-date-input" required autocomplete="off" value="<?= htmlspecialchars($claim['service_date'] ?? '') ?>">
    </div>
    <div class="col-md-6 mb-3">
      <label class="form-label">شماره فیش/فاکتور (اختیاری)</label>
      <input type="text" name="receipt_number" class="form-control" value="<?= htmlspecialchars($claim['receipt_number'] ?? '') ?>">
    </div>
  </div>

  <div class="mb-3">
    <label class="form-label">توضیحات</label>
    <textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($claim['description'] ?? '') ?></textarea>
  </div>

  <div class="mb-3">
    <label class="form-label">مدارک قبلی</label>
    <?php foreach ($existingDocs as $d): ?>
      <a href="<?= base_url('download.php?id=' . $d['id']) ?>" target="_blank" class="d-block small"><?= icon('paperclip') ?> <?= htmlspecialchars($d['item_label'] ?: $d['original_name']) ?></a>
    <?php endforeach; ?>
  </div>

  <div class="mb-3">
    <label class="form-label">افزودن مدرک جدید (در صورت نیاز به رفع نقص مدارک)</label>
    <?php
    $requiredItems = [];
    if ($row && trim((string)$row['required_documents']) !== '') {
        $requiredItems = array_values(array_filter(array_map('trim', explode("\n", $row['required_documents']))));
    }
    ?>
    <?php if ($requiredItems): ?>
      <div class="row g-2">
        <?php foreach ($requiredItems as $idx => $item): ?>
          <div class="col-md-4 mb-2">
            <label class="form-label small"><?= $idx + 1 ?>. <?= htmlspecialchars($item) ?></label>
            <input type="file" name="item_docs[<?= $idx ?>]" class="form-control form-control-sm" accept=".jpg,.jpeg,.png,.pdf">
          </div>
        <?php endforeach; ?>
      </div>
    <?php else: ?>
      <input type="file" name="documents[]" class="form-control" multiple accept=".jpg,.jpeg,.png,.pdf">
    <?php endif; ?>
  </div>

  <button type="submit" class="btn btn-primary">ذخیره و ارسال مجدد</button>
</form>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
