<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('customer_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'add' || $action === 'edit') {
        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name']);
        $phone = trim($_POST['phone']);
        $whatsapp = trim($_POST['whatsapp']);
        $email = trim($_POST['email']);
        $address = trim($_POST['address']);
        $nic = trim($_POST['nic']);
        $status = isset($_POST['status']) ? 1 : 0;

        if (empty($name) || empty($phone)) {
            $_SESSION['error'] = 'Name and phone are required.';
        } else {
            try {
                if ($action === 'add') {
                    $stmt = $pdo->prepare("INSERT INTO customers (name, phone, whatsapp, email, address, nic, status) VALUES (?,?,?,?,?,?,?)");
                    $stmt->execute([$name, $phone, $whatsapp, $email, $address, $nic, $status]);
                    $_SESSION['success'] = 'Customer added successfully.';
                } else {
                    $stmt = $pdo->prepare("UPDATE customers SET name=?, phone=?, whatsapp=?, email=?, address=?, nic=?, status=? WHERE id=?");
                    $stmt->execute([$name, $phone, $whatsapp, $email, $address, $nic, $status, $id]);
                    $_SESSION['success'] = 'Customer updated successfully.';
                }
            } catch (PDOException $e) { $_SESSION['error'] = 'Error: ' . $e->getMessage(); }
        }
        header('Location: customers.php'); exit;
    }
    if ($action === 'delete') {
        $stmt = $pdo->prepare("DELETE FROM customers WHERE id=?");
        $stmt->execute([(int)$_POST['id']]);
        $_SESSION['success'] = 'Customer deleted.';
        header('Location: customers.php'); exit;
    }
}

$customers = $pdo->query("SELECT * FROM customers ORDER BY name")->fetchAll();
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-users me-2"></i>Customers</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#customerModal" onclick="resetCustomerForm()"><i class="fas fa-plus me-1"></i>Add Customer</button>
        </div>
        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?></div><?php endif; ?>
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="customersTable" class="table table-hover datatable">
                        <thead><tr><th>Name</th><th>Phone</th><th>WhatsApp</th><th>Email</th><th>NIC</th><th>Due Balance</th><th>Total Purchases</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php foreach ($customers as $c): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($c['name']) ?></strong></td>
                                <td><?= htmlspecialchars($c['phone']) ?></td>
                                <td><?= htmlspecialchars($c['whatsapp'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($c['email'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($c['nic'] ?? '-') ?></td>
                                <td><span class="badge <?= $c['due_balance'] > 0 ? 'badge-pending' : 'badge-completed' ?>"><?= formatCurrency($c['due_balance']) ?></span></td>
                                <td><?= formatCurrency($c['total_purchases']) ?></td>
                                <td><?= $c['status'] ? '<span class="badge badge-completed">Active</span>' : '<span class="badge badge-cancelled">Inactive</span>' ?></td>
                                <td>
                                    <button class="btn btn-sm btn-info" onclick="editCustomer(<?= htmlspecialchars(json_encode($c)) ?>)"><i class="fas fa-edit"></i></button>
                                    <a href="customer_view.php?id=<?= $c['id'] ?>" class="btn btn-sm btn-success"><i class="fas fa-eye"></i></a>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this customer?');">
                                        <input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= $c['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="customerModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" id="custAction" value="add">
                <input type="hidden" name="id" id="custId" value="0">
                <div class="modal-header"><h5 class="modal-title" id="custModalTitle">Add Customer</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3"><label class="form-label">Name *</label><input type="text" name="name" id="custName" class="form-control" required></div>
                        <div class="col-md-6 mb-3"><label class="form-label">Phone *</label><input type="text" name="phone" id="custPhone" class="form-control" required></div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3"><label class="form-label">WhatsApp</label><input type="text" name="whatsapp" id="custWhatsapp" class="form-control"></div>
                        <div class="col-md-6 mb-3"><label class="form-label">Email</label><input type="email" name="email" id="custEmail" class="form-control"></div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3"><label class="form-label">NIC</label><input type="text" name="nic" id="custNic" class="form-control"></div>
                        <div class="col-md-6 mb-3"><div class="form-check mt-4"><input type="checkbox" name="status" id="custStatus" class="form-check-input" checked><label class="form-check-label">Active</label></div></div>
                    </div>
                    <div class="mb-3"><label class="form-label">Address</label><textarea name="address" id="custAddress" class="form-control" rows="2"></textarea></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetCustomerForm() { $('#custAction').val('add');$('#custId').val(0);$('#custModalTitle').text('Add Customer');$('#custName, #custPhone, #custWhatsapp, #custEmail, #custNic, #custAddress').val('');$('#custStatus').prop('checked',true); }
function editCustomer(c) { $('#custAction').val('edit');$('#custId').val(c.id);$('#custModalTitle').text('Edit: '+c.name);$('#custName').val(c.name);$('#custPhone').val(c.phone);$('#custWhatsapp').val(c.whatsapp);$('#custEmail').val(c.email);$('#custNic').val(c.nic);$('#custAddress').val(c.address);$('#custStatus').prop('checked',c.status==1);$('#customerModal').modal('show'); }
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
