<?php
// public/customers.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin']);

$pdo = db();
$title = "Customers - IMS";

function post_str(string $k): string { return trim((string)($_POST[$k] ?? '')); }
function post_int(string $k): int { return (int)($_POST[$k] ?? 0); }

$error = '';
$success = '';

$q = trim((string)($_GET['q'] ?? ''));

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $name = post_str('name');
        $phone = post_str('phone');
        $email = post_str('email');
        $address = post_str('address');

        if ($name === '') {
            $error = "Customer name is required.";
        } else {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO customers (name, phone, email, address)
                    VALUES (:name, :phone, :email, :address)
                ");
                $stmt->execute([
                    ':name' => $name,
                    ':phone' => ($phone !== '' ? $phone : null),
                    ':email' => ($email !== '' ? $email : null),
                    ':address' => ($address !== '' ? $address : null),
                ]);
                $success = "Customer added successfully.";
            } catch (PDOException $e) {
                $error = "Error adding customer: " . $e->getMessage();
            }
        }
    }

    if ($action === 'edit') {
        $id = post_int('id');
        $name = post_str('name');
        $phone = post_str('phone');
        $email = post_str('email');
        $address = post_str('address');

        if ($id <= 0 || $name === '') {
            $error = "Invalid customer data.";
        } else {
            try {
                $stmt = $pdo->prepare("
                    UPDATE customers
                    SET name = :name,
                        phone = :phone,
                        email = :email,
                        address = :address
                    WHERE id = :id
                    LIMIT 1
                ");
                $stmt->execute([
                    ':name' => $name,
                    ':phone' => ($phone !== '' ? $phone : null),
                    ':email' => ($email !== '' ? $email : null),
                    ':address' => ($address !== '' ? $address : null),
                    ':id' => $id
                ]);
                $success = "Customer updated successfully.";
            } catch (PDOException $e) {
                $error = "Error updating customer: " . $e->getMessage();
            }
        }
    }

    if ($action === 'delete') {
        $id = post_int('id');
        if ($id <= 0) {
            $error = "Invalid customer ID.";
        } else {
            try {
                // deliveries.customer_id is typically ON DELETE SET NULL, so safe
                $stmt = $pdo->prepare("DELETE FROM customers WHERE id = :id LIMIT 1");
                $stmt->execute([':id' => $id]);
                $success = "Customer deleted (deliveries linked to this customer become None).";
            } catch (PDOException $e) {
                $error = "Error deleting customer: " . $e->getMessage();
            }
        }
    }
}

// Edit mode (GET)
$edit_id = (int)($_GET['edit'] ?? 0);
$edit_customer = null;

if ($edit_id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $edit_id]);
    $edit_customer = $stmt->fetch();
    if (!$edit_customer) {
        $error = "Customer not found.";
        $edit_id = 0;
    }
}

// List customers
$sql = "SELECT * FROM customers WHERE 1=1 ";
$params = [];

if ($q !== '') {
    $sql .= " AND (name LIKE :q OR phone LIKE :q OR email LIKE :q) ";
    $params[':q'] = '%' . $q . '%';
}

$sql .= " ORDER BY name ASC ";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$customers = $stmt->fetchAll();

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between mb-3">
    <h4 class="mb-0">Customers</h4>

    <form class="d-flex gap-2" method="GET">
      <input class="form-control form-control-sm" name="q" placeholder="Search name/phone/email..." value="<?= htmlspecialchars($q) ?>">
      <button class="btn btn-sm btn-outline-primary" type="submit">Search</button>
      <a class="btn btn-sm btn-outline-secondary" href="customers.php">Reset</a>
    </form>
  </div>

  <?php if ($error !== ''): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <?php if ($success !== ''): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
  <?php endif; ?>

  <div class="row g-3">
    <!-- Add/Edit Form -->
    <div class="col-12 col-lg-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <h5 class="card-title mb-3"><?= $edit_id > 0 ? 'Edit Customer' : 'Add Customer' ?></h5>

          <form method="POST" autocomplete="off">
            <input type="hidden" name="action" value="<?= $edit_id > 0 ? 'edit' : 'add' ?>">
            <?php if ($edit_id > 0): ?>
              <input type="hidden" name="id" value="<?= (int)$edit_customer['id'] ?>">
            <?php endif; ?>

            <div class="mb-2">
              <label class="form-label">Name *</label>
              <input class="form-control" name="name" required value="<?= htmlspecialchars($edit_customer['name'] ?? '') ?>">
            </div>

            <div class="mb-2">
              <label class="form-label">Phone</label>
              <input class="form-control" name="phone" value="<?= htmlspecialchars($edit_customer['phone'] ?? '') ?>">
            </div>

            <div class="mb-2">
              <label class="form-label">Email</label>
              <input class="form-control" type="email" name="email" value="<?= htmlspecialchars($edit_customer['email'] ?? '') ?>">
            </div>

            <div class="mb-3">
              <label class="form-label">Address</label>
              <textarea class="form-control" name="address" rows="3"><?= htmlspecialchars($edit_customer['address'] ?? '') ?></textarea>
            </div>

            <button class="btn btn-primary w-100" type="submit">
              <?= $edit_id > 0 ? 'Save Changes' : 'Add Customer' ?>
            </button>

            <?php if ($edit_id > 0): ?>
              <a class="btn btn-outline-secondary w-100 mt-2" href="customers.php">Cancel</a>
            <?php endif; ?>
          </form>
        </div>
      </div>
    </div>

    <!-- Customer List -->
    <div class="col-12 col-lg-8">
      <div class="card shadow-sm">
        <div class="card-body">
          <h6 class="mb-3">Customer List</h6>

          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Phone</th>
                  <th>Email</th>
                  <th>Address</th>
                  <th style="width:190px;"></th>
                </tr>
              </thead>
              <tbody>
                <?php if (!$customers): ?>
                  <tr><td colspan="5" class="text-muted">No customers found.</td></tr>
                <?php else: ?>
                  <?php foreach ($customers as $c): ?>
                    <tr>
                      <td class="fw-semibold"><?= htmlspecialchars($c['name']) ?></td>
                      <td><?= htmlspecialchars($c['phone'] ?? '-') ?></td>
                      <td><?= htmlspecialchars($c['email'] ?? '-') ?></td>
                      <td class="small"><?= htmlspecialchars($c['address'] ?? '-') ?></td>
                      <td class="text-end">
                        <a class="btn btn-outline-primary btn-sm" href="customers.php?edit=<?= (int)$c['id'] ?>">Edit</a>

                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete this customer?');">
                          <input type="hidden" name="action" value="delete">
                          <input type="hidden" name="id" value="<?= (int)$c['id'] ?>">
                          <button class="btn btn-outline-danger btn-sm" type="submit">Delete</button>
                        </form>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <div class="text-muted small">
            Next: connect Customers to Deliveries better (auto-fill pickup/dropoff, quick “Add Customer” modal).
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
