<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request token.');
        header('Location: sale_vendors.php'); exit;
    }

    $data = [
        'company_name'   => trim($_POST['company_name'] ?? ''),
        'customer_name' => trim($_POST['customer_name']),
        'contact_person' => trim($_POST['contact_person']),
        'phone' => trim($_POST['phone']),
        'alt_phone' => trim($_POST['alt_phone']),
        'email' => trim($_POST['email']),
        'gst_number' => trim($_POST['gst_number']),
        'billing_address' => trim($_POST['billing_address']),
        'shipping_address' => trim($_POST['shipping_address']),
        'city' => trim($_POST['city']),
        'state' => trim($_POST['state']),
        'pincode' => trim($_POST['pincode']),
        'credit_limit' => (float)($_POST['credit_limit'] ?? 0),
        'opening_balance' => (float)($_POST['opening_balance'] ?? 0),
        'notes' => trim($_POST['notes']),
    ];

    if ($_POST['action'] === 'create') {
        $count = $pdo->query("SELECT COUNT(*) c FROM sale_vendors")->fetch()['c'] + 1;
        $data['customer_code'] = 'CUST' . str_pad($count, 4, '0', STR_PAD_LEFT);

        $stmt = $pdo->prepare("INSERT INTO sale_vendors
            (customer_code, company_name, customer_name, contact_person, phone, alt_phone, email, gst_number, billing_address, shipping_address, city, state, pincode, credit_limit, opening_balance, notes)
            VALUES (:customer_code,:company_name,:customer_name,:contact_person,:phone,:alt_phone,:email,:gst_number,:billing_address,:shipping_address,:city,:state,:pincode,:credit_limit,:opening_balance,:notes)");
        $stmt->execute($data);
        setFlash('success', 'Customer created successfully.');

    } elseif ($_POST['action'] === 'update') {
        $data['id'] = (int)$_POST['id'];
        $stmt = $pdo->prepare("UPDATE sale_vendors SET
            company_name=:company_name, customer_name=:customer_name, contact_person=:contact_person, phone=:phone, alt_phone=:alt_phone,
            email=:email, gst_number=:gst_number, billing_address=:billing_address, shipping_address=:shipping_address,
            city=:city, state=:state, pincode=:pincode, credit_limit=:credit_limit, opening_balance=:opening_balance, notes=:notes
            WHERE id=:id");
        $stmt->execute($data);
        setFlash('success', 'Customer updated successfully.');
    }
    header('Location: sale_vendors.php');
    exit;
}

if (isset($_GET['action']) && $_GET['action'] === 'toggle' && isset($_GET['id'])) {
    $pdo->prepare("UPDATE sale_vendors SET status = 1 - status WHERE id = ?")->execute([(int)$_GET['id']]);
    setFlash('success', 'Customer status updated.');
    header('Location: sale_vendors.php'); exit;
}
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $check = $pdo->prepare("SELECT COUNT(*) c FROM quotations WHERE customer_id = ?");
    $check->execute([$id]);
    if ($check->fetch()['c'] > 0) {
        setFlash('danger', 'Cannot delete: customer has quotation/sales records. Deactivate instead.');
    } else {
        $pdo->prepare("DELETE FROM sale_vendors WHERE id = ?")->execute([$id]);
        setFlash('success', 'Customer deleted successfully.');
    }
    header('Location: sale_vendors.php'); exit;
}

$search = trim($_GET['search'] ?? '');
$where = '';
$params = [];
if ($search) {
    $where = "WHERE customer_name LIKE ? OR customer_code LIKE ? OR phone LIKE ? OR email LIKE ?";
    $params = ["%$search%","%$search%","%$search%","%$search%"];
}
$stmt = $pdo->prepare("SELECT * FROM sale_vendors $where ORDER BY id DESC");
$stmt->execute($params);
$customers = $stmt->fetchAll();

$editCustomer = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM sale_vendors WHERE id = ?");
    $stmt->execute([(int)$_GET['edit']]);
    $editCustomer = $stmt->fetch();
}

$csrf = generateCSRFToken();

// All logic/redirects above are done - safe to render layout now
$pageTitle = 'Sale Customers';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Parties</div>
        <h2 class="mb-0">Sale Customers</h2>
    </div>
    <div class="flex gap-8">
        <form method="GET" class="flex gap-8">
            <input type="text" name="search" placeholder="Search customers..." value="<?= sanitize($search) ?>" style="width:220px">
            <button class="btn btn-icon" title="Search" style="width:38px;height:38px;"><?= icon('search') ?></button>
        </form>
        <button class="btn btn-primary" onclick="openCustomerModal()"><?= icon('plus') ?> Add Customer</button>
    </div>
</div>

<div class="card">
    <?php if ($customers): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Code</th><th>Customer Name</th><th>Contact</th><th>Phone</th><th>Email</th>
                    <th>GST No.</th><th>City</th><th class="text-right">Credit Limit</th><th>Status</th><th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($customers as $c): ?>
            <tr>
                <td class="mono"><?= sanitize($c['customer_code']) ?></td>
                <td><strong><?= sanitize($c['customer_name']) ?></strong></td>
                <td><?= sanitize($c['contact_person']) ?: '-' ?></td>
                <td><?= sanitize($c['phone']) ?></td>
                <td><?= sanitize($c['email']) ?></td>
                <td class="mono"><?= sanitize($c['gst_number']) ?: '-' ?></td>
                <td><?= sanitize($c['city']) ?: '-' ?></td>
                <td class="num"><?= formatMoney($c['credit_limit']) ?></td>
                <td><span class="badge badge-<?= $c['status']?'success':'muted' ?>"><?= $c['status']?'Active':'Inactive' ?></span></td>
                <td>
                    <div class="flex gap-8">
                        <button class="btn btn-icon btn-sm" title="Edit" onclick='editCustomer(<?= json_encode($c) ?>)'><?= icon('edit') ?></button>
                        <a href="?action=toggle&id=<?= $c['id'] ?>" class="btn btn-icon btn-sm" title="Toggle Status"><?= icon('power') ?></a>
                        <a href="?action=delete&id=<?= $c['id'] ?>" class="btn btn-icon btn-sm" title="Delete" onclick="return confirm('Delete this customer permanently?')"><?= icon('trash') ?></a>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('users') ?>No customers yet. Click "Add Customer" to create one.</div>
    <?php endif; ?>
