<!DOCTYPE html>
<html>
<head>
    <title>Scoring Layout Configuration Test</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-4">
        <h2>Scoring Layout Configuration Test</h2>
        
        <?php
        require_once 'includes/db.php';
        
        $message = '';
        
        // Handle form submission
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $event_id = $_POST['event_id'];
            $config_data = $_POST['scoring_layout_config'] ?? null;
            
            if ($config_data) {
                // Process the configuration (same logic as event_edit.php)
                $availableComponents = [
                    'criteriaInputGrid', 'finalCalculatedScore', 'figuresCard', 
                    'latestScores', 'otherHeatScores', 'diversityValidation', 
                    'figureHistory', 'formatInfo'
                ];
                
                if (isset($config_data['cards'])) {
                    foreach ($availableComponents as $component) {
                        if (!isset($config_data['cards'][$component]['enabled'])) {
                            $config_data['cards'][$component]['enabled'] = false;
                        } else {
                            $config_data['cards'][$component]['enabled'] = 
                                ($config_data['cards'][$component]['enabled'] == '1');
                        }
                    }
                }
                
                if (isset($config_data['layout']['compactMode'])) {
                    $config_data['layout']['compactMode'] = 
                        ($config_data['layout']['compactMode'] == '1');
                }
                if (isset($config_data['layout']['hideEmptyCards'])) {
                    $config_data['layout']['hideEmptyCards'] = 
                        ($config_data['layout']['hideEmptyCards'] == '1');
                }
                
                $config_json = json_encode($config_data);
                
                // Save to database
                try {
                    $stmt = $pdo->prepare("UPDATE events SET scoring_layout_config = ? WHERE id = ?");
                    $result = $stmt->execute([$config_json, $event_id]);
                    
                    if ($result) {
                        $message = '<div class="alert alert-success">Configuration saved successfully! JSON: ' . 
                                 htmlspecialchars($config_json) . '</div>';
                    } else {
                        $message = '<div class="alert alert-danger">Failed to save configuration!</div>';
                    }
                } catch (Exception $e) {
                    $message = '<div class="alert alert-danger">Database error: ' . $e->getMessage() . '</div>';
                }
            } else {
                $message = '<div class="alert alert-warning">No configuration data received!</div>';
            }
        }
        
        // Load test event
        $events_query = $pdo->query("SELECT id, name, scoring_layout_config FROM events ORDER BY id DESC LIMIT 5");
        $events = $events_query->fetchAll(PDO::FETCH_ASSOC);
        
        $selected_event_id = $_POST['event_id'] ?? $events[0]['id'] ?? null;
        $current_config = [];
        
        if ($selected_event_id) {
            $config_query = $pdo->prepare("SELECT scoring_layout_config FROM events WHERE id = ?");
            $config_query->execute([$selected_event_id]);
            $config_raw = $config_query->fetchColumn();
            
            if ($config_raw) {
                $current_config = json_decode($config_raw, true) ?? [];
            }
        }
        
        echo $message;
        ?>
        
        <form method="POST">
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Test Event</label>
                        <select class="form-select" name="event_id" onchange="this.form.submit()">
                            <?php foreach ($events as $event): ?>
                                <option value="<?= $event['id'] ?>" <?= $event['id'] == $selected_event_id ? 'selected' : '' ?>>
                                    Event <?= $event['id'] ?>: <?= htmlspecialchars($event['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <?php if ($selected_event_id): ?>
                        <div class="mb-3">
                            <label class="form-label">Current Configuration</label>
                            <textarea class="form-control" rows="4" readonly><?php
                                if (!empty($current_config)) {
                                    echo json_encode($current_config, JSON_PRETTY_PRINT);
                                } else {
                                    echo "No configuration saved";
                                }
                            ?></textarea>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-6">
                    <h5>Component Settings</h5>
                    
                    <?php
                    $components = [
                        'criteriaInputGrid' => 'Criteria Scoring Grid',
                        'finalCalculatedScore' => 'Final Score Display',
                        'figuresCard' => 'Figures Selection Card',
                        'latestScores' => 'Latest Scores Table',
                        'otherHeatScores' => 'Other Judges Scores',
                        'diversityValidation' => 'Diversity Validation',
                        'figureHistory' => 'Figure History',
                        'formatInfo' => 'Format Information Card'
                    ];
                    
                    foreach ($components as $key => $title):
                        $isEnabled = $current_config['cards'][$key]['enabled'] ?? true;
                    ?>
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="checkbox" 
                                   name="scoring_layout_config[cards][<?= $key ?>][enabled]" 
                                   id="<?= $key ?>" 
                                   value="1" <?= $isEnabled ? 'checked' : '' ?>>
                            <label class="form-check-label" for="<?= $key ?>">
                                <?= htmlspecialchars($title) ?>
                            </label>
                        </div>
                    <?php endforeach; ?>
                    
                    <hr>
                    <h6>Layout Options</h6>
                    
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="checkbox" 
                               name="scoring_layout_config[layout][compactMode]" 
                               id="compactMode" 
                               value="1" <?= ($current_config['layout']['compactMode'] ?? false) ? 'checked' : '' ?>>
                        <label class="form-check-label" for="compactMode">
                            Compact Mode
                        </label>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" 
                               name="scoring_layout_config[layout][hideEmptyCards]" 
                               id="hideEmptyCards" 
                               value="1" <?= ($current_config['layout']['hideEmptyCards'] ?? false) ? 'checked' : '' ?>>
                        <label class="form-check-label" for="hideEmptyCards">
                            Hide Empty Cards
                        </label>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Save Configuration</button>
                </div>
            </div>
        </form>
        
        <hr>
        <div class="row mt-4">
            <div class="col">
                <h5>Quick Actions</h5>
                <a href="setup_scoring_layout_db.php" class="btn btn-info btn-sm">Setup Database</a>
                <a href="test_scoring_layout_db.php" class="btn btn-secondary btn-sm">Test Database</a>
                <a href="admin/event_edit.php?id=<?= $selected_event_id ?>" class="btn btn-success btn-sm">Edit Event</a>
            </div>
        </div>
    </div>
</body>
</html>