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

// ── Toggle active/inactive ────────────────────────────────────────────────────
if (isset($_GET['toggle'], $_GET['id'])) {
    $cust = Database::fetchOne("SELECT status FROM customers WHERE id=?", [(int)$_GET['id']]);
    $new  = $cust['status'] === 'active' ? 'inactive' : 'active';
    Database::execute("UPDATE customers SET status=? WHERE id=?", [$new, (int)$_GET['id']]);
    $_SESSION['flash']['success'] = 'Customer status updated.';
    header('Location: /admin/customers.php'); exit;
}

// ── Delete ────────────────────────────────────────────────────────────────────
if (isset($_GET['delete'], $_GET['id'])) {
    Database::execute("DELETE FROM customers WHERE id=?", [(int)$_GET['id']]);
    $_SESSION['flash']['success'] = 'Customer deleted.';
    header('Location: /admin/customers.php'); exit;
}

// ── Create / Edit POST ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id          = (int)($_POST['id'] ?? 0);
    $company     = sanitize($_POST['company_name'] ?? '');
    $contact     = sanitize($_POST['contact_name'] ?? '');
    $email       = sanitize($_POST['email'] ?? '');
    $phone       = sanitize($_POST['phone'] ?? '');
    $address     = sanitize($_POST['address'] ?? '');
    $city        = sanitize($_POST['city'] ?? '');
    $ntn         = sanitize($_POST['ntn_number'] ?? '');
    $gst         = sanitize($_POST['gst_number'] ?? '');
    $industry    = sanitize($_POST['industry'] ?? '');
    $status      = sanitize($_POST['status'] ?? 'active');
    $password    = trim($_POST['password'] ?? '');

    if ($id > 0) {
        // Edit existing
        try {
            Database::execute(
                "UPDATE customers SET company_name=?, contact_name=?, email=?, phone=?, address=?, city=?, ntn=?, gst_number=?, industry=?, status=? WHERE id=?",
                [$company, $contact, $email, $phone, $address, $city, $ntn, $gst, $industry, $status, $id]
            );
            $_SESSION['flash']['success'] = "Customer updated.";
        } catch (\Exception $e) {
            error_log('Customer update error: ' . $e->getMessage());
            $_SESSION['flash']['error'] = 'Save failed: ' . htmlspecialchars($e->getMessage());
            header('Location: ?action=edit&id=' . $id); exit;
        }
    } else {
        // Create new
        if (!$email) { $_SESSION['flash']['error'] = 'Email is required.'; header('Location: ?action=create'); exit; }
        $plainPass = ucfirst(substr(str_word_count('rig dig api valve pipe flange seal pump gear bolt', 1)[array_rand(str_word_count('rig dig api valve pipe flange seal pump gear bolt', 1))], 0)) . rand(100,999) . '!';
        $hash = password_hash($plainPass, PASSWORD_BCRYPT);
        try {
            Database::insert(
                "INSERT INTO customers (company_name,contact_name,email,phone,address,city,ntn,gst_number,industry,status,password) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
                [$company, $contact, $email, $phone, $address, $city, $ntn, $gst, $industry, $status, $hash]
            );
            // Send welcome email with portal credentials
            sendEmailFromTemplate('welcome', $email, [
                'customer_name' => $contact ?: $company,
                'email'         => $email,
                'temp_password' => $plainPass,
            ]);
            $_SESSION['flash']['success'] = "Customer '$contact' added. Welcome email sent.";
        } catch (\Exception $e) {
            error_log('Customer insert error: ' . $e->getMessage());
            $_SESSION['flash']['error'] = 'Save failed: ' . htmlspecialchars($e->getMessage());
            header('Location: ?action=create'); exit;
        }
    }
    header('Location: /admin/customers.php'); exit;
}

$action = $_GET['action'] ?? 'list';

