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

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

/*
|--------------------------------------------------------------------------
| Add Customer
|--------------------------------------------------------------------------
*/
if (isset($_POST['add_customer'])) {
    $customer_name  = trim($_POST['customer_name'] ?? '');
    $contact_person = trim($_POST['contact_person'] ?? '');
    $phone          = trim($_POST['phone'] ?? '');
    $email          = trim($_POST['email'] ?? '');
    $address        = trim($_POST['address'] ?? '');
    $status         = trim($_POST['status'] ?? 'active');

    if ($customer_name === '') {
        $error = 'Customer name is required.';
    } else {
        $stmt = $pdo->prepare("
            INSERT INTO customers (customer_name, contact_person, phone, email, address, status)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$customer_name, $contact_person, $phone, $email, $address, $status]);
        $message = 'Customer added successfully.';
    }
}

/*
|--------------------------------------------------------------------------
| Update Customer
|--------------------------------------------------------------------------
*/
if (isset($_POST['update_customer'])) {
    $id             = (int)($_POST['id'] ?? 0);
    $customer_name  = trim($_POST['customer_name'] ?? '');
    $contact_person = trim($_POST['contact_person'] ?? '');
    $phone          = trim($_POST['phone'] ?? '');
    $email          = trim($_POST['email'] ?? '');
    $address        = trim($_POST['address'] ?? '');
    $status         = trim($_POST['status'] ?? 'active');

    if ($id <= 0 || $customer_name === '') {
        $error = 'Invalid customer data.';
    } else {
        $stmt = $pdo->prepare("
            UPDATE customers
            SET customer_name = ?, contact_person = ?, phone = ?, email = ?, address = ?, status = ?
            WHERE id = ?
        ");
        $stmt->execute([$customer_name, $contact_person, $phone, $email, $address, $status, $id]);
        $message = 'Customer updated successfully.';
    }
}

/*
|--------------------------------------------------------------------------
| Delete Customer
|--------------------------------------------------------------------------
*/
if (isset($_GET['delete'])) {
    $id = (int)($_GET['delete'] ?? 0);

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

/*
|--------------------------------------------------------------------------
| Edit Mode
|--------------------------------------------------------------------------
*/
$editCustomer = null;
if (isset($_GET['edit'])) {
    $id = (int)($_GET['edit'] ?? 0);
    if ($id > 0) {
        $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ? LIMIT 1");
        $stmt->execute([$id]);
        $editCustomer = $stmt->fetch();
    }
}

/*
|--------------------------------------------------------------------------
| Customer List
|--------------------------------------------------------------------------
*/
$stmt = $pdo->query("SELECT * FROM customers ORDER BY id DESC");
$customers = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customers - Service Portal</title>
    <style>
        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f3f6fb;
            color: #111827;
        }
        .topbar {
            background: #0f172a;
            color: white;
            padding: 16px 24px;
        }
        .topbar a {
            color: #93c5fd;
            text-decoration: none;
            margin-right: 14px;
        }
        .container {
            max-width: 1200px;
            margin: 24px auto;
            padding: 0 16px;
        }
        .box {
            background: white;
            padding: 22px;
            border-radius: 16px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05);
            margin-bottom: 20px;
        }
        h1, h2 {
            margin-top: 0;
        }
        .grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 14px;
        }
        .grid-full {
            grid-column: 1 / -1;
        }
        label {
            display: block;
            margin-bottom: 6px;
            font-weight: bold;
            font-size: 14px;
        }
        input, textarea, select {
            width: 100%;
            padding: 11px 12px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            font-size: 14px;
        }
        textarea {
            min-height: 100px;
            resize: vertical;
        }
        button {
            background: #2563eb;
            color: white;
            border: none;
            padding: 12px 18px;
            border-radius: 10px;
            cursor: pointer;
            font-weight: bold;
        }
        button:hover {
            background: #1d4ed8;
        }
        .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;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px 10px;
            border-bottom: 1px solid #e5e7eb;
            text-align: left;
            font-size: 14px;
            vertical-align: top;
        }
        th {
            background: #f8fafc;
        }
        .actions a {
            text-decoration: none;
            margin-right: 10px;
            font-weight: bold;
        }
        .edit-link {
            color: #2563eb;
        }
        .delete-link {
            color: #dc2626;
        }
        @media (max-width: 800px) {
            .grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>

    <div class="topbar">
        <a href="admin-dashboard.php">Dashboard</a>
        <a href="machines.php">Machines</a>
        <a href="logout.php">Logout</a>
    </div>

    <div class="container">
        <div class="box">
            <h1><?= $editCustomer ? 'Edit Customer' : 'Add Customer' ?></h1>

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

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

            <form method="POST">
                <?php if ($editCustomer): ?>
                    <input type="hidden" name="id" value="<?= esc($editCustomer['id']) ?>">
                <?php endif; ?>

                <div class="grid">
                    <div>
                        <label>Customer Name *</label>
                        <input type="text" name="customer_name" required value="<?= esc($editCustomer['customer_name'] ?? '') ?>">
                    </div>

                    <div>
                        <label>Contact Person</label>
                        <input type="text" name="contact_person" value="<?= esc($editCustomer['contact_person'] ?? '') ?>">
                    </div>

                    <div>
                        <label>Phone</label>
                        <input type="text" name="phone" value="<?= esc($editCustomer['phone'] ?? '') ?>">
                    </div>

                    <div>
                        <label>Email</label>
                        <input type="email" name="email" value="<?= esc($editCustomer['email'] ?? '') ?>">
                    </div>

                    <div>
                        <label>Status</label>
                        <select name="status">
                            <option value="active" <?= (($editCustomer['status'] ?? '') === 'active') ? 'selected' : '' ?>>Active</option>
                            <option value="inactive" <?= (($editCustomer['status'] ?? '') === 'inactive') ? 'selected' : '' ?>>Inactive</option>
                        </select>
                    </div>

                    <div class="grid-full">
                        <label>Address</label>
                        <textarea name="address"><?= esc($editCustomer['address'] ?? '') ?></textarea>
                    </div>
                </div>

                <br>

                <?php if ($editCustomer): ?>
                    <button type="submit" name="update_customer">Update Customer</button>
                    <a href="customers.php" style="margin-left:10px; text-decoration:none; color:#374151;">Cancel</a>
                <?php else: ?>
                    <button type="submit" name="add_customer">Add Customer</button>
                <?php endif; ?>
            </form>
        </div>

        <div class="box">
            <h2>Customer List</h2>

            <table>
                <thead>
                    <tr>
                        <th>Customer Name</th>
                        <th>Contact Person</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th>Status</th>
                        <th>Address</th>
                        <th width="140">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($customers): ?>
                        <?php foreach ($customers as $customer): ?>
                            <tr>
                                <td><?= esc($customer['customer_name']) ?></td>
                                <td><?= esc($customer['contact_person']) ?></td>
                                <td><?= esc($customer['phone']) ?></td>
                                <td><?= esc($customer['email']) ?></td>
                                <td><?= esc($customer['status']) ?></td>
                                <td><?= esc($customer['address']) ?></td>
                                <td class="actions">
                                    <a class="edit-link" href="customers.php?edit=<?= esc($customer['id']) ?>">Edit</a>
                                    <a class="delete-link" href="customers.php?delete=<?= esc($customer['id']) ?>" onclick="return confirm('Delete this customer?')">Delete</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7">No customers found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</body>
</html>