<?php
require_once __DIR__ . '/includes/expense_common.php';
expense_require_role(['employee', 'manager']);
expense_ensure_schema($conn);

$user_id  = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'User';
$claim_id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$csrf_token = expense_csrf_token();

$stmt = $conn->prepare("SELECT * FROM expenses WHERE id = ? AND employee_id = ?");
$stmt->bind_param("is", $claim_id, $user_id);
$stmt->execute();
$claim = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$claim) {
    set_flash('danger', 'Claim not found.');
    header("Location: expense_claim_list.php");
    exit();
}
if ($claim['status'] !== 'pending') {
    set_flash('warning', 'Only pending claims can be edited.');
    header("Location: expense_claim_view.php?id=" . $claim_id);
    exit();
}

$categories = [];
if ($resC = $conn->query("SELECT name, max_amount FROM expense_categories WHERE active = 1 ORDER BY name")) {
    $categories = $resC->fetch_all(MYSQLI_ASSOC);
}

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!expense_csrf_valid()) {
        set_flash('danger', 'Invalid request.');
        header("Location: expense_claim_edit.php?id=" . $claim_id);
        exit();
    }

    $expense_date = trim($_POST['expense_date'] ?? '');
    $to_date      = trim($_POST['to_date'] ?? '');
    $amount       = trim($_POST['amount'] ?? '');
    $category     = trim($_POST['category'] ?? '');
    $description  = trim($_POST['description'] ?? '');

    if ($to_date === '') $to_date = $expense_date;

    if ($expense_date === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $expense_date)) $errors[] = 'Please provide a valid "from" date.';
    if ($to_date === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $to_date)) $errors[] = 'Please provide a valid "to" date.';
    if ($expense_date !== '' && $expense_date > date('Y-m-d')) $errors[] = '"From" date cannot be in the future.';
    if ($to_date !== '' && $to_date > date('Y-m-d')) $errors[] = '"To" date cannot be in the future.';
    if ($expense_date !== '' && $to_date !== '' && $to_date < $expense_date) $errors[] = '"To" date cannot be before the "from" date.';
    if (!is_numeric($amount) || (float)$amount <= 0) $errors[] = 'Please provide a valid amount.';
    if ($category === '') $errors[] = 'Please select a category.';
    if ($description === '') $errors[] = 'Please provide a short description.';

    $bill_path = $claim['bill_image'];
    if (!empty($_FILES['bill_image']['name'])) {
        $file = $_FILES['bill_image'];
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = 'Bill upload failed. Please try again.';
        } else {
            $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', 'application/pdf' => 'pdf'];
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime  = finfo_file($finfo, $file['tmp_name']);
            finfo_close($finfo);
            if (!isset($allowed[$mime])) {
                $errors[] = 'Bill must be a JPG, PNG, WEBP or PDF file.';
            } elseif ($file['size'] > 5 * 1024 * 1024) {
                $errors[] = 'Bill file must be under 5MB.';
            } else {
                $dir = __DIR__ . '/uploads/expenses';
                if (!is_dir($dir)) mkdir($dir, 0755, true);
                $filename = 'expense_' . $user_id . '_' . time() . '.' . $allowed[$mime];
                if (move_uploaded_file($file['tmp_name'], $dir . '/' . $filename)) {
                    $bill_path = 'uploads/expenses/' . $filename;
                } else {
                    $errors[] = 'Could not save the uploaded file.';
                }
            }
        }
    }

    if (empty($errors)) {
        $stmt = $conn->prepare("UPDATE expenses SET expense_date=?, to_date=?, amount=?, category=?, description=?, bill_image=?, updated_at=NOW() WHERE id=? AND employee_id=? AND status='pending'");
        $stmt->bind_param("ssdsssis", $expense_date, $to_date, $amount, $category, $description, $bill_path, $claim_id, $user_id);
        if ($stmt->execute()) {
            set_flash('success', 'Claim updated.');
            $stmt->close();
            header("Location: expense_claim_view.php?id=" . $claim_id);
            exit();
        } else {
            $errors[] = 'Database error: ' . $stmt->error;
        }
        $stmt->close();
    }
    // repopulate for redisplay on error
    $claim = array_merge($claim, ['expense_date'=>$expense_date,'to_date'=>$to_date,'amount'=>$amount,'category'=>$category,'description'=>$description,'bill_image'=>$bill_path]);
}

