<?php
/**
 * Result Configurations API
 * 
 * Manages saved configurations for start lists and summary tables
 */

header('Content-Type: application/json');
include '../includes/auth.php';
include '../includes/db.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? $_POST['action'] ?? '';

// For POST requests with JSON data, extract action from JSON body
if ($method === 'POST' && empty($action)) {
    $json_data = json_decode(file_get_contents('php://input'), true);
    $action = $json_data['action'] ?? '';
}

try {
    switch ($method) {
        case 'GET':
            if ($action === 'list') {
                handleListConfigurations($pdo);
            } elseif ($action === 'get') {
                handleGetConfiguration($pdo);
            } else {
                throw new Exception('Invalid action for GET request');
            }
            break;
            
        case 'POST':
            if ($action === 'save') {
                handleSaveConfiguration($pdo);
            } elseif ($action === 'delete') {
                handleDeleteConfiguration($pdo);
            } elseif ($action === 'update_status') {
                handleUpdateStatus($pdo);
            } else {
                throw new Exception('Invalid action for POST request');
            }
            break;
            
        default:
            throw new Exception('Method not allowed');
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'error_code' => 'API_ERROR'
    ]);
}

function handleListConfigurations($pdo) {
    $event_id = (int)($_GET['event_id'] ?? 0);
    $view_type = $_GET['view_type'] ?? '';
    $status = $_GET['status'] ?? 'active';
    
    if (!$event_id) {
        throw new Exception('Event ID is required');
    }
    
    $query = "
        SELECT 
            rc.*,
            e.name as event_name,
            u.username as created_by_name
        FROM result_configurations rc
        JOIN events e ON rc.event_id = e.id
        JOIN users u ON rc.created_by = u.id
        WHERE rc.event_id = ?
    ";
    
    $params = [$event_id];
    
    if ($view_type) {
        $query .= " AND rc.view_type = ?";
        $params[] = $view_type;
    }
    
    if ($status !== 'all') {
        $query .= " AND rc.status = ?";
        $params[] = $status;
    }
    
    $query .= " ORDER BY rc.display_order ASC, rc.name ASC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $configurations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Parse JSON configurations
    foreach ($configurations as &$config) {
        $config['configuration'] = json_decode($config['configuration'], true);
    }
    
    echo json_encode([
        'success' => true,
        'data' => $configurations,
        'count' => count($configurations)
    ]);
}

function handleGetConfiguration($pdo) {
    $config_id = (int)($_GET['id'] ?? 0);
    
    if (!$config_id) {
        throw new Exception('Configuration ID is required');
    }
    
    $stmt = $pdo->prepare("
        SELECT 
            rc.*,
            e.name as event_name
        FROM result_configurations rc
        JOIN events e ON rc.event_id = e.id
        WHERE rc.id = ?
    ");
    $stmt->execute([$config_id]);
    $config = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$config) {
        throw new Exception('Configuration not found');
    }
    
    $config['configuration'] = json_decode($config['configuration'], true);
    
    echo json_encode([
        'success' => true,
        'data' => $config
    ]);
}

function handleSaveConfiguration($pdo) {
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    $required = ['name', 'view_type', 'event_id', 'configuration'];
    foreach ($required as $field) {
        if (!isset($data[$field]) || empty($data[$field])) {
            throw new Exception("Field '$field' is required");
        }
    }
    
    $config_id = $data['id'] ?? null;
    $name = trim($data['name']);
    $view_type = $data['view_type'];
    $event_id = (int)$data['event_id'];
    $heat_number = isset($data['heat_number']) ? (int)$data['heat_number'] : null;
    $category = $data['category'] ?? null;
    $configuration = json_encode($data['configuration']);
    $display_order = (int)($data['display_order'] ?? 0);
    $status = $data['status'] ?? 'draft';
    $user_id = $_SESSION['user_id'];
    
    if ($config_id) {
        // Update existing configuration
        $stmt = $pdo->prepare("
            UPDATE result_configurations 
            SET name = ?, heat_number = ?, category = ?, configuration = ?, 
                display_order = ?, status = ?, updated_at = NOW()
            WHERE id = ? AND created_by = ?
        ");
        $stmt->execute([
            $name, $heat_number, $category, $configuration, 
            $display_order, $status, $config_id, $user_id
        ]);
        
        if ($stmt->rowCount() === 0) {
            throw new Exception('Configuration not found or no permission to update');
        }
        
        $result_id = $config_id;
        $message = 'Configuration updated successfully';
    } else {
        // Create new configuration
        $stmt = $pdo->prepare("
            INSERT INTO result_configurations 
            (name, view_type, event_id, heat_number, category, configuration, display_order, status, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $name, $view_type, $event_id, $heat_number, $category, 
            $configuration, $display_order, $status, $user_id
        ]);
        
        $result_id = $pdo->lastInsertId();
        $message = 'Configuration saved successfully';
    }
    
    echo json_encode([
        'success' => true,
        'message' => $message,
        'id' => $result_id
    ]);
}

function handleDeleteConfiguration($pdo) {
    $data = json_decode(file_get_contents('php://input'), true);
    $config_id = (int)($data['id'] ?? 0);
    $user_id = $_SESSION['user_id'];
    
    if (!$config_id) {
        throw new Exception('Configuration ID is required');
    }
    
    $stmt = $pdo->prepare("
        DELETE FROM result_configurations 
        WHERE id = ? AND created_by = ?
    ");
    $stmt->execute([$config_id, $user_id]);
    
    if ($stmt->rowCount() === 0) {
        throw new Exception('Configuration not found or no permission to delete');
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Configuration deleted successfully'
    ]);
}

function handleUpdateStatus($pdo) {
    $data = json_decode(file_get_contents('php://input'), true);
    $config_id = (int)($data['id'] ?? 0);
    $status = $data['status'] ?? '';
    $user_id = $_SESSION['user_id'];
    
    if (!$config_id || !in_array($status, ['active', 'draft', 'public', 'private'])) {
        throw new Exception('Invalid configuration ID or status');
    }
    
    $stmt = $pdo->prepare("
        UPDATE result_configurations 
        SET status = ?, updated_at = NOW()
        WHERE id = ? AND created_by = ?
    ");
    $stmt->execute([$status, $config_id, $user_id]);
    
    if ($stmt->rowCount() === 0) {
        throw new Exception('Configuration not found or no permission to update');
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Status updated successfully'
    ]);
}
?>