<?php
$pageTitle = 'Customers';
require_once '../includes/functions.php';
requireLogin();
$db = getDB();

$action = $_GET['action'] ?? 'list';
$id     = (int)($_GET['id'] ?? 0);

// ── Handle POST ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fields = ['name','email','phone','address','city','state','pincode','gstin','status'];
    $vals   = [];
    foreach ($fields as $f) $vals[$f] = trim($_POST[$f] ?? '');
    $vals['status'] = $_POST['status'] ?? 'active';

    if (empty($vals['name'])) {
        setFlash('error', 'Customer name is required.');
    } else {
        try {
            if (($_POST['_action'] ?? 'add') === 'add') {
                $stmt = $db->prepare("INSERT INTO customers (name,email,phone,address,city,state,pincode,gstin,status) VALUES (?,?,?,?,?,?,?,?,?)");
                $stmt->execute(array_values($vals));
                setFlash('success', 'Customer added successfully!');
            } elseif ($_POST['_action'] === 'edit') {
                $cid = (int)($_POST['id'] ?? 0);
                $stmt = $db->prepare("UPDATE customers SET name=?,email=?,phone=?,address=?,city=?,state=?,pincode=?,gstin=?,status=? WHERE id=?");
                $stmt->execute([...array_values($vals), $cid]);
                setFlash('success', 'Customer updated!');
            }
        } catch (PDOException $e) {
            $msg = 'Failed to save customer. Please check inputs.';
            if (defined('APP_DEBUG') && APP_DEBUG) {
                $msg .= ' Error: ' . $e->getMessage();
            }
            setFlash('error', $msg);
        }
    }
    header('Location: customers.php');
    exit;
}

// ── Handle Delete ─────────────────────────────────────────────
if ($action === 'delete' && $id) {
    try {
        $db->prepare("DELETE FROM customers WHERE id=?")->execute([$id]);
        setFlash('success', 'Customer deleted.');
    } catch (PDOException $e) {
        setFlash('error', 'Failed to delete customer. They may have linked invoices.');
    }
    header('Location: customers.php');
    exit;
}

// ── List ──────────────────────────────────────────────────────
$search = trim($_GET['search'] ?? '');
$page   = max(1, (int)($_GET['page'] ?? 1));
$where  = 'WHERE 1=1';
$params = [];
if ($search) {
    $where .= ' AND (name LIKE ? OR email LIKE ? OR phone LIKE ?)';
    $params = ["%$search%","%$search%","%$search%"];
}
$result = paginate("SELECT * FROM customers $where ORDER BY created_at DESC", $params, $page);
require_once '../includes/header.php';
?>

<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5">
    <div>
        <h2 class="text-lg font-bold text-slate-800">Customers</h2>
        <p class="text-sm text-slate-400"><?= $result['total'] ?> customers</p>
    </div>
        <button type="button" id="addCustomerBtn" class="btn-primary"><i class="fas fa-plus"></i> Add Customer</button>
        <input type="text" name="search" value="<?= sanitize($search) ?>" placeholder="Search name, email, phone..." class="form-input pl-9">
    </div>
    <button type="submit" class="btn-outline">Search</button>
    <?php if ($search): ?><a href="customers.php" class="btn-outline">Clear</a><?php endif; ?>
</form>

