<?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';

$customer_id = trim($_GET['sd'] ?? '');

if ($customer_id === '') {
    header('Location: sp_customers.php'); exit;
}

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

/*
|--------------------------------------------------------------------------
| Add a machine to this customer (write action — gated by $canEdit)
|--------------------------------------------------------------------------
*/
if (isset($_POST['add_machine']) && $canEdit) {
    $unique_machine_no = trim($_POST['unique_machine_no'] ?? '');
    $machine_model     = trim($_POST['machine_model'] ?? '');
    $serial_no         = trim($_POST['serial_no'] ?? '');
    $location_text     = trim($_POST['location_text'] ?? '');
    $main_email        = trim($_POST['main_email'] ?? '');
    $invoice_email     = trim($_POST['invoice_email'] ?? '');
    $cc_email          = trim($_POST['cc_email'] ?? '');
    $telephone         = trim($_POST['telephone'] ?? '');

    if ($unique_machine_no === '' || $machine_model === '') {
        $error = 'Unique Machine No and Machine Model are required.';
    } else {
        $chk = $pdo->prepare("SELECT id FROM sp_machines WHERE company_id = ? AND unique_machine_no = ? LIMIT 1");
        $chk->execute([$companyId, $unique_machine_no]);
        if ($chk->fetch()) {
            $error = 'Machine No "' . $unique_machine_no . '" already exists.';
        } else {
            $stmt = $pdo->prepare("
                INSERT INTO sp_machines
                    (company_id, sd_no, unique_machine_no, machine_model, serial_no,
                     location_text, main_email, invoice_email, cc_email, telephone, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')
            ");
            $stmt->execute([
                $companyId, $customer_id, $unique_machine_no, $machine_model, $serial_no,
                $location_text, $main_email, $invoice_email, $cc_email, $telephone
            ]);
            header('Location: sp_customer_view.php?sd=' . urlencode($customer_id)); exit;
        }
    }
}

/*
|--------------------------------------------------------------------------
| Update a machine (write action — gated by $canEdit)
|--------------------------------------------------------------------------
*/
if (isset($_POST['update_machine']) && $canEdit) {
    $id                = (int)($_POST['id'] ?? 0);
    $unique_machine_no = trim($_POST['unique_machine_no'] ?? '');
    $machine_model     = trim($_POST['machine_model'] ?? '');
    $serial_no         = trim($_POST['serial_no'] ?? '');
    $location_text     = trim($_POST['location_text'] ?? '');
    $main_email        = trim($_POST['main_email'] ?? '');
    $invoice_email     = trim($_POST['invoice_email'] ?? '');
    $cc_email          = trim($_POST['cc_email'] ?? '');
    $telephone         = trim($_POST['telephone'] ?? '');

    if ($id <= 0 || $unique_machine_no === '') {
        $error = 'Invalid machine data.';
    } else {
        $chk = $pdo->prepare("SELECT id FROM sp_machines WHERE company_id = ? AND unique_machine_no = ? AND id != ? LIMIT 1");
        $chk->execute([$companyId, $unique_machine_no, $id]);
        if ($chk->fetch()) {
            $error = 'Another machine already uses No "' . $unique_machine_no . '".';
        } else {
            $stmt = $pdo->prepare("
                UPDATE sp_machines
                SET unique_machine_no = ?, machine_model = ?, serial_no = ?, location_text = ?,
                    main_email = ?, invoice_email = ?, cc_email = ?, telephone = ?
                WHERE id = ? AND company_id = ? AND sd_no = ?
            ");
            $stmt->execute([
                $unique_machine_no, $machine_model, $serial_no, $location_text,
                $main_email, $invoice_email, $cc_email, $telephone, $id, $companyId, $customer_id
            ]);
            header('Location: sp_customer_view.php?sd=' . urlencode($customer_id)); exit;
        }
    }
}

/*
|--------------------------------------------------------------------------
| Delete a machine (write action — gated by $canEdit)
|--------------------------------------------------------------------------
*/
if (isset($_POST['delete_machine']) && $canEdit) {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        $stmt = $pdo->prepare("DELETE FROM sp_machines WHERE id = ? AND company_id = ? AND sd_no = ?");
        $stmt->execute([$id, $companyId, $customer_id]);
    }
    header('Location: sp_customer_view.php?sd=' . urlencode($customer_id)); exit;
}

$editMachineId = ($canEdit) ? (int)($_GET['edit_machine'] ?? 0) : 0;

/*
|--------------------------------------------------------------------------
| Customer header info (scoped to company_id).
|--------------------------------------------------------------------------
*/
$stmt = $pdo->prepare("SELECT customer_name, vat_number, contract_status FROM sp_customers WHERE company_id = ? AND sd_no = ? LIMIT 1");
$stmt->execute([$companyId, $customer_id]);
$custRow = $stmt->fetch(PDO::FETCH_ASSOC);

$customerName   = $custRow['customer_name'] ?? null;
$vatNumber      = $custRow['vat_number'] ?? '';
$contractStatus = $custRow['contract_status'] ?? 'active';

/*
|--------------------------------------------------------------------------
| Machines for this customer (scoped to company_id + sd_no)
|--------------------------------------------------------------------------
*/
$mSearch = trim($_GET['m'] ?? '');

// total machines for this customer (unaffected by search)
$cntStmt = $pdo->prepare("SELECT COUNT(*) AS c FROM sp_machines WHERE company_id = ? AND sd_no = ?");
$cntStmt->execute([$companyId, $customer_id]);
$machineCount = (int)($cntStmt->fetch()['c'] ?? 0);

$sql = "
    SELECT
        id,
        unique_machine_no,
        machine_model,
        serial_no,
        location_text,
        main_email,
        invoice_email,
        cc_email,
        telephone
    FROM sp_machines
    WHERE company_id = ? AND sd_no = ?
";
$mParams = [$companyId, $customer_id];
if ($mSearch !== '') {
    $sql .= " AND (unique_machine_no LIKE ? OR serial_no LIKE ? OR machine_model LIKE ?) ";
    $mParams[] = '%' . $mSearch . '%';
    $mParams[] = '%' . $mSearch . '%';
    $mParams[] = '%' . $mSearch . '%';
}
$sql .= " ORDER BY id ASC ";

$stmt = $pdo->prepare($sql);
$stmt->execute($mParams);
$machines = $stmt->fetchAll(PDO::FETCH_ASSOC);
$shownCount = count($machines);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= esc($customerName ?: $customer_id) ?> - Customer</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: #eef2f9;
            --card: #ffffff;
            --ink: #0f172a;
            --muted: #64748b;
            --line: #e6eaf2;
            --brand: #1d4ed8;
            --brand2: #1e40af;
            --hero: linear-gradient(135deg, #1e40af 0%, #172a6b 100%);
            --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; }
        .topbar {
            display: flex; align-items: center; justify-content: space-between;
            gap: 16px; flex-wrap: wrap; margin-bottom: 18px;
        }
        .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: #c7d2fe; transform: translateY(-1px); }
        .topbar .company { font-weight: 700; color: var(--muted); font-size: 14px; }
        .card {
            background: var(--card); border: 1px solid var(--line); border-radius: 20px;
            box-shadow: var(--shadow); padding: 24px; margin-bottom: 20px;
        }
        /* Customer hero */
        .hero { background: var(--hero); color: #fff; border: none; }
        .hero .cust-head { display: flex; flex-wrap: wrap; align-items: center; gap: 14px; }
        .hero .avatar {
            width: 56px; height: 56px; border-radius: 16px; background: rgba(255,255,255,0.2);
            display: grid; place-items: center; font-size: 24px; font-weight: 800;
            border: 1px solid rgba(255,255,255,0.35);
        }
        .cust-name { font-size: 28px; font-weight: 800; margin: 0; letter-spacing: -0.02em; }
        .pill {
            display: inline-block; background: #eef2ff; color: var(--brand);
            padding: 7px 14px; border-radius: 999px; font-weight: 700; font-size: 13px;
        }
        .hero .pill { background: rgba(255,255,255,0.22); color: #fff; border: 1px solid rgba(255,255,255,0.3); }
        .pill-grey { background: #f1f5f9; color: #334155; }
        .pill-ended { background: #fee2e2 !important; color: #b91c1c !important; border-color: transparent !important; }
        .meta-row { margin-top: 14px; display: flex; flex-wrap: wrap; gap: 10px; }
        h2 { margin: 0 0 16px; font-size: 18px; font-weight: 800; display: flex; align-items: center; gap: 8px; }
        h2 .count { font-size: 13px; color: var(--muted); font-weight: 600; }
        .table-scroll { overflow-x: auto; border-radius: 14px; }
        table { width: 100%; border-collapse: collapse; min-width: 940px; }
        thead th {
            background: #f8fafc; color: var(--muted); text-transform: uppercase;
            font-size: 11px; letter-spacing: .04em; font-weight: 700;
            padding: 12px 12px; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap;
        }
        tbody td {
            padding: 13px 12px; border-bottom: 1px solid var(--line); text-align: left;
            font-size: 13px; vertical-align: top; white-space: nowrap;
        }
        tbody tr { transition: background .12s ease; }
        tbody tr:hover { background: #f9fafe; }
        td.wrap-cell { white-space: normal; min-width: 160px; }
        td.num, th.num { text-align: center; width: 56px; color: var(--muted); font-weight: 600; }
        .muted { color: #cbd5e1; }

        /* Card header with search + add */
        .card-head {
            display: flex; align-items: center; justify-content: space-between;
            gap: 12px; flex-wrap: wrap; margin-bottom: 16px;
        }
        .head-tools { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
        .search-form { display: flex; gap: 8px; }
        .search-form input[type="text"] {
            padding: 10px 14px; border: 1px solid #e2e8f0; border-radius: 10px;
            font-size: 14px; font-family: inherit; background: #f8fafc; min-width: 200px;
        }
        .search-form input[type="text"]:focus {
            outline: none; border-color: var(--brand); background: #fff;
            box-shadow: 0 0 0 4px rgba(29,78,216,0.12);
        }
        .btn {
            background: var(--brand); color: #fff; border: none; padding: 10px 16px;
            border-radius: 10px; 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; }
        .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; }
        .add-form {
            background: #f8fafc; border: 1px dashed #cbd5e1; border-radius: 16px;
            padding: 18px; margin-bottom: 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 1fr; } }
        @media (max-width: 520px) { .add-grid { grid-template-columns: 1fr; } }
        .row-input {
            padding: 8px 10px; border: 1px solid #e2e8f0; border-radius: 9px;
            font-size: 13px; font-family: inherit; width: 100%; background: #fff; min-width: 110px;
        }
        .row-input:focus { outline: none; border-color: var(--brand); box-shadow: 0 0 0 3px rgba(29,78,216,0.12); }
        .actions { white-space: nowrap; }
        .link-btn {
            border: none; background: none; padding: 6px 9px; margin-right: 2px; cursor: pointer;
            font-weight: 700; font-size: 13px; font-family: inherit; border-radius: 8px; transition: background .12s ease;
        }
        .link-btn:hover { background: #f1f5f9; }
        .link-edit   { color: #1d4ed8; }
        .link-save   { color: #059669; }
        .link-delete { color: #dc2626; }
        .link-cancel { color: #6b7280; }
        a.link-btn { text-decoration: none; display: inline-block; }
    </style>
</head>
<body>
    <div class="wrap">

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

        <div style="margin-bottom:18px;">
            <a href="sp_customers.php" style="color:#2563eb; text-decoration:none; font-weight:600;">&larr; Back to Customers</a>
        </div>

        <div class="card hero">
            <div class="cust-head">
                <div class="avatar"><?= esc(mb_strtoupper(mb_substr(trim($customerName ?: $customer_id), 0, 1))) ?></div>
                <div>
                    <h1 class="cust-name"><?= esc($customerName ?: '(no name)') ?></h1>
                    <div class="meta-row">
                        <span class="pill">SD No: <?= esc($customer_id) ?></span>
                        <span class="pill">Machines: <?= esc($machineCount) ?></span>
                        <?php if (!empty($vatNumber)): ?>
                            <span class="pill">VAT: <?= esc($vatNumber) ?></span>
                        <?php endif; ?>
                        <?php if ($contractStatus === 'ended'): ?>
                            <span class="pill pill-ended">Contract ended</span>
                        <?php endif; ?>
                    </div>
                    <div style="margin-top:14px;">
                        <a href="sp_customer_expenses.php?sd=<?= urlencode($customer_id) ?>"
                           style="display:inline-flex; align-items:center; gap:6px; background:#fff; color:#1e40af; padding:9px 16px; border-radius:10px; font-weight:700; text-decoration:none;">
                            💰 Expenses Tracker
                        </a>
                    </div>
                </div>
            </div>
        </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="card-head">
                <h2>Machines
                    <span class="count">(<?= $mSearch !== '' ? esc($shownCount) . ' of ' . esc($machineCount) : esc($machineCount) ?>)</span>
                </h2>
                <div class="head-tools">
                    <form method="GET" class="search-form">
                        <input type="hidden" name="sd" value="<?= esc($customer_id) ?>">
                        <input type="text" name="m" placeholder="Search machine no / serial..." value="<?= esc($mSearch) ?>">
                        <button type="submit" class="btn">Search</button>
                        <?php if ($mSearch !== ''): ?>
                            <a href="sp_customer_view.php?sd=<?= urlencode($customer_id) ?>" class="btn btn-clear">Clear</a>
                        <?php endif; ?>
                    </form>
                    <?php if ($canEdit): ?>
                        <button type="button" class="btn btn-add" onclick="toggleAddMachine()">+ Add Machine</button>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($canEdit): ?>
            <div id="addMachine" class="add-form" style="display:<?= (isset($_POST['add_machine']) && $error) ? 'block' : 'none' ?>;">
                <form method="POST">
                    <div class="add-grid">
                        <div>
                            <label>Unique Machine No *</label>
                            <input class="row-input" type="text" name="unique_machine_no" required>
                        </div>
                        <div>
                            <label>Machine Model *</label>
                            <input class="row-input" type="text" name="machine_model" required>
                        </div>
                        <div>
                            <label>Serial No</label>
                            <input class="row-input" type="text" name="serial_no">
                        </div>
                        <div>
                            <label>Telephone</label>
                            <input class="row-input" type="text" name="telephone">
                        </div>
                        <div style="grid-column: 1 / -1;">
                            <label>Location</label>
                            <input class="row-input" type="text" name="location_text">
                        </div>
                        <div>
                            <label>Main Email</label>
                            <input class="row-input" type="text" name="main_email">
                        </div>
                        <div>
                            <label>Invoice Email</label>
                            <input class="row-input" type="text" name="invoice_email">
                        </div>
                        <div>
                            <label>CC Email</label>
                            <input class="row-input" type="text" name="cc_email">
                        </div>
                    </div>
                    <div style="margin-top:14px;">
                        <button type="submit" name="add_machine" class="btn">Save Machine</button>
                        <button type="button" class="btn btn-clear" onclick="toggleAddMachine()">Cancel</button>
                    </div>
                </form>
            </div>
            <?php endif; ?>

            <?php if ($canEdit && $editMachineId > 0): ?>
                <form id="editmc" method="POST"></form>
            <?php endif; ?>

            <div class="table-scroll">
                <table>
                    <thead>
                        <tr>
                            <th class="num">No</th>
                            <th>unique_machine_no</th>
                            <th>machine_model</th>
                            <th>serial_no</th>
                            <th>location_text</th>
                            <th>main_email</th>
                            <th>invoice_email</th>
                            <th>cc_email</th>
                            <th>telephone</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($machines): ?>
                            <?php $no = 1; foreach ($machines as $m): ?>
                                <?php $isEdit = ($canEdit && $editMachineId === (int)$m['id']); ?>
                                <tr>
                                    <td class="num"><?= $no++ ?></td>
                                    <?php if ($isEdit): ?>
                                        <input type="hidden" name="id" value="<?= esc($m['id']) ?>" form="editmc">
                                        <td><input class="row-input" type="text" name="unique_machine_no" value="<?= esc($m['unique_machine_no']) ?>" form="editmc" required></td>
                                        <td><input class="row-input" type="text" name="machine_model" value="<?= esc($m['machine_model']) ?>" form="editmc"></td>
                                        <td><input class="row-input" type="text" name="serial_no" value="<?= esc($m['serial_no']) ?>" form="editmc"></td>
                                        <td><input class="row-input wrap-cell" type="text" name="location_text" value="<?= esc($m['location_text']) ?>" form="editmc"></td>
                                        <td><input class="row-input" type="text" name="main_email" value="<?= esc($m['main_email']) ?>" form="editmc"></td>
                                        <td><input class="row-input" type="text" name="invoice_email" value="<?= esc($m['invoice_email']) ?>" form="editmc"></td>
                                        <td><input class="row-input" type="text" name="cc_email" value="<?= esc($m['cc_email']) ?>" form="editmc"></td>
                                        <td><input class="row-input" type="text" name="telephone" value="<?= esc($m['telephone']) ?>" form="editmc"></td>
                                        <td class="actions">
                                            <button type="submit" name="update_machine" class="link-btn link-save" form="editmc">Save</button>
                                            <a class="link-btn link-cancel" href="sp_customer_view.php?sd=<?= urlencode($customer_id) ?>">Cancel</a>
                                        </td>
                                    <?php else: ?>
                                        <td><strong><?= esc($m['unique_machine_no']) ?></strong></td>
                                        <td><?= esc($m['machine_model']) ?></td>
                                        <td><?= esc($m['serial_no']) ?></td>
                                        <td class="wrap-cell"><?= esc($m['location_text']) ?></td>
                                        <td><?= $m['main_email'] ? esc($m['main_email']) : '<span class="muted">&mdash;</span>' ?></td>
                                        <td><?= $m['invoice_email'] ? esc($m['invoice_email']) : '<span class="muted">&mdash;</span>' ?></td>
                                        <td><?= $m['cc_email'] ? esc($m['cc_email']) : '<span class="muted">&mdash;</span>' ?></td>
                                        <td><?= $m['telephone'] ? esc($m['telephone']) : '<span class="muted">&mdash;</span>' ?></td>
                                        <td class="actions">
                                            <?php if ($canEdit): ?>
                                            <a class="link-btn link-edit" href="sp_customer_view.php?sd=<?= urlencode($customer_id) ?>&edit_machine=<?= esc($m['id']) ?><?= $mSearch !== '' ? '&m=' . urlencode($mSearch) : '' ?>">Edit</a>
                                            <form method="POST" style="display:inline" onsubmit="return confirm('Delete machine <?= esc($m['unique_machine_no']) ?>? This cannot be undone.')">
                                                <input type="hidden" name="id" value="<?= esc($m['id']) ?>">
                                                <button type="submit" name="delete_machine" class="link-btn link-delete">Delete</button>
                                            </form>
                                            <?php else: ?>
                                            <span class="muted">&mdash;</span>
                                            <?php endif; ?>
                                        </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="10" style="text-align:center; color:#6b7280;">
                                    <?= $mSearch !== '' ? 'No machines match your search.' : 'No machines for this customer yet.' ?>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>

    <?php if ($canEdit): ?>
    <script>
        function toggleAddMachine() {
            var f = document.getElementById('addMachine');
            f.style.display = (f.style.display === 'none' || f.style.display === '') ? 'block' : 'none';
        }
    </script>
    <?php endif; ?>
</body>
</html>
<?php ob_end_flush(); ?>