<?php
require_once 'db.php';
requireAdmin();




/*
|--------------------------------------------------------------------------
| Export Machines to Excel (.xls) - Pure PHP
|--------------------------------------------------------------------------
*/
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    $stmt = $pdo->query("
        SELECT 
            customer_id,
            unique_machine_no,
            machine_model,
            serial_no,
            customer_name,
            location_text,
            meter_date,
            main_email,
            invoice_email,
            cc_email,
            telephone,
            status
        FROM machines
        ORDER BY id ASC
    ");
    $exportMachines = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $filename = 'machines_export_' . date('Y-m-d_H-i-s') . '.xls';

    header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Pragma: no-cache");
    header("Expires: 0");

    echo "\xEF\xBB\xBF";
    ?>
    <table border="1">
        <thead>
            <tr>
                <th>customer_id</th>
                <th>unique_machine_no</th>
                <th>machine_model</th>
                <th>serial_no</th>
                <th>customer_name</th>
                <th>location_text</th>
                <th>meter_date</th>
                <th>main_email</th>
                <th>invoice_email</th>
                <th>cc_email</th>
                <th>telephone</th>
                <th>status</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($exportMachines as $row): ?>
                <tr>
                    <td><?= htmlspecialchars((string)$row['customer_id']) ?></td>
                    <td><?= htmlspecialchars((string)$row['unique_machine_no']) ?></td>
                    <td><?= htmlspecialchars((string)$row['machine_model']) ?></td>
                    <td><?= htmlspecialchars((string)$row['serial_no']) ?></td>
                    <td><?= htmlspecialchars((string)$row['customer_name']) ?></td>
                    <td><?= htmlspecialchars((string)$row['location_text']) ?></td>
                    <td><?= htmlspecialchars((string)$row['meter_date']) ?></td>
                    <td><?= htmlspecialchars((string)$row['main_email']) ?></td>
                    <td><?= htmlspecialchars((string)$row['invoice_email']) ?></td>
                    <td><?= htmlspecialchars((string)$row['cc_email']) ?></td>
                    <td><?= htmlspecialchars((string)$row['telephone']) ?></td>
                    <td><?= htmlspecialchars((string)$row['status']) ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php
    exit;
}

