<?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';
$csrf_token = expense_csrf_token();

/* Full name for employee_name column, mirroring how tasks_employee.php resolves display name */
$emp_name = $username;
if ($stmtN = $conn->prepare("SELECT first_name, last_name FROM users WHERE id = ?")) {
    $stmtN->bind_param("s", $user_id);
    $stmtN->execute();
    if ($rowN = $stmtN->get_result()->fetch_assoc()) {
        $emp_name = trim(($rowN['first_name'] ?? '') . ' ' . ($rowN['last_name'] ?? '')) ?: $username;
    }
    $stmtN->close();
}

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

$errors = [];
$posted_rows = []; // for re-display on validation error

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

    $expense_date = trim($_POST['expense_date'] ?? '');
    $to_date      = trim($_POST['to_date'] ?? '');
    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.';

    $cat_in  = $_POST['category'] ?? [];
    $amt_in  = $_POST['amount'] ?? [];
    $desc_in = $_POST['description'] ?? [];
    $files   = $_FILES['bill_image'] ?? null;
    $allowed_mime = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', 'application/pdf' => 'pdf'];

    $rows_to_insert = [];
    $row_count = max(count($cat_in), count($amt_in));

    for ($i = 0; $i < $row_count; $i++) {
        $cat  = trim($cat_in[$i] ?? '');
        $amt  = trim($amt_in[$i] ?? '');
        $desc = trim($desc_in[$i] ?? '');
        $has_file = $files && !empty($files['name'][$i]);

        /* Skip a fully empty row (happens if the person added a blank row and didn't fill it) */
        if ($cat === '' && $amt === '' && $desc === '' && !$has_file) continue;

        $row_errors = [];
        if ($cat === '' || !in_array($cat, $category_names, true)) $row_errors[] = "Row " . ($i+1) . ": please select a valid category.";
        if (!is_numeric($amt) || (float)$amt <= 0) $row_errors[] = "Row " . ($i+1) . ": please enter a valid amount.";

        $bill_path = null;
        if ($has_file) {
            if ($files['error'][$i] !== UPLOAD_ERR_OK) {
                $row_errors[] = "Row " . ($i+1) . ": bill upload failed.";
            } else {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime  = finfo_file($finfo, $files['tmp_name'][$i]);
                finfo_close($finfo);
                if (!isset($allowed_mime[$mime])) {
                    $row_errors[] = "Row " . ($i+1) . ": bill must be JPG, PNG, WEBP or PDF.";
                } elseif ($files['size'][$i] > 5 * 1024 * 1024) {
                    $row_errors[] = "Row " . ($i+1) . ": bill file must be under 5MB.";
                } else {
                    $dir = __DIR__ . '/uploads/expenses';
                    if (!is_dir($dir)) mkdir($dir, 0755, true);
                    $filename = 'expense_' . $user_id . '_' . time() . '_' . $i . '.' . $allowed_mime[$mime];
                    if (move_uploaded_file($files['tmp_name'][$i], $dir . '/' . $filename)) {
                        $bill_path = 'uploads/expenses/' . $filename;
                    } else {
                        $row_errors[] = "Row " . ($i+1) . ": could not save the uploaded file.";
                    }
                }
            }
        }

        if (!empty($row_errors)) {
            $errors = array_merge($errors, $row_errors);
        } else {
            $rows_to_insert[] = ['category' => $cat, 'amount' => (float)$amt, 'description' => $desc, 'bill' => $bill_path];
        }

        $posted_rows[] = ['category' => $cat, 'amount' => $amt, 'description' => $desc];
    }

    if (empty($rows_to_insert) && empty($errors)) {
        $errors[] = 'Please add at least one category with an amount.';
    }

    if (empty($errors)) {
        $claim_group = 'CG' . $user_id . strtoupper(bin2hex(random_bytes(4)));
        $stmt = $conn->prepare("INSERT INTO expenses (employee_id, employee_name, expense_date, to_date, amount, description, category, bill_image, status, claim_group, created_at) VALUES (?,?,?,?,?,?,?,?,'pending',?,NOW())");
        $inserted = 0;
        $total = 0;
        foreach ($rows_to_insert as $row) {
            $stmt->bind_param("ssssdssss", $user_id, $emp_name, $expense_date, $to_date, $row['amount'], $row['description'], $row['category'], $row['bill'], $claim_group);
            if ($stmt->execute()) { $inserted++; $total += $row['amount']; }
        }
        $stmt->close();

        if ($inserted > 0) {
            set_flash('success', "$inserted claim item(s) submitted for approval — total ₹" . number_format($total, 2) . ".");
            header("Location: expense_claim_list.php");
            exit();
        } else {
            $errors[] = 'Could not save the claim. Please try again.';
        }
    }
}

