<?php
$adminTitle = 'Invoices';
require_once __DIR__ . '/includes/header.php';

// ── Create invoice (inline form POST) ────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_invoice'])) {
    $custId    = (int)$_POST['customer_id'];
    $taxRate   = (float)($_POST['tax_rate'] ?? 17);
    $discount  = (float)($_POST['discount'] ?? 0);
    $dueDate   = sanitize($_POST['due_date'] ?? '');
    $notes     = sanitize($_POST['notes'] ?? '');
    $terms     = sanitize($_POST['terms'] ?? '');
    $payMethod = sanitize($_POST['payment_method'] ?? '');

    $descriptions = $_POST['descriptions'] ?? [];
    $quantities   = $_POST['quantities'] ?? [];
    $unitPrices   = $_POST['unit_prices'] ?? [];
    $units        = $_POST['units'] ?? [];

    $subtotal = 0;
    $lineItems = [];
    foreach ($descriptions as $i => $desc) {
        if (!trim($desc)) continue;
        $qty   = (float)($quantities[$i] ?? 1);
        $price = (float)($unitPrices[$i] ?? 0);
        $subtotal += $qty * $price;
        $lineItems[] = [$desc, $qty, sanitize($units[$i] ?? 'pcs'), $price, $qty * $price];
    }
    $taxAmount  = ($subtotal - $discount) * $taxRate / 100;
    $grandTotal = $subtotal - $discount + $taxAmount;

    $invNum = generateNumber(setting('invoice_prefix', 'INV-'), 'invoices', 'invoice_number');
    $invId  = Database::insert(
        "INSERT INTO invoices (invoice_number,customer_id,status,subtotal,discount,tax_rate,tax_amount,total,due_date,notes,terms,payment_method) VALUES (?,?,'sent',?,?,?,?,?,?,?,?,?)",
        [$invNum, $custId, $subtotal, $discount, $taxRate, $taxAmount, $grandTotal, $dueDate ?: null, $notes, $terms, $payMethod]
    );
    foreach ($lineItems as [$d,$q,$u,$p,$t]) {
        Database::insert("INSERT INTO invoice_items (invoice_id,description,quantity,unit,unit_price,total_price) VALUES (?,?,?,?,?,?)", [$invId,$d,$q,$u,$p,$t]);
    }
    $_SESSION['flash']['success'] = "Invoice $invNum created.";
    header('Location: /admin/invoices.php'); exit;
}

// ── Update invoice (mark paid etc.) ──────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['invoice_id'])) {
    $invId   = (int)$_POST['invoice_id'];
    $status  = sanitize($_POST['status'] ?? '');
    $paid    = (float)($_POST['amount_paid'] ?? 0);
    $payDate = sanitize($_POST['paid_date'] ?? '');
    $method  = sanitize($_POST['payment_method'] ?? '');
    $prevStatus = Database::fetchOne("SELECT status FROM invoices WHERE id=?", [$invId])['status'] ?? '';
    $milestone = sanitize($_POST['milestone'] ?? 'processed');
    $tracking  = sanitize($_POST['tracking_number'] ?? '');
    
    Database::execute(
        "UPDATE invoices SET status=?, amount_paid=?, paid_date=?, payment_method=?, milestone=?, tracking_number=?, updated_at=NOW() WHERE id=?",
        [$status, $paid, $payDate ?: null, $method, $milestone, $tracking, $invId]
    );
    // Send payment confirmed email when newly marked paid
    if ($status === 'paid' && $prevStatus !== 'paid') {
        $inv  = Database::fetchOne("SELECT i.*, c.email, c.contact_name, c.company_name FROM invoices i LEFT JOIN customers c ON i.customer_id=c.id WHERE i.id=?", [$invId]);
        if ($inv && $inv['email']) {
            sendEmailFromTemplate('invoice_paid', $inv['email'], [
                'customer_name'  => $inv['contact_name'] ?: $inv['company_name'],
                'invoice_number' => $inv['invoice_number'],
                'amount_paid'    => formatPrice($paid ?: $inv['total']),
                'paid_date'      => $payDate ? formatDate($payDate) : date('d M Y'),
            ]);
        }
    }
    $_SESSION['flash']['success'] = 'Invoice updated.';
    header('Location: /admin/invoices.php'); exit;
}

