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

// Handle create/update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id       = (int)($_POST['id'] ?? 0);
    $custId   = (int)($_POST['customer_id'] ?? 0);
    $quoteId  = (int)($_POST['quotation_id'] ?? 0) ?: null;
    $status   = sanitize($_POST['status'] ?? 'draft');
    $taxRate  = (float)($_POST['tax_rate'] ?? 17);
    $discount = (float)($_POST['discount'] ?? 0);
    $validUntil = sanitize($_POST['valid_until'] ?? '');
    $terms    = sanitize($_POST['terms'] ?? '');
    $notes    = sanitize($_POST['notes'] ?? '');

    // Build line items
    $descriptions = $_POST['descriptions'] ?? [];
    $quantities   = $_POST['quantities'] ?? [];
    $units        = $_POST['units'] ?? [];
    $unitPrices   = $_POST['unit_prices'] ?? [];

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

    if ($id > 0) {
        Database::execute("UPDATE estimates SET customer_id=?,status=?,subtotal=?,discount=?,tax_rate=?,tax_amount=?,total=?,terms=?,notes=?,valid_until=?,updated_at=NOW() WHERE id=?",
            [$custId,$status,$subtotal,$discount,$taxRate,$taxAmount,$grandTotal,$terms,$notes,$validUntil?:null,$id]);
        Database::execute("DELETE FROM estimate_items WHERE estimate_id=?", [$id]);
    } else {
        $estNum = generateNumber(setting('estimate_prefix','EST-'), 'estimates', 'estimate_number');
        $id = Database::insert("INSERT INTO estimates (estimate_number,quotation_id,customer_id,status,subtotal,discount,tax_rate,tax_amount,total,terms,notes,valid_until) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
            [$estNum,$quoteId,$custId,$status,$subtotal,$discount,$taxRate,$taxAmount,$grandTotal,$terms,$notes,$validUntil?:null]);
        $_SESSION['flash']['success'] = "Estimate $estNum created.";
    }

    foreach ($lineItems as $item) {
        Database::insert("INSERT INTO estimate_items (estimate_id,description,quantity,unit,unit_price,total_price) VALUES (?,?,?,?,?,?)",
            [$id,$item['desc'],$item['qty'],$item['unit'],$item['price'],$item['total']]);
    }

    if (isset($_POST['send_to_customer'])) {
        Database::execute("UPDATE estimates SET status='sent' WHERE id=?", [$id]);
        $cust = Database::fetchOne("SELECT * FROM customers WHERE id=?", [$custId]);
        if ($cust) {
            $est = Database::fetchOne("SELECT * FROM estimates WHERE id=?", [$id]);
            sendEmailFromTemplate('estimate_sent', $cust['email'], [
                'customer_name' => $cust['contact_name'],
                'estimate_number' => $est['estimate_number'],
                'valid_until' => $est['valid_until'] ? formatDate($est['valid_until']) : 'N/A',
            ]);
        }
    }

    header('Location: /admin/estimates.php');
    exit;
}

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

