<?php
/**
 * Quick invoice creation from PO or standalone
 */
$adminTitle = 'Create Invoice';
require_once __DIR__ . '/includes/header.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $custId   = (int)$_POST['customer_id'];
    $poId     = (int)($_POST['po_id'] ?? 0) ?: null;
    $status   = 'sent';
    $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;
    foreach ($descriptions as $i => $desc) {
        if (!$desc) continue;
        $total = (float)($quantities[$i] ?? 1) * (float)($unitPrices[$i] ?? 0);
        $subtotal += $total;
    }

    $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,po_id,customer_id,status,subtotal,discount,tax_rate,tax_amount,total,due_date,notes,terms,payment_method) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
        [$invNum,$poId,$custId,$status,$subtotal,$discount,$taxRate,$taxAmount,$grandTotal,$dueDate?:null,$notes,$terms,$payMethod]
    );

    foreach ($descriptions as $i => $desc) {
        if (!$desc) continue;
        $qty   = (float)($quantities[$i] ?? 1);
        $price = (float)($unitPrices[$i] ?? 0);
        Database::insert("INSERT INTO invoice_items (invoice_id,description,quantity,unit,unit_price,total_price) VALUES (?,?,?,?,?,?)",
            [$invId, $desc, $qty, sanitize($units[$i] ?? 'pcs'), $price, $qty*$price]);
    }

    // Notify customer
    $cust = Database::fetchOne("SELECT * FROM customers WHERE id=?", [$custId]);
    if ($cust) {
        sendEmailFromTemplate('invoice_sent', $cust['email'], [
            'customer_name'  => $cust['contact_name'],
            'invoice_number' => $invNum,
            'total'          => number_format($grandTotal, 2),
            'due_date'       => $dueDate ? formatDate($dueDate) : 'N/A',
        ]);
    }

    logActivity('admin', $_SESSION['admin_id'], 'Invoice Created', $invNum);
    $_SESSION['flash']['success'] = "Invoice $invNum created and sent to customer.";
    header('Location: /admin/invoices.php');
    exit;
}

$customers = Database::fetchAll("SELECT id, company_name, contact_name FROM customers WHERE status='active' ORDER BY company_name");
?>

<div class="flex items-center gap-4 mb-6">
  <a href="/admin/invoices.php" class="text-gray-400 hover:text-white">← Invoices</a>
  <h2 class="font-semibold">Create Invoice</h2>
</div>

<form method="POST" class="max-w-7xl">
  <div class="grid grid-cols-2 gap-5 mb-5 card-dark p-5">
    <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">
    </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">
    </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 class="card-dark p-5 mb-5">
    <h3 class="font-semibold mb-4 text-sm">Invoice Items</h3>
    <table class="w-full text-sm mb-3">
      <thead><tr class="text-xs text-gray-400"><th class="text-left pb-2">Description</th><th class="text-left pb-2 w-24">Qty</th><th class="text-left pb-2 w-24">Unit</th><th class="text-left pb-2 w-48">Unit Price (PKR)</th><th class="text-left pb-2 w-48">Total</th><th class="w-8"></th></tr></thead>
      <tbody id="inv-items">
        <tr class="inv-item">
          <td class="pr-2"><input type="text" name="descriptions[]" required class="p-2"></td>
          <td class="pr-2"><input type="number" name="quantities[]" value="1" min="0.01" step="0.01" class="w-24 p-2" onchange="calcInvLine(this)"></td>
          <td class="pr-2"><input type="text" name="units[]" value="pcs" class="w-24 p-2"></td>
          <td class="pr-2"><input type="number" name="unit_prices[]" value="0" min="0" step="0.01" class="w-48 p-2" onchange="calcInvLine(this)"></td>
          <td class="pr-2"><input type="number" name="totals[]" value="0" class="w-48 p-2 inv-total" readonly style="background:#0f1a2e"></td>
          <td></td>
        </tr>
      </tbody>
    </table>
    <button type="button" onclick="addInvItem()" class="btn-outline text-xs py-1.5">+ Add Item</button>
  </div>

  <div class="card-dark p-5 mb-5 grid grid-cols-2 gap-4">
    <div><label class="text-xs text-gray-400 block mb-1.5">Terms</label><textarea name="terms" rows="3"><?= 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"></textarea></div>
  </div>

  <button type="submit" class="btn-primary">Create & Send Invoice</button>
</form>

<script>
function calcInvLine(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('.inv-total').value = (qty*price).toFixed(2);
}
function addInvItem() {
  const row = document.createElement('tr');
  row.className='inv-item';
  row.innerHTML=`<td class="pr-2"><input type="text" name="descriptions[]" required class="p-2 w-full"></td><td class="pr-2"><input type="number" name="quantities[]" value="1" min="0.01" step="0.01" class="w-24 p-2" onchange="calcInvLine(this)"></td><td class="pr-2"><input type="text" name="units[]" value="pcs" class="w-24 p-2"></td><td class="pr-2"><input type="number" name="unit_prices[]" value="0" min="0" step="0.01" class="w-48 p-2" onchange="calcInvLine(this)"></td><td class="pr-2"><input type="number" name="totals[]" value="0" class="w-48 p-2 inv-total" readonly style="background:#0f1a2e"></td><td><button type="button" onclick="this.closest('tr').remove()" class="text-red-400">✕</button></td>`;
  document.getElementById('inv-items').appendChild(row);
}
</script>

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