$message = '';
$error = '';
/*
|--------------------------------------------------------------------------
| Machine CSV Upload
|--------------------------------------------------------------------------
*/
if (isset($_POST['upload_machines_csv'])) {
    if (!isset($_FILES['machines_csv']) || $_FILES['machines_csv']['error'] !== 0) {
        $error = 'Please choose a valid CSV file.';
    } else {
        $fileTmp = $_FILES['machines_csv']['tmp_name'];

        if (!is_uploaded_file($fileTmp)) {
            $error = 'Invalid uploaded file.';
        } else {
            $handle = fopen($fileTmp, 'r');

            if (!$handle) {
                $error = 'Could not open CSV file.';
            } else {
                $header = fgetcsv($handle);

                $expectedHeader = [
                    'customer_id',
                    'unique_machine_no',
                    'machine_model',
                    'serial_no',
                    'customer_name',
                    'location_text',
                    'meter_date',
                    'main_email',
                    'invoice_email',
                    'cc_email',
                    'telephone',
                    'status'
                ];

                if (!$header) {
                    $error = 'CSV file is empty.';
                } else {
                    $header = array_map('trim', $header);

                    if (isset($header[0])) {
                        $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', $header[0]);
                    }

                    if ($header !== $expectedHeader) {
                        $error = 'Invalid CSV header. Please use the required machine CSV format.';
                    } else {
                        $inserted = 0;
                        $skipped = 0;

                        $stmt = $pdo->prepare("
                            INSERT IGNORE INTO machines (
                                customer_id,
                                unique_machine_no,
                                machine_model,
                                serial_no,
                                customer_name,
                                location_text,
                                meter_date,
                                main_email,
                                invoice_email,
                                cc_email,
                                telephone,
                                status
                            )
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        ");

                        while (($row = fgetcsv($handle)) !== false) {
                            if (count($row) < count($expectedHeader)) {
                                $skipped++;
                                continue;
                            }

                            $row = array_map('trim', $row);
                            $data = array_combine($expectedHeader, array_slice($row, 0, count($expectedHeader)));

                            $customer_id       = trim($data['customer_id'] ?? '');
                            $unique_machine_no = trim($data['unique_machine_no'] ?? '');
                            $machine_model     = trim($data['machine_model'] ?? '');
                            $serial_no         = trim($data['serial_no'] ?? '');
                            $customer_name     = trim($data['customer_name'] ?? '');
                            $location_text     = trim($data['location_text'] ?? '');
                            $meter_date        = trim($data['meter_date'] ?? '');
                            $main_email        = trim($data['main_email'] ?? '');
                            $invoice_email     = trim($data['invoice_email'] ?? '');
                            $cc_email          = trim($data['cc_email'] ?? '');
                            $telephone         = trim($data['telephone'] ?? '');
                            $status            = trim($data['status'] ?? 'active');

                            if ($machine_model === '' || $customer_name === '') {
                                $skipped++;
                                continue;
                            }

                            $customer_id = $customer_id !== '' ? $customer_id : null;
                            $unique_machine_no = $unique_machine_no !== '' ? $unique_machine_no : null;

                            if (!in_array($status, ['active', 'inactive', 'retired'], true)) {
                                $status = 'active';
                            }

                            $stmt->execute([
                                $customer_id,
                                $unique_machine_no,
                                $machine_model,
                                $serial_no,
                                $customer_name,
                                $location_text,
                                $meter_date ?: null,
                                $main_email,
                                $invoice_email,
                                $cc_email,
                                $telephone,
                                $status
                            ]);

                            if ($stmt->rowCount() > 0) {
                                $inserted++;
                            } else {
                                $skipped++;
                            }
                        }

                        $message = "CSV upload completed. Inserted: {$inserted}, Skipped: {$skipped}.";
                    }
                }

                fclose($handle);
            }
        }
    }
}

/*
|--------------------------------------------------------------------------
| Add Machine
|--------------------------------------------------------------------------
*/
if (isset($_POST['add_machine'])) {

    $unique_machine_no = trim($_POST['unique_machine_no'] ?? '');
    $customer_id       = trim($_POST['customer_id'] ?? '');
    $machine_model     = trim($_POST['machine_model'] ?? '');
    $serial_no         = trim($_POST['serial_no'] ?? '');
    $customer_name     = trim($_POST['customer_name'] ?? '');
    $location_text     = trim($_POST['location_text'] ?? '');
    $meter_date        = trim($_POST['meter_date'] ?? '');
    $main_email        = trim($_POST['main_email'] ?? '');
    $invoice_email     = trim($_POST['invoice_email'] ?? '');
    $cc_email          = trim($_POST['cc_email'] ?? '');
    $telephone         = trim($_POST['telephone'] ?? '');
    $status            = trim($_POST['status'] ?? 'active');

    if ($unique_machine_no === '' || $machine_model === '' || $customer_name === '') {
        $error = 'Unique Machine No, Machine Model, and Customer Name are required.';
    } else {

        $checkStmt = $pdo->prepare("SELECT id FROM machines WHERE unique_machine_no = ? LIMIT 1");
        $checkStmt->execute([$unique_machine_no]);

        if ($checkStmt->fetch()) {
            $error = 'This Machine No already exists.';
        } else {

            $stmt = $pdo->prepare("
                INSERT INTO machines (
                    unique_machine_no,
                    customer_id,
                    machine_model,
                    serial_no,
                    customer_name,
                    location_text,
                    meter_date,
                    main_email,
                    invoice_email,
                    cc_email,
                    telephone,
                    status
                )
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $stmt->execute([
                $unique_machine_no,
                $customer_id !== '' ? $customer_id : null,
                $machine_model,
                $serial_no,
                $customer_name,
                $location_text,
                $meter_date ?: null,
                $main_email,
                $invoice_email,
                $cc_email,
                $telephone,
                $status
            ]);

            $message = 'Machine added successfully.';
        }
    }
}

/*
|--------------------------------------------------------------------------
| Update Machine
|--------------------------------------------------------------------------
*/
if (isset($_POST['update_machine'])) {

    $id                = (int)($_POST['id'] ?? 0);
    $unique_machine_no = trim($_POST['unique_machine_no'] ?? '');
    $customer_id       = trim($_POST['customer_id'] ?? '');
    $machine_model     = trim($_POST['machine_model'] ?? '');
    $serial_no         = trim($_POST['serial_no'] ?? '');
    $customer_name     = trim($_POST['customer_name'] ?? '');
    $location_text     = trim($_POST['location_text'] ?? '');
    $meter_date        = trim($_POST['meter_date'] ?? '');
    $main_email        = trim($_POST['main_email'] ?? '');
    $invoice_email     = trim($_POST['invoice_email'] ?? '');
    $cc_email          = trim($_POST['cc_email'] ?? '');
    $telephone         = trim($_POST['telephone'] ?? '');
    $status            = trim($_POST['status'] ?? 'active');

    if ($id <= 0 || $unique_machine_no === '') {
        $error = 'Invalid machine data.';
    } else {

        $checkStmt = $pdo->prepare("SELECT id FROM machines WHERE unique_machine_no = ? AND id != ? LIMIT 1");
        $checkStmt->execute([$unique_machine_no, $id]);

        if ($checkStmt->fetch()) {
            $error = 'Another machine already uses this Machine No.';
        } else {

            $stmt = $pdo->prepare("
                UPDATE machines
                SET unique_machine_no = ?,
                    customer_id = ?,
                    machine_model = ?,
                    serial_no = ?,
                    customer_name = ?,
                    location_text = ?,
                    meter_date = ?,
                    main_email = ?,
                    invoice_email = ?,
                    cc_email = ?,
                    telephone = ?,
                    status = ?
                WHERE id = ?
            ");

            $stmt->execute([
                $unique_machine_no,
                $customer_id !== '' ? $customer_id : null,
                $machine_model,
                $serial_no,
                $customer_name,
                $location_text,
                $meter_date ?: null,
                $main_email,
                $invoice_email,
                $cc_email,
                $telephone,
                $status,
                $id
            ]);

            $message = 'Machine updated successfully.';
        }
    }
}

/*
|--------------------------------------------------------------------------
| Delete Machine
|--------------------------------------------------------------------------
*/
if (isset($_GET['delete'])) {

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

    if ($id > 0) {
        $stmt = $pdo->prepare("DELETE FROM machines WHERE id = ?");
        $stmt->execute([$id]);
        $message = 'Machine deleted.';
    }
}

/*
|--------------------------------------------------------------------------
| Edit Mode
|--------------------------------------------------------------------------
*/


/*
|--------------------------------------------------------------------------
| Machine Statistics
|--------------------------------------------------------------------------
*/
$totalMachines    = $pdo->query("SELECT COUNT(*) FROM machines")->fetchColumn();
$activeMachines   = $pdo->query("SELECT COUNT(*) FROM machines WHERE status = 'active'")->fetchColumn();
$inactiveMachines = $pdo->query("SELECT COUNT(*) FROM machines WHERE status = 'inactive'")->fetchColumn();
$retiredMachines  = $pdo->query("SELECT COUNT(*) FROM machines WHERE status = 'retired'")->fetchColumn();


/*
|--------------------------------------------------------------------------
| Machine List
|--------------------------------------------------------------------------
| Oldest to newest so row number starts naturally from 1 -> total
|--------------------------------------------------------------------------
*/
$stmt = $pdo->query("SELECT * FROM machines ORDER BY id ASC");
$machines = $stmt->fetchAll();
$machineCount = count($machines);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Machines</title>
    <link rel="stylesheet" href="css/style.css?v=1">

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f3f6fb;
            color: #111827;
        }

        .container {
            max-width: 1200px;
            margin: 24px auto;
            padding: 0 16px;
        }

        .section {
            background: #fff;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05);
            margin-bottom: 20px;
        }

        h1, h2 {
            margin-top: 0;
        }

        .message {
            background: #dcfce7;
            color: #166534;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }

        .error {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 14px;
            margin-bottom: 20px;
        }

        .stat-card {
            color: #fff;
            padding: 16px 18px;
            border-radius: 14px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.08);
        }

        .stat-card b {
            display: block;
            font-size: 14px;
            margin-bottom: 6px;
        }

        .stat-number {
            font-size: 24px;
            font-weight: bold;
        }

        .stat-total {
            background: #2563eb;
        }

        .stat-active {
            background: #16a34a;
        }

        .stat-inactive {
            background: #f59e0b;
        }

        .stat-retired {
            background: #dc2626;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 16px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            font-weight: bold;
            margin-bottom: 6px;
            font-size: 14px;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            font-size: 14px;
            background: #fff;
        }

        .full-width {
            grid-column: 1 / -1;
        }

        .btn {
            background: #2563eb;
            color: #fff;
            border: none;
            padding: 11px 16px;
            border-radius: 10px;
            cursor: pointer;
            font-weight: bold;
        }

        .btn:hover {
            background: #1d4ed8;
        }

        .table-wrap {
            width: 100%;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            text-align: left;
            padding: 12px 10px;
            border-bottom: 1px solid #e5e7eb;
            font-size: 14px;
            vertical-align: top;
        }

        th {
            background: #f8fafc;
            white-space: nowrap;
        }

        .action-links a {
            margin-right: 10px;
            text-decoration: none;
            color: #2563eb;
            font-weight: bold;
        }

        .action-links a:hover {
            text-decoration: underline;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-active {
            background: #dcfce7;
            color: #166534;
        }

        .status-inactive,
        .status-retired {
            background: #fee2e2;
            color: #991b1b;
        }

        .number-col {
            width: 60px;
            text-align: center;
            font-weight: bold;
            color: #374151;
        }

        .mobile-label{
            display:none;
        }

        .modal-overlay {
            position: fixed;
            inset: 0;
            background: rgba(15, 23, 42, 0.45);
            display: none;
            align-items: center;
            justify-content: center;
            padding: 20px;
            z-index: 9999;
        }

        .modal-overlay.show {
            display: flex;
        }

        .modal-box {
            width: min(1100px, 100%);
            max-height: 90vh;
            overflow-y: auto;
            background: #fff;
            border-radius: 20px;
            padding: 24px;
            box-shadow: 0 20px 50px rgba(0,0,0,0.18);
        }

        .modal-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 18px;
        }

        .modal-close {
            border: none;
            background: #f3f4f6;
            width: 40px;
            height: 40px;
            border-radius: 10px;
            font-size: 24px;
            line-height: 1;
            cursor: pointer;
            color: #111827;
        }

        .modal-close:hover {
            background: #e5e7eb;
        }
        .action-cell {
    width: 70px;
    text-align: center;
    vertical-align: middle;
}

.action-menu {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}

.action-btn {
    width: 32px;
    height: 32px;
    border: none;
    border-radius: 8px;
    background: transparent;
    cursor: pointer;
}

.action-btn:hover {
    background: #f3f4f6;
}

.action-dots {
    display: flex;
    flex-direction: column;
    gap: 2px;
    align-items: center;
}

.action-dots span {
    width: 3px;
    height: 3px;
    background: #6b7280;
    border-radius: 999px;
}

.action-dropdown {
    position: absolute;
    top: calc(100% + 6px);
    right: 0;
    min-width: 120px;
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 10px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    display: none;
    z-index: 100;
}

.action-dropdown.show {
    display: block;
}

.action-dropdown a {
    display: block;
    padding: 8px 12px;
    text-decoration: none;
    color: #111827;
    font-size: 13px;
}

.action-dropdown a:hover {
    background: #f9fafb;
}

.action-dropdown .delete-link {
    color: #dc2626;
    font-weight: bold;
}
.machine-toolbar {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
    margin-bottom: 16px;
}

.machine-toolbar-top {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
}

.csv-upload-row {
    margin-left: auto;
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: nowrap;
    min-width: 0;
}

.csv-file-input {
    min-width: 260px;
    max-width: 420px;
    padding: 8px 10px;
    border: 1px solid #d1d5db;
    border-radius: 10px;
    font-size: 13px;
    background: #fff;
}

.csv-upload-btn,
.export-btn {
    white-space: nowrap;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 10px 14px;
    border-radius: 10px;
}

.export-row {
    display: flex;
    align-items: center;
}

/* tablet */
@media (max-width: 900px) {
    .stats-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
}

/* mobile */
@media (max-width: 768px) {
    .form-grid {
        grid-template-columns: 1fr;
    }

    .stats-grid {
        grid-template-columns: 1fr;
    }

    .desktop-label {
        display: none;
    }

    .mobile-label {
        display: inline;
    }

    .machine-toolbar {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
    }

    .machine-toolbar-top {
        width: 100%;
        justify-content: space-between;
        gap: 10px;
    }

    .csv-upload-row {
        margin-left: 0;
        width: 100%;
        gap: 8px;
    }

    .csv-file-input {
        flex: 1;
        min-width: 0;
        max-width: none;
        width: 100%;
        font-size: 12px;
        padding: 8px;
    }

    .csv-upload-btn {
        flex: 0 0 auto;
        padding: 9px 12px;
        font-size: 12px;
    }

    .export-row {
        width: 100%;
    }

    .export-btn {
        align-self: flex-start;
    }
}

       
    </style>
</head>
<body>
    <?php include 'header.php'; ?>

    <div style="margin:20px 0;">
        <a href="admin-dashboard.php"
           style="display:inline-block;background:#2563eb;color:#fff;padding:8px 14px;border-radius:8px;text-decoration:none;font-weight:bold;">
           ← Dashboard
        </a>
    </div>

    <div class="container">

       <div id="machineModal" class="modal-overlay">
            <div class="modal-box">
                <div class="modal-header">
                    <h2 id="machineModalTitle" style="margin:0;">Add Machine</h2>
                    <button type="button" class="modal-close" onclick="closeMachineModal()">×</button>
                </div>

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

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

                <form method="POST">
                    <input type="hidden" name="id" id="machine_id">

                    <div class="form-grid">
                        <div class="form-group">
                            <label>Machine No</label>
                            <input id="unique_machine_no" name="unique_machine_no" required>
                        </div>

                        <div class="form-group">
                            <label>Customer ID</label>
                            <input id="customer_id" name="customer_id">
                        </div>

                        <div class="form-group">
                            <label>Machine Model</label>
                            <input id="machine_model" name="machine_model" required>
                        </div>

                        <div class="form-group">
                            <label>Serial No</label>
                            <input id="serial_no" name="serial_no">
                        </div>

                        <div class="form-group">
                            <label>Customer Name</label>
                            <input id="customer_name" name="customer_name" required>
                        </div>

                        <div class="form-group">
                            <label>Location</label>
                            <input id="location_text" name="location_text">
                        </div>

                        <div class="form-group">
                            <label>Meter Date / Meter Number</label>
                            <input id="meter_date" name="meter_date">
                        </div>

                        <div class="form-group">
                            <label>Telephone</label>
                            <input id="telephone" name="telephone">
                        </div>

                        <div class="form-group full-width">
                            <label>Status</label>
                            <select id="status" name="status">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                                <option value="retired">Retired</option>
                            </select>
                        </div>

                        <div class="form-group full-width">
                            <button id="machineSubmitBtn" type="submit" name="add_machine" class="btn">
                                Add Machine
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
</div> 

        

        <div class="section">
            <div class="stats-grid">
                <div class="stat-card stat-total">
                    <b>Total Machines</b>
                    <div class="stat-number"><?= $totalMachines ?></div>
                </div>

                <div class="stat-card stat-active">
                    <b>Active</b>
                    <div class="stat-number"><?= $activeMachines ?></div>
                </div>

                <div class="stat-card stat-inactive">
                    <b>Inactive</b>
                    <div class="stat-number"><?= $inactiveMachines ?></div>
                </div>

                <div class="stat-card stat-retired">
                    <b>Retired</b>
                    <div class="stat-number"><?= $retiredMachines ?></div>
                </div>
            </div>

            
            <div class="machine-toolbar">
                <div class="machine-toolbar-top">
                    <h2 style="margin:0;">Machine List (<?= $machineCount ?>)</h2>

                    <button type="button" class="btn" onclick="openAddMachineModal()">
                        Add New Machine
                    </button>
                </div>

                <form method="POST" enctype="multipart/form-data" class="csv-upload-row">
                    <input type="file" name="machines_csv" accept=".csv" required class="csv-file-input">

                    <button type="submit" name="upload_machines_csv" class="btn csv-upload-btn">
                        Upload csv file
                    </button>
                </form>

                <div class="export-row">
                    <a href="machines.php?export=excel" class="btn export-btn">
                        Export Excel
                    </a>
                </div>
            </div>

            <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th class="number-col">#</th>
                            <th>
                                <span class="desktop-label">Machine No</span>
                                <span class="mobile-label">M_No</span>
                            </th>
                            <th>
                                <span class="desktop-label">Customer ID</span>
                                <span class="mobile-label">Cust ID</span>
                            </th>
                            <th>Model</th>
                            <th>Customer Name</th>
                            <th>Location</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($machines): ?>
                            <?php $i = 1; ?>
                            <?php foreach ($machines as $m): ?>
                                <tr>
                                    <td class="number-col"><?= $i++ ?></td>
                                    <td><?= esc($m['unique_machine_no']) ?></td>
                                    <td><?= esc($m['customer_id']) ?></td>
                                    <td><?= esc($m['machine_model']) ?></td>
                                    <td><?= esc($m['customer_name']) ?></td>
                                    <td><?= esc($m['location_text']) ?></td>
                                    <td>
                                        <span class="status-badge status-<?= esc($m['status']) ?>">
                                            <?= esc($m['status']) ?>
                                        </span>
                                    </td>
                                    <td class="action-cell">
                                        <div class="action-menu">
                                            <button type="button" class="action-btn" onclick="toggleActionMenu(this)">
                                                <span class="action-dots">
                                                    <span></span>
                                                    <span></span>
                                                    <span></span>
                                                </span>
                                            </button>

                                            <div class="action-dropdown">
                                                <a href="#"
                                                onclick="event.preventDefault(); openEditMachineModal(this);"
                                                data-id="<?= (int)$m['id'] ?>"
                                                data-unique_machine_no="<?= esc($m['unique_machine_no']) ?>"
                                                data-customer_id="<?= esc($m['customer_id']) ?>"
                                                data-machine_model="<?= esc($m['machine_model']) ?>"
                                                data-serial_no="<?= esc($m['serial_no']) ?>"
                                                data-customer_name="<?= esc($m['customer_name']) ?>"
                                                data-location_text="<?= esc($m['location_text']) ?>"
                                                data-meter_date="<?= esc($m['meter_date']) ?>"
                                                data-telephone="<?= esc($m['telephone']) ?>"
                                                data-status="<?= esc($m['status']) ?>">
                                                    Edit
                                                </a>

                                                <a href="machines.php?delete=<?= (int)$m['id'] ?>"
                                                class="delete-link"
                                                onclick="return confirm('Delete this machine?')">
                                                    Delete
                                                </a>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8">No machine records yet.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>

    <script>
function openMachineModal() {
    document.getElementById('machineModal').classList.add('show');
}

function closeMachineModal() {
    document.getElementById('machineModal').classList.remove('show');
}

function resetForm() {
    document.getElementById('machine_id').value = '';
    document.getElementById('unique_machine_no').value = '';
    document.getElementById('customer_id').value = '';
    document.getElementById('machine_model').value = '';
    document.getElementById('serial_no').value = '';
    document.getElementById('customer_name').value = '';
    document.getElementById('location_text').value = '';
    document.getElementById('meter_date').value = '';
    document.getElementById('telephone').value = '';
    document.getElementById('status').value = 'active';
}

function setMode(mode) {
    const title = document.getElementById('machineModalTitle');
    const btn = document.getElementById('machineSubmitBtn');

    if (mode === 'edit') {
        title.innerText = 'Edit Machine';
        btn.innerText = 'Update Machine';
        btn.name = 'update_machine';
    } else {
        title.innerText = 'Add Machine';
        btn.innerText = 'Add Machine';
        btn.name = 'add_machine';
    }
}

function openAddMachineModal() {
    resetForm();
    setMode('add');
    openMachineModal();
}

function openEditMachineModal(el) {
    resetForm();
    setMode('edit');

    document.getElementById('machine_id').value = el.dataset.id;
    document.getElementById('unique_machine_no').value = el.dataset.unique_machine_no;
    document.getElementById('customer_id').value = el.dataset.customer_id;
    document.getElementById('machine_model').value = el.dataset.machine_model;
    document.getElementById('serial_no').value = el.dataset.serial_no;
    document.getElementById('customer_name').value = el.dataset.customer_name;
    document.getElementById('location_text').value = el.dataset.location_text;
    document.getElementById('meter_date').value = el.dataset.meter_date;
    document.getElementById('telephone').value = el.dataset.telephone;
    document.getElementById('status').value = el.dataset.status;

    openMachineModal();
}

function toggleActionMenu(btn) {
    const dropdown = btn.nextElementSibling;
    document.querySelectorAll('.action-dropdown').forEach(d => {
        if (d !== dropdown) d.classList.remove('show');
    });
    dropdown.classList.toggle('show');
}

document.addEventListener('click', function(e) {
    if (!e.target.closest('.action-menu')) {
        document.querySelectorAll('.action-dropdown').forEach(d => d.classList.remove('show'));
    }

    if (e.target.id === 'machineModal') {
        closeMachineModal();
    }
});
</script>
<?php if ((isset($_POST['add_machine']) && $error) || (isset($_POST['update_machine']) && $error)): ?>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        openMachineModal();
    });
</script>
<?php endif; ?>
</body>
</html>