// ── Create / Edit Form ────────────────────────────────────────────────────────
if ($action === 'create' || $action === 'edit') {
    $c = ($action === 'edit') ? Database::fetchOne("SELECT * FROM customers WHERE id=?", [(int)($_GET['id'] ?? 0)]) : [];
    ?>
    <div class="flex items-center gap-4 mb-6">
      <a href="/admin/customers.php" class="text-gray-400 hover:text-white text-sm">← Customers</a>
      <h2 class="font-semibold"><?= $action === 'edit' ? 'Edit Customer' : 'Add New Customer' ?></h2>
    </div>
    <form method="POST" class="max-w-3xl">
      <input type="hidden" name="id" value="<?= $c['id'] ?? '' ?>">
      <div class="card-dark p-6 mb-5">
        <h3 class="text-sm font-semibold text-orange-400 mb-4">Company & Contact</h3>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="text-xs text-gray-400 block mb-1.5">Company Name</label>
            <input type="text" name="company_name" value="<?= e($c['company_name'] ?? '') ?>" placeholder="Acme Corp">
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1.5">Contact Person *</label>
            <input type="text" name="contact_name" value="<?= e($c['contact_name'] ?? '') ?>" required>
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1.5">Email *</label>
            <input type="email" name="email" value="<?= e($c['email'] ?? '') ?>" required>
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1.5">Phone</label>
            <input type="text" name="phone" value="<?= e($c['phone'] ?? '') ?>" placeholder="+92 300 0000000">
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1.5">Industry</label>
            <select name="industry">
              <option value="">Select industry</option>
              <?php foreach (['Oil & Gas','Mining','Construction','Agriculture','Manufacturing','Transport','Government','Other'] as $ind): ?>
              <option value="<?= $ind ?>" <?= ($c['industry'] ?? '')===$ind?'selected':'' ?>><?= $ind ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1.5">Status</label>
            <select name="status">
              <option value="active" <?= ($c['status'] ?? 'active')==='active'?'selected':'' ?>>Active</option>
              <option value="inactive" <?= ($c['status'] ?? '')==='inactive'?'selected':'' ?>>Inactive</option>
            </select>
          </div>
        </div>
      </div>

      <div class="card-dark p-6 mb-5">
        <h3 class="text-sm font-semibold text-orange-400 mb-4">Address</h3>
        <div class="grid grid-cols-2 gap-4">
          <div class="col-span-2">
            <label class="text-xs text-gray-400 block mb-1.5">Street Address</label>
            <input type="text" name="address" value="<?= e($c['address'] ?? '') ?>">
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1.5">City</label>
            <input type="text" name="city" value="<?= e($c['city'] ?? '') ?>">
          </div>
        </div>
      </div>

      <div class="card-dark p-6 mb-5">
        <h3 class="text-sm font-semibold text-orange-400 mb-4">Tax / Legal Numbers</h3>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="text-xs text-gray-400 block mb-1.5">NTN Number</label>
            <input type="text" name="ntn_number" value="<?= e($c['ntn'] ?? '') ?>" placeholder="1234567-8">
          </div>
          <div>
            <label class="text-xs text-gray-400 block mb-1.5">GST/STRN Number</label>
            <input type="text" name="gst_number" value="<?= e($c['gst_number'] ?? '') ?>" placeholder="12-34-5678-001-56">
          </div>
        </div>
      </div>

      <div class="flex gap-3">
        <button type="submit" class="btn-primary"><?= $action === 'edit' ? 'Save Changes' : 'Create Customer' ?></button>
        <a href="/admin/customers.php" class="btn-outline">Cancel</a>
      </div>
    </form>
    <?php
    include __DIR__ . '/includes/footer.php';
    exit;
}

// ── List ──────────────────────────────────────────────────────────────────────
$search = trim($_GET['q'] ?? '');
$params = $search ? ["%$search%", "%$search%", "%$search%"] : [];
$where  = $search ? "WHERE company_name LIKE ? OR contact_name LIKE ? OR email LIKE ?" : "";
$total  = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM customers $where", $params)['c'] ?? 0);
$pag    = paginate($total, ADMIN_PER_PAGE, (int)($_GET['page'] ?? 1), '/admin/customers.php?' . http_build_query(array_filter(['q'=>$search])));
$customers = Database::fetchAll(
    "SELECT * FROM customers $where ORDER BY 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">Customers (<?= $total ?>)</h2>
  <a href="?action=create" class="btn-primary text-sm">+ Add Customer</a>
</div>

<form method="GET" class="mb-4 flex gap-3">
  <input type="text" name="q" value="<?= e($search) ?>" placeholder="Search by name, company, email..." class="max-w-xs">
  <button class="btn-outline text-sm">Search</button>
  <?php if ($search): ?><a href="/admin/customers.php" class="btn-outline text-sm">Clear</a><?php endif; ?>
</form>

<div class="card-dark overflow-hidden">
  <table class="data-table">
    <thead><tr><th>Company</th><th>Contact</th><th>Email</th><th>Phone</th><th>Industry</th><th>Status</th><th>Joined</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($customers as $c): ?>
    <tr>
      <td class="font-medium text-sm"><?= e($c['company_name'] ?: '—') ?></td>
      <td class="text-sm"><?= e($c['contact_name']) ?></td>
      <td class="text-xs"><?= e($c['email']) ?></td>
      <td class="text-xs"><?= e($c['phone'] ?? '—') ?></td>
      <td class="text-xs text-gray-400"><?= e($c['industry'] ?? '—') ?></td>
      <td><?= statusBadge($c['status']) ?></td>
      <td class="text-xs text-gray-400"><?= formatDate($c['created_at']) ?></td>
      <td>
        <div class="flex gap-2 flex-wrap">
          <a href="?action=edit&id=<?= $c['id'] ?>" class="text-xs text-orange-500 hover:underline">Edit</a>
          <a href="?toggle=1&id=<?= $c['id'] ?>" class="text-xs <?= $c['status']==='active'?'text-yellow-400':'text-green-400' ?> hover:underline"><?= $c['status']==='active'?'Disable':'Enable' ?></a>
          <a href="/admin/quotes.php?customer=<?= $c['id'] ?>" class="text-xs text-blue-400 hover:underline">Quotes</a>
          <a href="?delete=1&id=<?= $c['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Delete this customer?')">Delete</a>
        </div>
      </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($customers)): ?>
    <tr><td colspan="8" class="text-center text-gray-500 py-8">No customers found. <a href="?action=create" class="text-orange-400 hover:underline">Add the first one →</a></td></tr>
    <?php endif; ?>
    </tbody>
  </table>
</div>
<?= paginationHtml($pag) ?>
<?php include __DIR__ . '/includes/footer.php'; ?>