require_once __DIR__ . '/includes/expense_theme.php';
expense_render_head('Edit Claim');
expense_render_sidebar_and_topbar('employee', $username, 'expense_claim_list.php', 'Edit Claim #' . $claim_id);
?>
  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">Edit Claim #<?= (int)$claim_id ?></div>
        <div class="page-subtitle">Only pending claims can be edited</div>
      </div>
      <a href="expense_claim_view.php?id=<?= (int)$claim_id ?>" class="back-btn"><i class="fas fa-arrow-left" style="font-size:10px"></i> View Claim</a>
    </div>

    <?php if (!empty($errors)): ?>
      <div class="alert-custom alert-danger-custom">
        <i class="fas fa-exclamation-circle" style="margin-top:1px;flex-shrink:0"></i>
        <span><?= h(implode(' ', $errors)) ?></span>
      </div>
    <?php endif; ?>

    <div class="dash-card">
      <div class="dash-card-header"><div class="dash-card-title"><i class="fas fa-pen"></i> Edit Details</div></div>
      <div class="dash-card-body">
        <form method="POST" enctype="multipart/form-data">
          <input type="hidden" name="csrf" value="<?= h($csrf_token) ?>">
          <input type="hidden" name="id" value="<?= (int)$claim_id ?>">
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">From Date</label>
              <input type="date" name="expense_date" id="fromDate" class="form-control" max="<?= date('Y-m-d') ?>" value="<?= h($claim['expense_date']) ?>" required onchange="document.getElementById('toDate').min=this.value;">
            </div>
            <div class="form-group">
              <label class="form-label">To Date</label>
              <input type="date" name="to_date" id="toDate" class="form-control" max="<?= date('Y-m-d') ?>" value="<?= h($claim['to_date'] ?? $claim['expense_date']) ?>" required>
            </div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">Amount (₹)</label>
              <input type="number" name="amount" step="0.01" min="0.01" class="form-control" value="<?= h($claim['amount']) ?>" required>
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">Category</label>
            <select name="category" class="form-control" required>
              <?php foreach ($categories as $cat): ?>
                <option value="<?= h($cat['name']) ?>" <?= ($claim['category'] === $cat['name']) ? 'selected' : '' ?>><?= h($cat['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Description</label>
            <textarea name="description" class="form-control" rows="3" required><?= h($claim['description']) ?></textarea>
          </div>
          <div class="form-group">
            <label class="form-label">Bill / Receipt</label>
            <?php if (!empty($claim['bill_image'])): ?>
              <div style="margin-bottom:8px"><img src="<?= h($claim['bill_image']) ?>" style="max-width:160px;border-radius:8px;border:1px solid var(--border)"></div>
            <?php endif; ?>
            <label class="file-drop" style="display:block">
              <i class="fas fa-cloud-arrow-up"></i>
              <span id="fileLabel">Click to replace file (optional)</span>
              <input type="file" name="bill_image" accept=".jpg,.jpeg,.png,.webp,.pdf" style="display:none" onchange="document.getElementById('fileLabel').textContent=this.files[0]?this.files[0].name:'Click to replace file (optional)'">
            </label>
          </div>
          <button type="submit" class="btn-action btn-finish" style="margin-top:6px"><i class="fas fa-save" style="font-size:11px"></i> Save Changes</button>
        </form>
      </div>
    </div>
  </div>
<?php expense_render_footer_scripts(); ?>