<?php
session_start();
require_once('../config.php');

// Check if user is logged in
if (!is_logged_in()) {
    redirect(BASE_URL . 'login.php');
}

$user = get_current_user();
if (!$user || !is_array($user)) {
    $user = ['id' => $_SESSION['user_id'] ?? null, 'username' => $_SESSION['username'] ?? 'User', 'garage_name' => 'My Garage'];
}

$customers = [];
$error = '';
$success = '';

// Fetch customers for this user
try {
    global $pdo;
    $stmt = $pdo->prepare("SELECT id, customer_name, email, address, postcode, phone, vehicle_make, vehicle_model, created_at FROM customers WHERE user_id = ? ORDER BY created_at DESC");
    $stmt->execute([$user['id']]);
    $customers = $stmt->fetchAll();
} catch (Exception $e) {
    $error = 'Error loading customers: ' . $e->getMessage();
}

// Handle add customer
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_customer') {
    $customer_name = trim($_POST['customer_name'] ?? '');
    $email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
    $address = trim($_POST['address'] ?? '');
    $postcode = trim($_POST['postcode'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $vehicle_make = trim($_POST['vehicle_make'] ?? '');
    $vehicle_model = trim($_POST['vehicle_model'] ?? '');

    if (empty($customer_name)) {
        $error = 'Customer name is required';
    } else {
        try {
            global $pdo;
            $stmt = $pdo->prepare("INSERT INTO customers (user_id, customer_name, email, address, postcode, phone, vehicle_make, vehicle_model) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            if ($stmt->execute([$user['id'], $customer_name, $email, $address, $postcode, $phone, $vehicle_make, $vehicle_model])) {
                $success = 'Customer added successfully';
                // Refresh
                $stmt = $pdo->prepare("SELECT id, customer_name, email, address, postcode, phone, vehicle_make, vehicle_model, created_at FROM customers WHERE user_id = ? ORDER BY created_at DESC");
                $stmt->execute([$user['id']]);
                $customers = $stmt->fetchAll();
            }
        } catch (Exception $e) {
            $error = 'Error adding customer: ' . $e->getMessage();
        }
    }
}

// Handle logout
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'logout') {
    session_destroy();
    redirect(BASE_URL . 'login.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customers - Document Signing System</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            font-size: 28px;
            margin: 0;
        }
        .user-info {
            text-align: right;
        }
        .user-info p {
            margin: 5px 0;
            font-size: 14px;
        }
        .logout-btn {
            background: #ff6b6b;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            margin-top: 10px;
            font-size: 14px;
        }
        .logout-btn:hover {
            background: #ff5252;
        }
        .nav-menu {
            background: #f8f9fa;
            padding: 15px 30px;
            border-bottom: 1px solid #ddd;
            display: flex;
            gap: 20px;
        }
        .nav-menu a {
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
            padding: 10px 15px;
            border-bottom: 2px solid transparent;
        }
        .nav-menu a:hover, .nav-menu a.active {
            border-bottom-color: #667eea;
        }
        .content {
            padding: 40px;
        }
        .section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 40px;
            margin-bottom: 40px;
        }
        .form-section {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 8px;
        }
        .form-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 600;
            font-size: 14px;
        }
        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .alert-error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .alert-success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .customers-table {
            width: 100%;
            border-collapse: collapse;
        }
        .customers-table th {
            background: #f8f9fa;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #333;
            border-bottom: 2px solid #ddd;
            font-size: 12px;
        }
        .customers-table td {
            padding: 15px;
            border-bottom: 1px solid #ddd;
            font-size: 13px;
        }
        .customers-table tr:hover {
            background: #f8f9fa;
        }
        .customers-list {
            background: white;
        }
        .customers-list h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 20px;
        }
        @media (max-width: 768px) {
            .section {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>👥 Customers</h1>
            <div class="user-info">
                <p><strong><?php echo htmlspecialchars($user['garage_name'] ?? 'My Garage'); ?></strong></p>
                <p><?php echo htmlspecialchars($user['username'] ?? 'User'); ?></p>
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="action" value="logout">
                    <button type="submit" class="logout-btn">Logout</button>
                </form>
            </div>
        </div>

        <div class="nav-menu">
            <a href="<?php echo BASE_URL; ?>admin-dashboard.php">Dashboard</a>
            <a href="<?php echo BASE_URL; ?>manage-categories.php">Categories</a>
            <a href="<?php echo BASE_URL; ?>manage-forms.php">Forms</a>
            <a href="<?php echo BASE_URL; ?>customers.php" class="active">Customers</a>
            <a href="<?php echo BASE_URL; ?>generate-document.php">Generate Document</a>
        </div>

        <div class="content">
            <?php if ($error): ?>
                <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
            <?php endif; ?>

            <div class="section">
                <!-- Add Customer Form -->
                <div class="form-section">
                    <h2>➕ Add New Customer</h2>
                    <form method="POST">
                        <input type="hidden" name="action" value="add_customer">

                        <div class="form-group">
                            <label for="customer_name">Customer Name *</label>
                            <input type="text" id="customer_name" name="customer_name" required placeholder="Full name">
                        </div>

                        <div class="form-group">
                            <label for="email">Email</label>
                            <input type="email" id="email" name="email" placeholder="customer@example.com">
                        </div>

                        <div class="form-group">
                            <label for="address">Address</label>
                            <input type="text" id="address" name="address" placeholder="Street address">
                        </div>

                        <div class="form-group">
                            <label for="postcode">Postcode</label>
                            <input type="text" id="postcode" name="postcode" placeholder="Postal code">
                        </div>

                        <div class="form-group">
                            <label for="phone">Phone</label>
                            <input type="tel" id="phone" name="phone" placeholder="Phone number">
                        </div>

                        <div class="form-group">
                            <label for="vehicle_make">Vehicle Make</label>
                            <input type="text" id="vehicle_make" name="vehicle_make" placeholder="e.g., Ford">
                        </div>

                        <div class="form-group">
                            <label for="vehicle_model">Vehicle Model</label>
                            <input type="text" id="vehicle_model" name="vehicle_model" placeholder="e.g., Focus">
                        </div>

                        <button type="submit" class="btn">Add Customer</button>
                    </form>
                </div>

                <!-- Customers List -->
                <div class="customers-list">
                    <h2>📋 All Customers (<?php echo count($customers); ?>)</h2>
                    <?php if (count($customers) > 0): ?>
                        <table class="customers-table">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Postcode</th>
                                    <th>Vehicle</th>
                                    <th>Added</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($customers as $cust): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($cust['customer_name']); ?></td>
                                        <td><?php echo htmlspecialchars($cust['email'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($cust['postcode'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars(($cust['vehicle_make'] ?? '') . ' ' . ($cust['vehicle_model'] ?? '')); ?></td>
                                        <td><?php echo date('M d, Y', strtotime($cust['created_at'])); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <p style="color: #999; padding: 20px 0;">No customers yet. Add one above.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
