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

$categories = [];
$forms = [];
$form_details = null;
$customers = [];
$error = '';
$success = '';

$selected_category = $_GET['category'] ?? null;
$selected_form = $_GET['form'] ?? null;

// Fetch categories
try {
    global $pdo;
    $stmt = $pdo->prepare("SELECT id, name FROM form_categories ORDER BY display_order ASC");
    $stmt->execute();
    $categories = $stmt->fetchAll();
} catch (Exception $e) {
    $error = 'Error loading categories: ' . $e->getMessage();
}

// Fetch forms for selected category
if ($selected_category) {
    try {
        global $pdo;
        $stmt = $pdo->prepare("SELECT id, form_name FROM form_templates WHERE category_id = ? ORDER BY id ASC");
        $stmt->execute([$selected_category]);
        $forms = $stmt->fetchAll();
    } catch (Exception $e) {
        $error = 'Error loading forms: ' . $e->getMessage();
    }
}

// Fetch form details and customers
if ($selected_form) {
    try {
        global $pdo;
        // Get form details
        $stmt = $pdo->prepare("SELECT id, form_name, form_fields FROM form_templates WHERE id = ?");
        $stmt->execute([$selected_form]);
        $form_details = $stmt->fetch();

        if ($form_details && $form_details['form_fields']) {
            $form_details['fields'] = json_decode($form_details['form_fields'], true);
        }

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

// Handle generate PDF
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'generate_pdf') {
    $form_id = intval($_POST['form_id'] ?? 0);
    $customer_id = intval($_POST['customer_id'] ?? 0);

    // Collect form data
    $form_data = [];
    if (isset($_POST['form_data'])) {
        $form_data = $_POST['form_data'];
    }

    if ($form_id <= 0 || $customer_id <= 0) {
        $error = 'Form and customer are required';
    } else {
        // TODO: Generate PDF here
        $success = 'PDF generation coming soon!';
    }
}

// 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>Generate Document - 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;
        }
        .wizard {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 40px;
        }
        .wizard-section {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 8px;
        }
        .wizard-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 20px;
        }
        .wizard-section.hidden {
            display: none;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 600;
            font-size: 14px;
        }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            font-family: Arial, sans-serif;
        }
        .form-group textarea {
            min-height: 80px;
            resize: vertical;
        }
        .form-group input:focus, .form-group select:focus, .form-group textarea: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;
        }
        .steps {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #ddd;
        }
        .step {
            flex: 1;
            text-align: center;
            padding: 10px;
            background: white;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            color: #999;
        }
        .step.active {
            background: #667eea;
            color: white;
        }
        @media (max-width: 768px) {
            .wizard {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📝 Generate Document</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">Customers</a>
            <a href="<?php echo BASE_URL; ?>generate-document.php" class="active">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="wizard">
                <!-- Step 1: Select Category & Form -->
                <div class="wizard-section">
                    <h2>📂 Step 1: Select Form</h2>
                    <form method="GET" style="display: inline;">
                        <div class="form-group">
                            <label for="category">Category *</label>
                            <select id="category" name="category" required onchange="this.form.submit()">
                                <option value="">-- Choose Category --</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>" <?php echo ($selected_category == $cat['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <?php if ($selected_category && count($forms) > 0): ?>
                        <div class="form-group">
                            <label for="form">Form *</label>
                            <select id="form" name="form" required onchange="this.form.submit()">
                                <option value="">-- Choose Form --</option>
                                <?php foreach ($forms as $f): ?>
                                    <option value="<?php echo $f['id']; ?>" <?php echo ($selected_form == $f['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($f['form_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php endif; ?>
                    </form>
                </div>

                <!-- Step 2: Select Customer & Fill Form -->
                <?php if ($form_details): ?>
                <div class="wizard-section">
                    <h2>📋 Step 2: Fill Form & Generate</h2>
                    <form method="POST">
                        <input type="hidden" name="action" value="generate_pdf">
                        <input type="hidden" name="form_id" value="<?php echo $selected_form; ?>">

                        <div class="form-group">
                            <label for="customer">Select Customer *</label>
                            <select id="customer" name="customer_id" required onchange="loadCustomerData(this.value)">
                                <option value="">-- Choose Customer --</option>
                                <?php foreach ($customers as $cust): ?>
                                    <option value="<?php echo $cust['id']; ?>" data-customer='<?php echo json_encode($cust); ?>'>
                                        <?php echo htmlspecialchars($cust['customer_name'] . ' (' . $cust['postcode'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div style="border-top: 2px solid #ddd; padding-top: 15px; margin-top: 20px;">
                            <h3 style="color: #333; margin-bottom: 15px; font-size: 16px;">Form Fields</h3>
                            <?php if ($form_details['fields']): ?>
                                <?php foreach ($form_details['fields'] as $field): ?>
                                    <div class="form-group">
                                        <label for="field_<?php echo htmlspecialchars($field['label']); ?>">
                                            <?php echo htmlspecialchars($field['label']); ?>
                                            <?php if ($field['required']): ?><span style="color: #ff6b6b;">*</span><?php endif; ?>
                                        </label>
                                        <?php if ($field['type'] === 'textarea'): ?>
                                            <textarea name="form_data[<?php echo htmlspecialchars($field['label']); ?>]" <?php echo $field['required'] ? 'required' : ''; ?>></textarea>
                                        <?php else: ?>
                                            <input type="<?php echo $field['type']; ?>" name="form_data[<?php echo htmlspecialchars($field['label']); ?>]" <?php echo $field['required'] ? 'required' : ''; ?>>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <p style="color: #999;">No fields defined for this form yet.</p>
                            <?php endif; ?>
                        </div>

                        <button type="submit" class="btn" style="margin-top: 20px; width: 100%;">🔄 Generate PDF</button>
                    </form>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        function loadCustomerData(customerId) {
            const select = document.getElementById('customer');
            if (customerId && select.options[select.selectedIndex].dataset.customer) {
                const customer = JSON.parse(select.options[select.selectedIndex].dataset.customer);
                // TODO: Auto-fill form fields with customer data
            }
        }
    </script>
</body>
</html>
