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

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

$user = get_current_user();
if (!$user || $user['role'] !== 'admin') {
    redirect(BASE_URL . 'admin-dashboard.php');
}

$categories = [];
$forms = [];
$error = '';
$success = '';
$selected_category = $_GET['category'] ?? null;

// Fetch all 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, description 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();
    }
}

// Handle save form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_form') {
    $form_id = $_POST['form_id'] ?? null;
    $category_id = intval($_POST['category_id'] ?? 0);
    $form_name = trim($_POST['form_name'] ?? '');
    $form_desc = trim($_POST['form_description'] ?? '');
    $form_fields = $_POST['form_fields'] ?? '[]';

    if (empty($form_name) || $category_id <= 0) {
        $error = 'Form name and category are required';
    } else {
        try {
            global $pdo;
            // Validate JSON
            json_decode($form_fields);
            if (json_last_error() !== JSON_ERROR_NONE) {
                $error = 'Invalid field configuration';
            } else {
                if ($form_id) {
                    $stmt = $pdo->prepare("UPDATE form_templates SET form_name = ?, description = ?, form_fields = ?, created_by = ? WHERE id = ?");
                    $stmt->execute([$form_name, $form_desc, $form_fields, $user['id'], $form_id]);
                } else {
                    $stmt = $pdo->prepare("INSERT INTO form_templates (category_id, form_name, description, form_fields, created_by) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([$category_id, $form_name, $form_desc, $form_fields, $user['id']]);
                }
                $success = 'Form saved successfully';
                // Refresh
                $stmt = $pdo->prepare("SELECT id, form_name, description FROM form_templates WHERE category_id = ? ORDER BY id ASC");
                $stmt->execute([$category_id]);
                $forms = $stmt->fetchAll();
            }
        } catch (Exception $e) {
            $error = 'Error saving form: ' . $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>Manage Forms - 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;
        }
        .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;
        }
        .category-selector {
            margin-bottom: 30px;
        }
        .category-selector label {
            display: block;
            margin-bottom: 10px;
            color: #333;
            font-weight: 600;
            font-size: 14px;
        }
        .category-selector select {
            width: 100%;
            max-width: 300px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        .form-builder {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 8px;
            display: none;
        }
        .form-builder.active {
            display: block;
        }
        .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 textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        .form-group textarea {
            min-height: 80px;
            resize: vertical;
        }
        .form-group input: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);
        }
        .fields-section {
            margin-top: 30px;
            padding-top: 30px;
            border-top: 2px solid #ddd;
        }
        .fields-section h3 {
            color: #333;
            margin-bottom: 15px;
        }
        .field-item {
            background: white;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .field-info {
            flex: 1;
        }
        .field-label {
            color: #333;
            font-weight: 600;
            margin-bottom: 3px;
        }
        .field-type {
            color: #999;
            font-size: 12px;
        }
        .field-actions {
            display: flex;
            gap: 10px;
        }
        .btn-delete {
            background: #ff6b6b;
            padding: 8px 12px;
            font-size: 12px;
        }
        .btn-delete:hover {
            background: #ff5252;
        }
        .add-field-form {
            background: white;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
        }
        .field-row {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr auto;
            gap: 10px;
            margin-bottom: 10px;
        }
        .field-row input, .field-row select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 3px;
            font-size: 12px;
        }
        .btn-small {
            padding: 8px 15px;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📝 Manage Forms</h1>
            <div class="user-info">
                <p><strong><?php echo htmlspecialchars($user['garage_name'] ?? '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" class="active">Forms</a>
            <a href="<?php echo BASE_URL; ?>customers.php">Customers</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="category-selector">
                <label for="category_select">Select Category:</label>
                <select id="category_select" onchange="selectCategory(this.value)">
                    <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): ?>
            <div class="form-builder active">
                <h2 style="margin-bottom: 20px;">➕ Create New Form</h2>
                <form method="POST">
                    <input type="hidden" name="action" value="save_form">
                    <input type="hidden" name="form_id" value="">
                    <input type="hidden" name="category_id" value="<?php echo $selected_category; ?>">
                    <input type="hidden" name="form_fields" id="form_fields_data" value="[]">

                    <div class="form-group">
                        <label for="form_name">Form Name *</label>
                        <input type="text" id="form_name" name="form_name" required placeholder="e.g., Service Agreement">
                    </div>

                    <div class="form-group">
                        <label for="form_description">Description</label>
                        <textarea id="form_description" name="form_description" placeholder="Brief description of this form"></textarea>
                    </div>

                    <div class="fields-section">
                        <h3>📋 Form Fields</h3>
                        <p style="color: #999; margin-bottom: 15px; font-size: 12px;">Define the fields that will appear on this form</p>

                        <div class="add-field-form" id="add_field_form">
                            <div class="field-row">
                                <input type="text" id="field_label" placeholder="Field Label (e.g., Customer Name)">
                                <select id="field_type">
                                    <option value="text">Text</option>
                                    <option value="email">Email</option>
                                    <option value="phone">Phone</option>
                                    <option value="date">Date</option>
                                    <option value="textarea">Text Area</option>
                                    <option value="number">Number</option>
                                </select>
                                <input type="checkbox" id="field_required" style="width: auto;"> <label style="display: inline; font-weight: normal; font-size: 12px;">Required</label>
                                <button type="button" class="btn btn-small" onclick="addField()">Add Field</button>
                            </div>
                        </div>

                        <div id="fields_list"></div>
                    </div>

                    <button type="submit" class="btn" style="margin-top: 30px;">Save Form</button>
                </form>
            </div>

            <div style="margin-top: 40px;">
                <h3>📄 Forms in This Category (<?php echo count($forms); ?>)</h3>
                <div style="margin-top: 15px;">
                    <?php if (count($forms) > 0): ?>
                        <?php foreach ($forms as $form): ?>
                            <div class="field-item">
                                <div class="field-info">
                                    <div class="field-label"><?php echo htmlspecialchars($form['form_name']); ?></div>
                                    <div class="field-type"><?php echo htmlspecialchars($form['description'] ?? 'No description'); ?></div>
                                </div>
                                <div class="field-actions">
                                    <button class="btn btn-small" onclick="editForm(<?php echo $form['id']; ?>, '<?php echo htmlspecialchars($form['form_name']); ?>')">Edit</button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p style="color: #999;">No forms in this category yet. Create one above.</p>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        let formFields = [];

        function selectCategory(categoryId) {
            if (categoryId) {
                window.location.href = '?category=' + categoryId;
            }
        }

        function addField() {
            const label = document.getElementById('field_label').value.trim();
            const type = document.getElementById('field_type').value;
            const required = document.getElementById('field_required').checked;

            if (!label) {
                alert('Field label is required');
                return;
            }

            formFields.push({
                label: label,
                type: type,
                required: required
            });

            updateFieldsList();
            document.getElementById('field_label').value = '';
            document.getElementById('field_type').value = 'text';
            document.getElementById('field_required').checked = false;
        }

        function removeField(index) {
            formFields.splice(index, 1);
            updateFieldsList();
        }

        function updateFieldsList() {
            const listDiv = document.getElementById('fields_list');
            if (formFields.length === 0) {
                listDiv.innerHTML = '<p style="color: #999; font-size: 12px;">No fields added yet</p>';
            } else {
                listDiv.innerHTML = formFields.map((field, index) => `
                    <div class="field-item">
                        <div class="field-info">
                            <div class="field-label">${field.label} ${field.required ? '<span style="color: #ff6b6b;">*</span>' : ''}</div>
                            <div class="field-type">${field.type}</div>
                        </div>
                        <button type="button" class="btn btn-delete btn-small" onclick="removeField(${index})">Remove</button>
                    </div>
                `).join('');
            }
            document.getElementById('form_fields_data').value = JSON.stringify(formFields);
        }

        function editForm(formId, formName) {
            alert('Edit functionality coming soon. Form: ' + formName);
        }

        // Initialize
        updateFieldsList();
    </script>
</body>
</html>