<div class="card overflow-hidden">
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead class="bg-slate-50 border-b border-slate-100">
                <tr>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">#</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Name</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Phone</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Email</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">City</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Status</th>
                    <th class="text-right px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-50">
                <?php if (empty($result['data'])): ?>
                <tr><td colspan="7" class="text-center py-12 text-slate-400">
                    <i class="fas fa-users text-3xl mb-2 block"></i>No customers found.
                </td></tr>
                <?php else: foreach ($result['data'] as $i => $c): ?>
                <tr class="table-row">
                    <td class="px-5 py-3.5 text-slate-400 text-xs"><?= ($page-1)*10 + $i + 1 ?></td>
                    <td class="px-5 py-3.5">
                        <div class="flex items-center gap-3">
                            <div class="w-8 h-8 bg-brand-100 rounded-full flex items-center justify-center text-brand-700 font-bold text-xs">
                                <?= strtoupper(substr($c['name'],0,1)) ?>
                            </div>
                            <div>
                                <div class="font-semibold text-slate-800"><?= sanitize($c['name']) ?></div>
                                <?php if ($c['gstin']): ?><div class="text-xs text-slate-400 font-mono">GSTIN: <?= sanitize($c['gstin']) ?></div><?php endif; ?>
                            </div>
                        </div>
                    </td>
                    <td class="px-5 py-3.5 text-slate-600"><?= sanitize($c['phone'] ?: '—') ?></td>
                    <td class="px-5 py-3.5 text-slate-600"><?= sanitize($c['email'] ?: '—') ?></td>
                    <td class="px-5 py-3.5 text-slate-600"><?= sanitize($c['city'] ?: '—') ?></td>
                    <td class="px-5 py-3.5"><?= statusBadge($c['status']) ?></td>
                    <td class="px-5 py-3.5 text-right">
                        <button class="editCustomerBtn text-brand-600 hover:text-brand-700 font-semibold text-xs mr-3" data-customer="<?= htmlspecialchars(json_encode($c)) ?>">
                            <i class="fas fa-pen mr-1"></i>Edit
                        </button>
                        <form method="POST" action="customers.php?action=delete&id=<?= $c['id'] ?>" class="inline" onsubmit="return confirm('Delete this customer?')">
                            <button type="submit" class="text-red-500 hover:text-red-700 font-semibold text-xs"><i class="fas fa-trash mr-1"></i>Delete</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($result['totalPages'] > 1): ?>
    <div class="px-5 py-4 border-t border-slate-100 flex items-center justify-between">
        <span class="text-xs text-slate-400">Page <?= $page ?> of <?= $result['totalPages'] ?></span>
        <div class="flex gap-2">
            <?php for ($p = 1; $p <= $result['totalPages']; $p++): ?>
            <a href="?page=<?= $p ?>&search=<?= urlencode($search) ?>" class="w-8 h-8 flex items-center justify-center rounded-lg text-xs font-semibold <?= $p == $page ? 'bg-brand-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200' ?>">
                <?= $p ?>
            </a>
            <?php endfor; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Modal -->
<div id="custModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[85vh] overflow-y-auto">
        <div class="flex items-center justify-between p-6 border-b border-slate-100 sticky top-0 bg-white">
            <h3 class="font-bold text-slate-800" id="custModalTitle">Add Customer</h3>
            <button id="custModalCloseBtn" class="text-slate-400 hover:text-slate-600"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST" action="customers.php">
            <input type="hidden" name="_action" id="custAction" value="add">
            <input type="hidden" name="id" id="custId">
            <div class="p-6 space-y-4">
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Customer Name *</label>
                        <input type="text" name="name" id="cName" class="form-input" required placeholder="Full name / Company">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Phone</label>
                        <input type="text" name="phone" id="cPhone" class="form-input" placeholder="+91 9876543210">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Email</label>
                        <input type="email" name="email" id="cEmail" class="form-input" placeholder="email@example.com">
                    </div>
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Address</label>
                        <textarea name="address" id="cAddress" class="form-input" rows="2" placeholder="Street address..."></textarea>
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">City</label>
                        <input type="text" name="city" id="cCity" class="form-input" placeholder="Mumbai">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">State</label>
                        <input type="text" name="state" id="cState" class="form-input" placeholder="Maharashtra">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Pincode</label>
                        <input type="text" name="pincode" id="cPincode" class="form-input" placeholder="400001">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">GSTIN</label>
                        <input type="text" name="gstin" id="cGstin" class="form-input" placeholder="22AAAAA0000A1Z5">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Status</label>
                        <select name="status" id="cStatus" class="form-input">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="px-6 pb-6 flex gap-3 justify-end">
                <button type="button" id="custModalCancelBtn" class="btn-outline">Cancel</button>
                <button type="submit" class="btn-primary">Save Customer</button>
            </div>
        </form>
    </div>
</div>

<script src="<?= $basePath ?>assets/js/customer-modal.js"></script>
<?php if ($action === 'add'): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    openAddCustomer();
});
</script>
<?php endif; ?>

<?php require_once '../includes/footer.php'; ?>
