<?php
ob_start();
session_start();
require_once '../config/database.php';      // provides $pdo (Seven Credit DB)
require_once '../config/modules.php';        // company_enabled_modules(), module_on()
require_once '../config/module_access.php';  // mod_can_edit()

if (!isset($_SESSION['user_id']) || empty($_SESSION['company_id'])) {
    header('Location: ../auth/login.php'); exit;
}
$companyId = (int)$_SESSION['company_id'];
$userId    = (int)$_SESSION['user_id'];
$role      = $_SESSION['role'] ?? '';

// module must be enabled for the company
$enabled = company_enabled_modules($pdo, $companyId);
if (!module_on($enabled, 'customer')) {
    http_response_code(403);
    exit('The Customer Management module is not enabled for your company.');
}
if (!mod_can_view($pdo, $companyId, $userId, $role, 'customer')) {
    http_response_code(403);
    exit('You do not have access to Customer Management. Please ask your admin.');
}

$canEdit = mod_can_edit($pdo, $companyId, $userId, $role, 'customer');

// esc() helper may not exist in this app:
if (!function_exists('esc')) {
    function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}

$companyName = $_SESSION['company_name'] ?? 'Company';

$message = '';
$error   = '';

/*
|--------------------------------------------------------------------------
| Auto-create the real Seven Credit tables (idempotent), scoped by company.
|--------------------------------------------------------------------------
*/
$pdo->exec("
    CREATE TABLE IF NOT EXISTS sp_customers (
        id INT AUTO_INCREMENT PRIMARY KEY,
        company_id INT NOT NULL,
        sd_no VARCHAR(50) NOT NULL,
        customer_name VARCHAR(255) DEFAULT NULL,
        telephone VARCHAR(100) DEFAULT NULL,
        vat_number VARCHAR(100) DEFAULT NULL,
        contract_status VARCHAR(20) NOT NULL DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY uniq_cust (company_id, sd_no),
        INDEX (company_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");
$pdo->exec("
    CREATE TABLE IF NOT EXISTS sp_machines (
        id INT AUTO_INCREMENT PRIMARY KEY,
        company_id INT NOT NULL,
        sd_no VARCHAR(50) DEFAULT NULL,
        unique_machine_no VARCHAR(100) DEFAULT NULL,
        machine_model VARCHAR(255) DEFAULT NULL,
        serial_no VARCHAR(100) DEFAULT NULL,
        location_text TEXT,
        meter_date VARCHAR(50) DEFAULT NULL,
        main_email VARCHAR(255) DEFAULT NULL,
        invoice_email VARCHAR(255) DEFAULT NULL,
        cc_email VARCHAR(255) DEFAULT NULL,
        telephone VARCHAR(100) DEFAULT NULL,
        status VARCHAR(20) DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX (company_id, sd_no)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

/*
|--------------------------------------------------------------------------
| Add a brand-new customer (write action — gated by $canEdit)
|--------------------------------------------------------------------------
*/
if (isset($_POST['add_customer']) && $canEdit) {
    $customer_id   = trim($_POST['customer_id'] ?? '');
    $customer_name = trim($_POST['customer_name'] ?? '');
    $telephone     = trim($_POST['telephone'] ?? '');
    $vat_number    = trim($_POST['vat_number'] ?? '');

    if ($customer_id === '' || $customer_name === '') {
        $error = 'SD No and Customer Name are required.';
    } else {
        // Block duplicate sd_no within the same company_id
        $chk = $pdo->prepare("SELECT 1 FROM sp_customers WHERE company_id = ? AND sd_no = ? LIMIT 1");
        $chk->execute([$companyId, $customer_id]);
        if ($chk->fetch()) {
            $error = 'A customer with SD No "' . $customer_id . '" already exists.';
        } else {
            $stmt = $pdo->prepare("
                INSERT INTO sp_customers (company_id, sd_no, customer_name, telephone, vat_number, contract_status)
                VALUES (?, ?, ?, ?, ?, 'active')
            ");
            $stmt->execute([$companyId, $customer_id, $customer_name, $telephone, $vat_number]);
            header('Location: sp_customers.php'); exit;
        }
    }
}

/*
|--------------------------------------------------------------------------
| Save edited customers (bulk — write action, gated by $canEdit)
| Updates sp_customers rows by id.
|--------------------------------------------------------------------------
*/
if (isset($_POST['save_all']) && $canEdit && !empty($_POST['rows']) && is_array($_POST['rows'])) {
    $up = $pdo->prepare("
        UPDATE sp_customers
        SET customer_name = ?, telephone = ?, vat_number = ?
        WHERE id = ? AND company_id = ?
    ");

    foreach ($_POST['rows'] as $rid => $vals) {
        $rid = (int)$rid;
        if ($rid <= 0) { continue; }
        $name = trim($vals['name'] ?? '');
        $tel  = trim($vals['tel'] ?? '');
        $vat  = trim($vals['vat'] ?? '');

        if ($name === '') { continue; } // don't wipe a name to blank

        $up->execute([$name, $tel, $vat, $rid, $companyId]);
    }

    header('Location: sp_customers.php'); exit;
}

/*
|--------------------------------------------------------------------------
| Toggle contract status (End / Resume — write action, gated by $canEdit)
|--------------------------------------------------------------------------
*/
if ((isset($_POST['toggle_contract']) || isset($_GET['toggle'])) && $canEdit) {
    $customer_id = trim($_POST['customer_id'] ?? $_GET['toggle'] ?? '');
    $new_status  = (($_POST['new_status'] ?? $_GET['to'] ?? '') === 'ended') ? 'ended' : 'active';

    if ($customer_id !== '') {
        $stmt = $pdo->prepare("
            UPDATE sp_customers SET contract_status = ?
            WHERE company_id = ? AND sd_no = ?
        ");
        $stmt->execute([$new_status, $companyId, $customer_id]);
    }
    $qBack = trim($_GET['q'] ?? '');
    header('Location: sp_customers.php' . ($qBack !== '' ? '?q=' . urlencode($qBack) : '')); exit;
}

/*
|--------------------------------------------------------------------------
| Search
|--------------------------------------------------------------------------
*/
$search = trim($_GET['q'] ?? '');

/*
|--------------------------------------------------------------------------
| Customer list — read directly from sp_customers for this company.
| Machine count = COUNT of sp_machines matching company_id + sd_no.
|--------------------------------------------------------------------------
*/
$sql = "
    SELECT
        c.id                                  AS id,
        c.sd_no                               AS customer_id,
        c.customer_name                       AS customer_name,
        c.telephone                           AS telephone,
        c.vat_number                          AS vat_number,
        c.contract_status                     AS contract_status,
        (
            SELECT COUNT(*) FROM sp_machines m
            WHERE m.company_id = c.company_id AND m.sd_no = c.sd_no
        )                                     AS machine_count
    FROM sp_customers c
    WHERE c.company_id = ?
";
$params = [$companyId];
if ($search !== '') {
    $sql .= " AND (c.sd_no LIKE ? OR c.customer_name LIKE ?) ";
    $params[] = '%' . $search . '%';
    $params[] = '%' . $search . '%';
}
$sql .= " ORDER BY c.sd_no ASC ";

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

$totalCustomers = count($customers);

// preserve search in links
$qLink = $search !== '' ? '&q=' . urlencode($search) : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Management</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg: #f3f6fb;
            --card: #ffffff;
            --ink: #111827;
            --muted: #64748b;
            --line: #eaeef5;
            --brand: #2563eb;
            --brand2: #1d4ed8;
            --brand-grad: #2563eb;
            --shadow: 0 12px 30px rgba(30, 41, 59, 0.08);
            --shadow-sm: 0 2px 6px rgba(30, 41, 59, 0.06);
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: 'Noto Sans Lao', 'Inter', Arial, sans-serif;
            background: var(--bg);
            color: var(--ink);
            -webkit-font-smoothing: antialiased;
        }
        .wrap { max-width: 1280px; margin: 0 auto; padding: 10px 16px 16px; }

        /* Simple top bar */
        .topbar {
            display: flex; align-items: center; justify-content: space-between;
            gap: 16px; flex-wrap: wrap; margin-bottom: 22px;
        }
        .topbar a.back {
            background: #fff; border: 1px solid var(--line); padding: 9px 15px;
            border-radius: 999px; text-decoration: none; color: #475569; font-weight: 600;
            font-size: 14px; transition: all .15s ease; box-shadow: var(--shadow-sm);
        }
        .topbar a.back:hover { color: var(--brand); border-color: #bfdbfe; transform: translateY(-1px); }
        .topbar .company { font-weight: 700; color: var(--muted); font-size: 14px; }

        /* Page title row */
        .page-head {
            display: flex; align-items: center; justify-content: space-between;
            gap: 16px; flex-wrap: wrap; margin-bottom: 10px;
        }
        .page-head h1 { margin: 0; font-size: 22px; font-weight: 800; letter-spacing: -0.02em; }
        .stat {
            display: inline-flex; align-items: center; gap: 8px; background: #fff;
            border: 1px solid var(--line); color: var(--ink); font-weight: 700;
            padding: 10px 16px; border-radius: 14px; box-shadow: var(--shadow-sm); font-size: 14px;
        }
        .stat b { color: var(--brand); font-size: 18px; }

        .card {
            background: var(--card); border: 1px solid var(--line); border-radius: 20px;
            box-shadow: var(--shadow); padding: 22px; margin-bottom: 20px;
        }

        .search-form { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 8px; }
        .search-form input[type="text"] {
            flex: 1; min-width: 220px; padding: 12px 16px; border: 1px solid #e2e8f0;
            border-radius: 12px; font-size: 14px; font-family: inherit; background: #f8fafc;
            transition: all .15s ease;
        }
        .search-form input[type="text"]:focus {
            outline: none; border-color: var(--brand); background: #fff;
            box-shadow: 0 0 0 4px rgba(37,99,235,0.12);
        }
        .btn {
            background: var(--brand); color: #fff; border: none; padding: 12px 18px;
            border-radius: 12px; cursor: pointer; font-weight: 700; text-decoration: none;
            display: inline-flex; align-items: center; gap: 6px; font-size: 14px; font-family: inherit;
            transition: all .15s ease;
        }
        .btn:hover { background: var(--brand2); transform: translateY(-1px); }
        .btn-clear { background: #eef2f7; color: #475569; }
        .btn-clear:hover { background: #e2e8f0; }
        .btn-add { background: #059669; }
        .btn-add:hover { background: #047857; }
        .toolbar {
            display: flex; gap: 12px; flex-wrap: wrap; align-items: flex-start;
            justify-content: space-between; margin-bottom: 8px;
        }
        .toolbar .search-form { flex: 1; margin-bottom: 0; }
        .add-form {
            background: #f8fafc; border: 1px dashed #cbd5e1; border-radius: 16px;
            padding: 18px; margin: 14px 0 18px;
        }
        .add-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; }
        .add-form label { display: block; font-weight: 600; font-size: 12px; color: var(--muted); margin-bottom: 6px; text-transform: uppercase; letter-spacing: .03em; }
        @media (max-width: 800px) { .add-grid { grid-template-columns: 1fr; } }
        .message { background: #ecfdf5; color: #047857; padding: 13px 16px; border-radius: 12px; margin-bottom: 14px; border: 1px solid #a7f3d0; font-weight: 600; }
        .error   { background: #fef2f2; color: #b91c1c; padding: 13px 16px; border-radius: 12px; margin-bottom: 14px; border: 1px solid #fecaca; font-weight: 600; }
        .table-scroll { overflow-x: auto; border-radius: 14px; }
        table { width: 100%; border-collapse: collapse; min-width: 900px; }
        thead th {
            background: #f8fafc; color: var(--muted); text-transform: uppercase;
            font-size: 11px; letter-spacing: .05em; font-weight: 700;
            padding: 12px 12px; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap;
        }
        tbody td {
            padding: 14px 12px; border-bottom: 1px solid var(--line); text-align: left;
            font-size: 14px; vertical-align: middle;
        }
        tbody tr { transition: background .12s ease; }
        tbody tr:hover { background: #f9fafe; }
        td.num, th.num { text-align: center; width: 70px; color: var(--muted); font-weight: 600; }
        .badge {
            display: inline-block; background: #eef2ff; color: var(--brand); padding: 4px 11px;
            border-radius: 999px; font-size: 12px; font-weight: 700;
        }
        .row-input {
            padding: 9px 11px; border: 1px solid #e2e8f0; border-radius: 10px;
            font-size: 13px; font-family: inherit; width: 100%; background: #fff;
        }
        .row-input:focus { outline: none; border-color: var(--brand); box-shadow: 0 0 0 3px rgba(37,99,235,0.12); }
        .actions { white-space: nowrap; }
        .link-btn {
            border: none; background: none; padding: 6px 10px; margin-right: 4px; cursor: pointer;
            font-weight: 700; font-size: 13px; font-family: inherit; border-radius: 8px; transition: background .12s ease;
        }
        .link-btn:hover { background: #f1f5f9; }
        .link-view   { color: #7c3aed; }
        .link-edit   { color: #2563eb; }
        .link-save   { color: #059669; }
        .link-end    { color: #dc2626; }
        .link-resume { color: #059669; }
        .link-cancel { color: #6b7280; }
        a.link-btn { text-decoration: none; display: inline-block; }
        /* greyed-out ended contracts */
        tr.ended td { color: #a3adba; background: #fbfcfd; }
        tr.ended td strong { color: #a3adba; }
        tr.ended:hover { background: #f6f8fa; }
        .tag-ended {
            display: inline-block; background: #fef2f2; color: #b91c1c; padding: 3px 9px;
            border-radius: 999px; font-size: 11px; font-weight: 700; margin-left: 6px; border: 1px solid #fecaca;
        }
        .head-actions { display: flex; gap: 10px; flex-wrap: wrap; }
        .btn-edit-all { background: #0f766e; }
        .btn-edit-all:hover { background: #115e59; }
        .edit-hint {
            background: #eff6ff; color: #1e40af; border: 1px solid #bfdbfe;
            padding: 11px 14px; border-radius: 12px; margin: 4px 0 14px; font-weight: 600; font-size: 14px;
        }
        /* editable cells: look like plain text until edit mode */
        .cell-input {
            width: 100%; border: 1px solid transparent; background: transparent;
            padding: 8px 10px; border-radius: 9px; font-size: 14px; font-family: inherit; color: inherit;
        }
        .cell-input:read-only { cursor: default; }
        body.edit-mode .cell-input {
            border-color: #d1d9e6; background: #fff;
        }
        body.edit-mode .cell-input:focus {
            outline: none; border-color: var(--brand); box-shadow: 0 0 0 3px rgba(37,99,235,0.12);
        }
        body.edit-mode tbody tr:hover { background: transparent; }
        @media (max-width: 640px) { .brand h1 { font-size: 20px; } }
    </style>
</head>
<body>
    <div class="wrap">

        <?php $spActive = 'customers'; include 'sp_nav.php'; ?>

        <div class="page-head">
            <h1>Customer Management</h1>
            <span class="stat"><b><?= esc($totalCustomers) ?></b> total customers</span>
        </div>

        <?php if ($message): ?>
            <div class="message"><?= esc($message) ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="error"><?= esc($error) ?></div>
        <?php endif; ?>

        <div class="card">
            <div class="toolbar">
                <form method="GET" class="search-form">
                    <input type="text" name="q" placeholder="Search by SD No or Customer Name..." value="<?= esc($search) ?>">
                    <button type="submit" class="btn">Search</button>
                    <?php if ($search !== ''): ?>
                        <a href="sp_customers.php" class="btn btn-clear">Clear</a>
                    <?php endif; ?>
                </form>
                <?php if ($canEdit): ?>
                <div class="head-actions">
                    <button type="button" id="editAllBtn" class="btn btn-edit-all" onclick="enterEditMode()">Edit All</button>
                    <button type="submit" name="save_all" form="bulkform" id="saveAllBtn" class="btn" style="display:none;">Save All</button>
                    <button type="button" id="cancelAllBtn" class="btn btn-clear" style="display:none;" onclick="location.reload()">Cancel</button>
                    <button type="button" class="btn btn-add" onclick="toggleAddForm()">+ Add Customer</button>
                </div>
                <?php endif; ?>
            </div>

            <?php if ($canEdit): ?>
            <div id="editHint" class="edit-hint" style="display:none;">
                Editing all rows &mdash; change any fields you need, then click <strong>Save All</strong>.
            </div>

            <div id="addForm" class="add-form" style="display:<?= (isset($_POST['add_customer']) && $error) ? 'block' : 'none' ?>;">
                <form method="POST">
                    <div class="add-grid">
                        <div>
                            <label>SD No (Customer ID) *</label>
                            <input class="row-input" type="text" name="customer_id" placeholder="e.g. SD200" required>
                        </div>
                        <div>
                            <label>Customer Name *</label>
                            <input class="row-input" type="text" name="customer_name" required>
                        </div>
                        <div>
                            <label>Telephone</label>
                            <input class="row-input" type="text" name="telephone">
                        </div>
                        <div>
                            <label>VAT Number</label>
                            <input class="row-input" type="text" name="vat_number">
                        </div>
                    </div>
                    <div style="margin-top:12px;">
                        <button type="submit" name="add_customer" class="btn">Save Customer</button>
                        <button type="button" class="btn btn-clear" onclick="toggleAddForm()">Cancel</button>
                    </div>
                </form>
            </div>
            <?php endif; ?>

            <?php if ($canEdit): ?><form id="bulkform" method="POST"></form><?php endif; ?>
            <div class="table-scroll">
                <table>
                    <thead>
                        <tr>
                            <th class="num">No</th>
                            <th>customer_id</th>
                            <th>customer_name</th>
                            <th>telephone</th>
                            <th>machines</th>
                            <th>vat_number</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($customers): ?>
                            <?php $no = 1; foreach ($customers as $c): ?>
                                <?php
                                    $cid     = $c['customer_id'];
                                    $rid     = (int)$c['id'];
                                    $isEnded = ($c['contract_status'] === 'ended');
                                ?>
                                <tr id="row-<?= esc($rid) ?>" class="<?= $isEnded ? 'ended' : '' ?>">
                                    <td class="num"><?= $no++ ?></td>
                                    <td>
                                        <strong><?= esc($cid) ?></strong>
                                        <?php if ($isEnded): ?><span class="tag-ended">Contract ended</span><?php endif; ?>
                                    </td>
                                    <?php if ($canEdit): ?>
                                    <td>
                                        <input class="cell-input" type="text" form="bulkform"
                                               name="rows[<?= esc($rid) ?>][name]"
                                               value="<?= esc($c['customer_name']) ?>" readonly>
                                    </td>
                                    <td>
                                        <input class="cell-input" type="text" form="bulkform"
                                               name="rows[<?= esc($rid) ?>][tel]"
                                               value="<?= esc($c['telephone'] ?? '') ?>" readonly>
                                    </td>
                                    <td><span class="badge"><?= esc($c['machine_count']) ?></span></td>
                                    <td>
                                        <input class="cell-input" type="text" form="bulkform"
                                               name="rows[<?= esc($rid) ?>][vat]"
                                               value="<?= esc($c['vat_number'] ?? '') ?>" placeholder="&mdash;" readonly>
                                    </td>
                                    <?php else: ?>
                                    <td><?= esc($c['customer_name']) ?></td>
                                    <td><?= esc($c['telephone'] ?? '') ?></td>
                                    <td><span class="badge"><?= esc($c['machine_count']) ?></span></td>
                                    <td><?= $c['vat_number'] !== null && $c['vat_number'] !== '' ? esc($c['vat_number']) : '&mdash;' ?></td>
                                    <?php endif; ?>
                                    <td class="actions">
                                        <a class="link-btn link-view" href="sp_customer_view.php?sd=<?= urlencode($cid) ?>">View</a>
                                        <?php if ($canEdit): ?>
                                            <?php if ($isEnded): ?>
                                                <a class="link-btn link-resume" href="sp_customers.php?toggle=<?= urlencode($cid) ?>&to=active<?= $qLink ?>">Resume</a>
                                            <?php else: ?>
                                                <a class="link-btn link-end" href="sp_customers.php?toggle=<?= urlencode($cid) ?>&to=ended<?= $qLink ?>"
                                                   onclick="return confirm('End contract for <?= esc($cid) ?>? The row will be greyed out.')">End Contract</a>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" style="text-align:center; color:#6b7280;">No customers found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>

    <?php if ($canEdit): ?>
    <script>
        function toggleAddForm() {
            var f = document.getElementById('addForm');
            f.style.display = (f.style.display === 'none' || f.style.display === '') ? 'block' : 'none';
        }
        function enterEditMode() {
            document.body.classList.add('edit-mode');
            document.querySelectorAll('.cell-input').forEach(function (i) { i.readOnly = false; });
            document.getElementById('editAllBtn').style.display = 'none';
            document.getElementById('saveAllBtn').style.display = '';
            document.getElementById('cancelAllBtn').style.display = '';
            document.getElementById('editHint').style.display = '';
        }
        // Warn before leaving with unsaved edits
        window.addEventListener('beforeunload', function (e) {
            if (document.body.classList.contains('edit-mode') && !window.__savingAll) {
                e.preventDefault();
                e.returnValue = '';
            }
        });
        var saveBtn = document.getElementById('saveAllBtn');
        if (saveBtn) { saveBtn.addEventListener('click', function () { window.__savingAll = true; }); }
    </script>
    <?php endif; ?>
</body>
</html>
<?php ob_end_flush(); ?>