</div>

<!-- Customer Modal -->
<div class="modal-backdrop" id="customerModal">
    <div class="modal modal-lg">
        <div class="modal-header">
            <h2 id="modalTitle">Add Customer</h2>
            <button class="btn btn-icon" onclick="closeCustomerModal()"><?= icon('x') ?></button>
        </div>
        <form method="POST" id="customerForm">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" id="formAction" value="create">
            <input type="hidden" name="id" id="customerId">

            <fieldset>
                <legend>Basic Details</legend>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Company Name</label>
                        <input type="text" name="company_name" id="company_name" placeholder="Registered company name">
                    </div>
                    <div class="form-group">
                        <label>Customer Name <span class="req">*</span></label>
                        <input type="text" name="customer_name" id="customer_name" required>
                    </div>
                    <div class="form-group">
                        <label>Contact Person</label>
                        <input type="text" name="contact_person" id="contact_person">
                    </div>
                    <div class="form-group">
                        <label>Phone <span class="req">*</span></label>
                        <input type="tel" name="phone" id="phone" required>
                        <div class="text-sm text-faint">Used for delivery/communication.</div>
                    </div>
                    <div class="form-group">
                        <label>Alternate Phone</label>
                        <input type="tel" name="alt_phone" id="alt_phone">
                    </div>
                    <div class="form-group">
                        <label>Email <span class="req">*</span></label>
                        <input type="email" name="email" id="email" required>
                        <div class="text-sm text-faint">Quotations & invoices auto-emailed here.</div>
                    </div>
                    <div class="form-group">
                        <label>GST Number</label>
                        <input type="text" name="gst_number" id="gst_number">
                    </div>
                </div>
            </fieldset>

            <fieldset>
                <legend>Address</legend>
                <div class="form-grid">
                    <div class="form-group full">
                        <label>Billing Address</label>
                        <textarea name="billing_address" id="billing_address" rows="2"></textarea>
                    </div>
                    <div class="form-group full">
                        <label>Shipping Address</label>
                        <textarea name="shipping_address" id="shipping_address" rows="2"></textarea>
                    </div>
                    <div class="form-group">
                        <label>City</label>
                        <input type="text" name="city" id="city">
                    </div>
                    <div class="form-group">
                        <label>State</label>
                        <input type="text" name="state" id="state">
                    </div>
                    <div class="form-group">
                        <label>Pincode</label>
                        <input type="text" name="pincode" id="pincode">
                    </div>
                </div>
            </fieldset>

            <fieldset>
                <legend>Financial</legend>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Credit Limit</label>
                        <input type="number" step="0.01" name="credit_limit" id="credit_limit" value="0">
                    </div>
                    <div class="form-group">
                        <label>Opening Balance (Receivable)</label>
                        <input type="number" step="0.01" name="opening_balance" id="opening_balance" value="0">
                    </div>
                </div>
            </fieldset>

            <div class="form-group full">
                <label>Notes</label>
                <textarea name="notes" id="notes" rows="2"></textarea>
            </div>

            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="closeCustomerModal()">Cancel</button>
                <button type="submit" class="btn btn-primary"><?= icon('check') ?> Save Customer</button>
            </div>
        </form>
    </div>
</div>

<script>
function openCustomerModal() {
    document.getElementById('modalTitle').textContent = 'Add Customer';
    document.getElementById('formAction').value = 'create';
    document.getElementById('customerForm').reset();
    document.getElementById('customerId').value = '';
    document.getElementById('customerModal').classList.add('show');
}
function closeCustomerModal() {
    document.getElementById('customerModal').classList.remove('show');
}
function editCustomer(c) {
    document.getElementById('modalTitle').textContent = 'Edit Customer';
    document.getElementById('formAction').value = 'update';
    document.getElementById('customerId').value = c.id;
    document.getElementById('company_name').value = c.company_name || '';
    document.getElementById('customer_name').value = c.customer_name || '';
    document.getElementById('contact_person').value = c.contact_person || '';
    document.getElementById('phone').value = c.phone || '';
    document.getElementById('alt_phone').value = c.alt_phone || '';
    document.getElementById('email').value = c.email || '';
    document.getElementById('gst_number').value = c.gst_number || '';
    document.getElementById('billing_address').value = c.billing_address || '';
    document.getElementById('shipping_address').value = c.shipping_address || '';
    document.getElementById('city').value = c.city || '';
    document.getElementById('state').value = c.state || '';
    document.getElementById('pincode').value = c.pincode || '';
    document.getElementById('credit_limit').value = c.credit_limit || 0;
    document.getElementById('opening_balance').value = c.opening_balance || 0;
    document.getElementById('notes').value = c.notes || '';
    document.getElementById('customerModal').classList.add('show');
}
<?php if ($editCustomer): ?>
editCustomer(<?= json_encode($editCustomer) ?>);
<?php endif; ?>
</script>

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