$action    = $_GET['action'] ?? 'list';
$customers = Database::fetchAll("SELECT id, company_name, contact_name FROM customers WHERE status='active' ORDER BY company_name");

// ── Create Invoice Form ───────────────────────────────────────────────────────
if ($action === 'create'): ?>
<div class="flex items-center gap-4 mb-6">
  <a href="/admin/invoices.php" class="text-gray-400 hover:text-white text-sm">← Invoices</a>
  <h2 class="font-semibold">Create New Invoice</h2>
</div>
<form method="POST" class="max-w-4xl">
  <input type="hidden" name="create_invoice" value="1">
  <div class="card-dark p-5 mb-5">
    <h3 class="text-sm font-semibold text-orange-400 mb-4">Invoice Details</h3>
    <div class="grid grid-cols-2 gap-4">
      <div>
        <label class="text-xs text-gray-400 block mb-1.5">Customer *</label>
        <select name="customer_id" required>
          <option value="">Select customer</option>
          <?php foreach ($customers as $c): ?>
          <option value="<?= $c['id'] ?>"><?= e($c['company_name'] ?: $c['contact_name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1.5">Due Date</label>
        <input type="date" name="due_date" value="<?= date('Y-m-d', strtotime('+30 days')) ?>">
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1.5">Tax Rate (%)</label>
        <input type="number" name="tax_rate" value="<?= setting('default_tax_rate', '17') ?>" step="0.01" min="0">
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1.5">Discount (PKR)</label>
        <input type="number" name="discount" value="0" step="0.01" min="0">
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1.5">Payment Method</label>
        <input type="text" name="payment_method" placeholder="Bank transfer, cheque...">
      </div>
    </div>
  </div>

  <div class="card-dark p-5 mb-5">
    <h3 class="text-sm font-semibold text-orange-400 mb-4">Line Items</h3>
    <table class="w-full text-sm mb-3" id="inv-table">
      <thead><tr class="text-xs text-gray-400 border-b border-navy-500">
        <th class="text-left pb-2 pr-2">Description</th>
        <th class="text-left pb-2 pr-2 w-16">Qty</th>
        <th class="text-left pb-2 pr-2 w-16">Unit</th>
        <th class="text-left pb-2 pr-2 w-36">Unit Price (PKR)</th>
        <th class="text-left pb-2 pr-2 w-36">Total</th>
        <th class="w-8"></th>
      </tr></thead>
      <tbody id="inv-rows">
        <tr>
          <td class="pr-2 py-1"><input type="text" name="descriptions[]" required placeholder="Item or service description" class="w-full"></td>
          <td class="pr-2 py-1"><input type="number" name="quantities[]" value="1" min="0.01" step="0.01" class="w-16" onchange="calcRow(this)"></td>
          <td class="pr-2 py-1"><input type="text" name="units[]" value="pcs" class="w-16"></td>
          <td class="pr-2 py-1"><input type="number" name="unit_prices[]" value="0" min="0" step="0.01" class="w-36" onchange="calcRow(this)"></td>
          <td class="pr-2 py-1"><input type="number" name="totals[]" value="0" class="w-36 row-total" readonly style="background:#0f1a2e;color:#6b7280"></td>
          <td></td>
        </tr>
      </tbody>
    </table>
    <button type="button" onclick="addRow()" class="btn-outline text-xs py-1.5 px-3">+ Add Line</button>
  </div>

  <div class="card-dark p-5 mb-5">
    <div class="grid grid-cols-2 gap-4">
      <div>
        <label class="text-xs text-gray-400 block mb-1.5">Terms & Conditions</label>
        <textarea name="terms" rows="3" placeholder="Payment terms..."><?= e(setting('invoice_terms')) ?></textarea>
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1.5">Notes</label>
        <textarea name="notes" rows="3" placeholder="Any notes for the customer..."></textarea>
      </div>
    </div>
  </div>

  <div class="flex gap-3">
    <button type="submit" class="btn-primary">Create Invoice</button>
    <a href="/admin/invoices.php" class="btn-outline">Cancel</a>
  </div>
</form>

<script>
function calcRow(el) {
  const row = el.closest('tr');
  const qty = parseFloat(row.querySelector('[name="quantities[]"]').value) || 0;
  const price = parseFloat(row.querySelector('[name="unit_prices[]"]').value) || 0;
  row.querySelector('.row-total').value = (qty * price).toFixed(2);
}
function addRow() {
  const tbody = document.getElementById('inv-rows');
  const tr = document.createElement('tr');
  tr.innerHTML = `
    <td class="pr-2 py-1"><input type="text" name="descriptions[]" required placeholder="Item description" class="w-full"></td>
    <td class="pr-2 py-1"><input type="number" name="quantities[]" value="1" min="0.01" step="0.01" class="w-16" onchange="calcRow(this)"></td>
    <td class="pr-2 py-1"><input type="text" name="units[]" value="pcs" class="w-16"></td>
    <td class="pr-2 py-1"><input type="number" name="unit_prices[]" value="0" min="0" step="0.01" class="w-36" onchange="calcRow(this)"></td>
    <td class="pr-2 py-1"><input type="number" name="totals[]" value="0" class="w-36 row-total" readonly style="background:#0f1a2e;color:#6b7280"></td>
    <td class="py-1"><button type="button" onclick="this.closest('tr').remove()" style="color:#f87171;background:none;border:none;cursor:pointer;font-size:16px;">✕</button></td>`;
  tbody.appendChild(tr);
}
</script>

<?php
include __DIR__ . '/includes/footer.php';
exit;
endif;

// ── Invoice List ──────────────────────────────────────────────────────────────
$filter = trim($_GET['status'] ?? '');
$params = $filter ? [$filter] : [];
$where  = $filter ? "WHERE i.status=?" : "";
$total  = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM invoices i $where", $params)['c'] ?? 0);
$pag    = paginate($total, ADMIN_PER_PAGE, (int)($_GET['page'] ?? 1), '/admin/invoices.php?' . http_build_query(array_filter(['status'=>$filter])));
$invoices = Database::fetchAll(
    "SELECT i.*, c.contact_name, c.company_name FROM invoices i LEFT JOIN customers c ON i.customer_id=c.id $where ORDER BY i.created_at DESC LIMIT ? OFFSET ?",
    array_merge($params, [$pag['per_page'], $pag['offset']])
);
?>

<div class="flex items-center justify-between mb-6">
  <h2 class="text-lg font-semibold">Invoices (<?= $total ?>)</h2>
  <div class="flex items-center gap-3">
    <?php foreach ([''=>'All','draft'=>'Draft','sent'=>'Sent','paid'=>'Paid','partial'=>'Partial','overdue'=>'Overdue'] as $v=>$l): ?>
    <a href="?<?= $v?'status='.$v:'' ?>" class="text-xs px-3 py-1.5 rounded <?= $filter===$v?'bg-orange-600 text-white':'bg-navy-700 text-gray-300 hover:bg-navy-600' ?>"><?= $l ?></a>
    <?php endforeach; ?>
    <a href="?action=create" class="btn-primary text-sm" style="margin-left:8px;">+ Create Invoice</a>
  </div>
</div>

<div class="card-dark overflow-hidden">
  <table class="data-table">
    <thead><tr><th>Invoice #</th><th>Customer</th><th>Total</th><th>Paid</th><th>Status</th><th>Due Date</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($invoices as $inv): ?>
    <tr>
      <td class="font-mono text-xs text-orange-400"><?= e($inv['invoice_number']) ?></td>
      <td class="text-sm"><?= e($inv['company_name'] ?: $inv['contact_name']) ?></td>
      <td class="text-sm font-semibold"><?= formatPrice($inv['total']) ?></td>
      <td class="text-sm text-green-400"><?= formatPrice($inv['amount_paid'] ?? 0) ?></td>
      <td><?= statusBadge($inv['status']) ?></td>
      <td class="text-xs <?= ($inv['due_date'] && $inv['due_date'] < date('Y-m-d') && $inv['status'] !== 'paid') ? 'text-red-400 font-semibold' : 'text-gray-400' ?>">
        <?= $inv['due_date'] ? formatDate($inv['due_date']) : '—' ?>
      </td>
      <td>
        <button onclick="document.getElementById('pay-<?= $inv['id'] ?>').classList.toggle('hidden')" class="text-xs text-orange-500 hover:underline">Update</button>
        <a href="/admin/certificates.php?invoice_id=<?= $inv['id'] ?>" class="text-xs text-green-400 hover:underline ml-2">🛡️ Vault</a>
        <a href="/admin/invoice-pdf.php?id=<?= $inv['id'] ?>" target="_blank" class="text-xs text-blue-400 hover:underline ml-2">⬇ PDF</a>
      </td>
    </tr>
    <tr id="pay-<?= $inv['id'] ?>" class="hidden">
      <td colspan="7" style="background:#1e2534;padding:16px;">
        <form method="POST" class="flex flex-wrap gap-3 items-end">
          <input type="hidden" name="invoice_id" value="<?= $inv['id'] ?>">
          <div>
            <label class="text-xs text-gray-400 block mb-1">Status</label>
            <select name="status" class="text-sm py-1">
              <?php foreach (['draft','sent','paid','partial','overdue','cancelled'] as $s): ?>
              <option value="<?= $s ?>" <?= $inv['status']===$s?'selected':'' ?>><?= ucfirst($s) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1">Amount Paid (PKR)</label>
            <input type="number" name="amount_paid" value="<?= $inv['amount_paid'] ?? 0 ?>" step="0.01" class="w-36 text-sm py-1">
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1">Paid Date</label>
            <input type="date" name="paid_date" value="<?= $inv['paid_date'] ?? '' ?>" class="text-sm py-1">
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1">Payment Method</label>
            <input type="text" name="payment_method" value="<?= e($inv['payment_method'] ?? '') ?>" placeholder="Bank transfer" class="w-40 text-sm py-1">
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1">Process Milestone</label>
            <select name="milestone" class="text-sm py-1">
                <?php foreach (['processed'=>'Processed','sourcing'=>'Global Sourcing','workshop'=>'Workshop','testing'=>'Technical Testing','dispatched'=>'Dispatched','delivered'=>'Delivered'] as $m=>$l): ?>
                <option value="<?= $m ?>" <?= ($inv['milestone']??'processed')===$m?'selected':'' ?>><?= $l ?></option>
                <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1">Tracking ID</label>
            <input type="text" name="tracking_number" value="<?= e($inv['tracking_number'] ?? '') ?>" placeholder="TRK-000" class="w-24 text-sm py-1">
          </div>
          <button class="btn-primary text-xs py-1.5">Save</button>
          <button type="button" onclick="document.getElementById('pay-<?= $inv['id'] ?>').classList.add('hidden')" class="btn-outline text-xs py-1.5">Cancel</button>
        </form>
      </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($invoices)): ?>
    <tr><td colspan="7" class="text-center text-gray-500 py-8">No invoices yet. <a href="?action=create" class="text-orange-400 hover:underline">Create first invoice →</a></td></tr>
    <?php endif; ?>
    </tbody>
  </table>
</div>
<?= paginationHtml($pag) ?>
<?php include __DIR__ . '/includes/footer.php'; ?>