if ($action === 'create' || $action === 'edit') {
    $est  = $action === 'edit' ? Database::fetchOne("SELECT * FROM estimates WHERE id=?", [(int)$_GET['id']]) : [];
    $estItems = $action === 'edit' ? Database::fetchAll("SELECT * FROM estimate_items WHERE estimate_id=?", [(int)$_GET['id']]) : [];
    $fromQuote = isset($_GET['from_quote']) ? (int)$_GET['from_quote'] : 0;
    $quoteItems = $fromQuote ? Database::fetchAll("SELECT * FROM quotation_items qi LEFT JOIN products p ON qi.product_id=p.id WHERE qi.quotation_id=?", [$fromQuote]) : [];
    ?>
    <div class="flex items-center gap-4 mb-6">
      <a href="/admin/estimates.php" class="text-gray-400 hover:text-white">← Estimates</a>
      <h2 class="font-semibold"><?= $action === 'edit' ? 'Edit Estimate' : 'Create Estimate' ?></h2>
    </div>
    <form method="POST" class="max-w-7xl">
      <input type="hidden" name="id" value="<?= $est['id'] ?? '' ?>">
      <?php if ($fromQuote): ?><input type="hidden" name="quotation_id" value="<?= $fromQuote ?>"><?php endif; ?>
      <div class="grid grid-cols-2 gap-5 mb-6 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'] ?>" <?= ($est['customer_id'] ?? 0) == $c['id'] ? 'selected' : '' ?>><?= e($c['company_name'] ?: $c['contact_name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div>
          <label class="text-xs text-gray-400 block mb-1.5">Status</label>
          <select name="status">
            <?php foreach (['draft','sent','approved','rejected','converted'] as $s): ?>
            <option value="<?= $s ?>" <?= ($est['status'] ?? 'draft')===$s?'selected':'' ?>><?= ucfirst($s) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div>
          <label class="text-xs text-gray-400 block mb-1.5">Tax Rate (%)</label>
          <input type="number" name="tax_rate" value="<?= $est['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="<?= $est['discount'] ?? 0 ?>" step="0.01">
        </div>
        <div>
          <label class="text-xs text-gray-400 block mb-1.5">Valid Until</label>
          <input type="date" name="valid_until" value="<?= $est['valid_until'] ?? date('Y-m-d', strtotime('+30 days')) ?>">
        </div>
      </div>

      <!-- Line Items -->
      <div class="card-dark p-5 mb-5">
        <h3 class="font-semibold mb-4 text-sm">Line Items</h3>
        <table class="w-full text-sm mb-3" id="line-items-table">
          <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</th>
            <th class="text-left pb-2 w-48">Total</th>
            <th class="w-8"></th>
          </tr></thead>
          <tbody id="line-items-body">
          <?php
          $displayItems = !empty($estItems) ? $estItems : (!empty($quoteItems) ? array_map(fn($qi) => ['desc' => $qi['description'] ?? $qi['product_name'], 'qty' => $qi['quantity'] ?? 1, 'unit' => 'pcs', 'price' => 0, 'total' => 0], $quoteItems) : [['desc'=>'','qty'=>1,'unit'=>'pcs','price'=>0,'total'=>0]]);
          foreach ($displayItems as $i => $item): ?>
          <tr class="line-item">
            <td class="pr-2"><input type="text" name="descriptions[]" value="<?= e($item['description'] ?? $item['desc'] ?? '') ?>" placeholder="Item description" required class="p-2"></td>
            <td class="pr-2"><input type="number" name="quantities[]" value="<?= $item['quantity'] ?? $item['qty'] ?? 1 ?>" min="0.01" step="0.01" class="w-24 p-2" onchange="calcLine(this)"></td>
            <td class="pr-2"><input type="text" name="units[]" value="<?= e($item['unit'] ?? 'pcs') ?>" class="w-24 p-2"></td>
            <td class="pr-2"><input type="number" name="unit_prices[]" value="<?= $item['unit_price'] ?? $item['price'] ?? 0 ?>" min="0" step="0.01" class="w-48 p-2" onchange="calcLine(this)"></td>
            <td class="pr-2"><input type="number" name="totals[]" value="<?= $item['total_price'] ?? $item['total'] ?? 0 ?>" class="w-48 p-2 line-total" readonly style="background:#0f1a2e"></td>
            <td><button type="button" onclick="this.closest('tr').remove()" class="text-red-400 hover:text-red-300">✕</button></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        <button type="button" onclick="addLineItem()" 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 & Conditions</label><textarea name="terms" rows="3"><?= e($est['terms'] ?? setting('invoice_terms')) ?></textarea></div>
        <div><label class="text-xs text-gray-400 block mb-1.5">Notes</label><textarea name="notes" rows="3"><?= e($est['notes'] ?? '') ?></textarea></div>
      </div>

      <div class="flex gap-3">
        <button type="submit" class="btn-primary">Save Estimate</button>
        <button type="submit" name="send_to_customer" value="1" class="btn-outline">Save & Send to Customer</button>
        <a href="/admin/estimates.php" class="btn-outline">Cancel</a>
      </div>
    </form>
    <script>
    function calcLine(el) {
      const row = el.closest('tr');
      const qty = parseFloat(row.querySelector('input[name="quantities[]"]').value) || 0;
      const price = parseFloat(row.querySelector('input[name="unit_prices[]"]').value) || 0;
      row.querySelector('.line-total').value = (qty * price).toFixed(2);
    }
    function addLineItem() {
      const row = document.createElement('tr');
      row.className = 'line-item';
      row.innerHTML = `<td class="pr-2"><input type="text" name="descriptions[]" placeholder="Item description" required class="w-full 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="calcLine(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="calcLine(this)"></td><td class="pr-2"><input type="number" name="totals[]" value="0" class="w-48 p-2 line-total" readonly style="background:#0f1a2e"></td><td><button type="button" onclick="this.closest('tr').remove()" class="text-red-400">✕</button></td>`;
      document.getElementById('line-items-body').appendChild(row);
    }
    </script>
    <?php
    include __DIR__ . '/includes/footer.php';
    exit;
}

// List
$total = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM estimates")['c'] ?? 0);
$pag   = paginate($total, ADMIN_PER_PAGE, (int)($_GET['page'] ?? 1), '/admin/estimates.php');
$estimates = Database::fetchAll(
    "SELECT e.*, c.company_name, c.contact_name FROM estimates e LEFT JOIN customers c ON e.customer_id=c.id ORDER BY e.created_at DESC LIMIT ? OFFSET ?",
    [$pag['per_page'], $pag['offset']]
);
?>
<div class="flex items-center justify-between mb-6">
  <h2 class="text-lg font-semibold">Estimates (<?= $total ?>)</h2>
  <a href="?action=create" class="btn-primary text-sm">+ Create Estimate</a>
</div>
<div class="card-dark overflow-hidden">
  <table class="data-table">
    <thead><tr><th>Estimate #</th><th>Customer</th><th>Total</th><th>Tax</th><th>Status</th><th>Valid Until</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($estimates as $est): ?>
    <tr>
      <td class="font-mono text-xs text-orange-400"><?= e($est['estimate_number']) ?></td>
      <td class="text-sm"><?= e($est['company_name'] ?: $est['contact_name']) ?></td>
      <td class="font-semibold text-sm"><?= formatPrice($est['total']) ?></td>
      <td class="text-xs text-gray-400"><?= $est['tax_rate'] ?>%</td>
      <td><?= statusBadge($est['status']) ?></td>
      <td class="text-xs text-gray-400"><?= $est['valid_until'] ? formatDate($est['valid_until']) : '—' ?></td>
      <td class="flex gap-3 items-center">
        <a href="?action=edit&id=<?= $est['id'] ?>" class="text-xs text-orange-500 hover:underline">Edit</a>
        <a href="/admin/estimate-pdf.php?id=<?= $est['id'] ?>" target="_blank" class="text-xs text-blue-400 hover:underline">⬇ PDF</a>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?= paginationHtml($pag) ?>
<?php include __DIR__ . '/includes/footer.php'; ?>