require_once __DIR__ . '/includes/expense_theme.php';
expense_render_head('New Claim');
expense_render_sidebar_and_topbar('employee', $username, 'expense_claim_add.php', 'New Claim');

/* Ensure at least one blank row renders on first load / after a row-count mismatch */
if (empty($posted_rows)) $posted_rows = [['category'=>'','amount'=>'','description'=>'']];
?>
  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">New Expense Claim</div>
        <div class="page-subtitle">Add one or more categories — bill upload is optional per item</div>
      </div>
      <a href="expense_claim_list.php" class="back-btn"><i class="fas fa-arrow-left" style="font-size:10px"></i> My Claims</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-receipt"></i> Claim Details</div></div>
      <div class="dash-card-body">
        <form method="POST" enctype="multipart/form-data" id="claimForm">
          <input type="hidden" name="csrf" value="<?= h($csrf_token) ?>">

          <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($_POST['expense_date'] ?? date('Y-m-d')) ?>" required onchange="document.getElementById('toDate').min=this.value; if(!document.getElementById('toDate').value) document.getElementById('toDate').value=this.value;">
            </div>
            <div class="form-group">
              <label class="form-label">To Date <span style="font-weight:400;color:var(--muted)">(same as From for a single-day expense)</span></label>
              <input type="date" name="to_date" id="toDate" class="form-control" max="<?= date('Y-m-d') ?>" value="<?= h($_POST['to_date'] ?? date('Y-m-d')) ?>" required>
            </div>
          </div>

          <label class="form-label" style="margin-top:6px">Categories &amp; Amounts</label>
          <div id="itemRows">
            <?php foreach ($posted_rows as $idx => $row): ?>
            <div class="claim-row" style="display:grid;grid-template-columns:1.4fr 1fr 1.6fr 1.4fr auto;gap:10px;align-items:flex-start;margin-bottom:10px;padding:10px;background:var(--bg);border:1px solid var(--border);border-radius:10px">
              <div>
                <select name="category[]" class="form-control row-category" required onchange="recalcTotal()">
                  <option value="">Select category…</option>
                  <?php foreach ($categories as $cat): ?>
                    <option value="<?= h($cat['name']) ?>" <?= ($row['category'] === $cat['name']) ? 'selected' : '' ?>>
                      <?= h($cat['name']) ?><?= $cat['max_amount'] ? ' (max ₹' . number_format($cat['max_amount'],0) . ')' : '' ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div>
                <input type="number" name="amount[]" step="0.01" min="0.01" class="form-control row-amount" placeholder="Amount ₹" value="<?= h($row['amount']) ?>" required oninput="recalcTotal()">
              </div>
              <div>
                <input type="text" name="description[]" class="form-control" placeholder="Note (optional)" value="<?= h($row['description']) ?>">
              </div>
              <div>
                <label class="file-drop" style="display:block;padding:9px;font-size:11px">
                  <i class="fas fa-cloud-arrow-up" style="font-size:14px;margin-bottom:2px"></i>
                  <span class="row-file-label">Bill (optional)</span>
                  <input type="file" name="bill_image[]" accept=".jpg,.jpeg,.png,.webp,.pdf" style="display:none" onchange="this.closest('.claim-row').querySelector('.row-file-label').textContent=this.files[0]?this.files[0].name:'Bill (optional)'">
                </label>
              </div>
              <div>
                <button type="button" class="btn-action btn-danger" style="padding:7px 10px" onclick="removeRow(this)"><i class="fas fa-trash" style="font-size:11px"></i></button>
              </div>
            </div>
            <?php endforeach; ?>
          </div>

          <button type="button" class="btn-action btn-remarks" onclick="addRow()"><i class="fas fa-plus" style="font-size:10px"></i> Add Another Category</button>

          <div style="margin-top:16px;padding:14px 16px;background:#eef2ff;border-radius:10px;display:flex;justify-content:space-between;align-items:center">
            <span style="font-size:13px;font-weight:700;color:var(--ink)">Overall Total</span>
            <span style="font-size:22px;font-weight:700;color:var(--accent)">₹<span id="totalDisplay">0.00</span></span>
          </div>

          <button type="submit" class="btn-action btn-finish" style="margin-top:16px"><i class="fas fa-paper-plane" style="font-size:11px"></i> Submit Claim</button>
        </form>
      </div>
    </div>
  </div>

  <template id="rowTemplate">
    <div class="claim-row" style="display:grid;grid-template-columns:1.4fr 1fr 1.6fr 1.4fr auto;gap:10px;align-items:flex-start;margin-bottom:10px;padding:10px;background:var(--bg);border:1px solid var(--border);border-radius:10px">
      <div>
        <select name="category[]" class="form-control row-category" required onchange="recalcTotal()">
          <option value="">Select category…</option>
          <?php foreach ($categories as $cat): ?>
            <option value="<?= h($cat['name']) ?>"><?= h($cat['name']) ?><?= $cat['max_amount'] ? ' (max ₹' . number_format($cat['max_amount'],0) . ')' : '' ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div><input type="number" name="amount[]" step="0.01" min="0.01" class="form-control row-amount" placeholder="Amount ₹" required oninput="recalcTotal()"></div>
      <div><input type="text" name="description[]" class="form-control" placeholder="Note (optional)"></div>
      <div>
        <label class="file-drop" style="display:block;padding:9px;font-size:11px">
          <i class="fas fa-cloud-arrow-up" style="font-size:14px;margin-bottom:2px"></i>
          <span class="row-file-label">Bill (optional)</span>
          <input type="file" name="bill_image[]" accept=".jpg,.jpeg,.png,.webp,.pdf" style="display:none" onchange="this.closest('.claim-row').querySelector('.row-file-label').textContent=this.files[0]?this.files[0].name:'Bill (optional)'">
        </label>
      </div>
      <div><button type="button" class="btn-action btn-danger" style="padding:7px 10px" onclick="removeRow(this)"><i class="fas fa-trash" style="font-size:11px"></i></button></div>
    </div>
  </template>

  <script>
    function addRow() {
      const tpl = document.getElementById('rowTemplate').content.cloneNode(true);
      document.getElementById('itemRows').appendChild(tpl);
    }
    function removeRow(btn) {
      const rows = document.querySelectorAll('.claim-row');
      if (rows.length <= 1) { alert('At least one category row is required.'); return; }
      btn.closest('.claim-row').remove();
      recalcTotal();
    }
    function recalcTotal() {
      let total = 0;
      document.querySelectorAll('.row-amount').forEach(inp => {
        const v = parseFloat(inp.value);
        if (!isNaN(v)) total += v;
      });
      document.getElementById('totalDisplay').textContent = total.toFixed(2);
    }
    document.addEventListener('DOMContentLoaded', recalcTotal);
  </script>
<?php expense_render_footer_scripts(); ?>