<?php
// returnGIFframes.php
// Returns the frame count, cycle_num, and delay_time for a specific scoring animation

// DEBUG MODE - Set to true to see debug output
$debug = false;

if ($debug) {
    header('Content-Type: text/plain'); // Plain text for debug
} else {
    header('Content-Type: application/json'); // JSON for production
}
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

// Include config file
require_once $_SERVER['DOCUMENT_ROOT'] . '/config.php';

// Default values if not found
$default_response = [
    'frame_count' => 20,
    'cycle_num' => 1,
    'delay_time' => 100
];

// Get input parameter
$input = isset($_GET['input']) ? trim($_GET['input']) : '';

if ($debug) echo "[DEBUG] Raw input received: '$input'\n";

// Validate input format: should be like "MLB_H-1_1_6"
if (empty($input)) {
    if ($debug) echo "[DEBUG] Input is empty, returning default response\n";
    echo json_encode($default_response);
    exit;
}

// Parse the input - Format: {league}_{type}_{gif_type}_{panel_chain}
$parts = explode('_', $input);
if ($debug) echo "[DEBUG] Input split into " . count($parts) . " parts: " . json_encode($parts) . "\n";

if (count($parts) < 4) {
    if ($debug) echo "[DEBUG] Not enough parts (need at least 4), returning default response\n";
    echo json_encode($default_response);
    exit;
}

// Extract components
$league = strtoupper($parts[0]);  // First part is the league (NFL, MLB, etc.)
$panel_chain_raw = intval($parts[count($parts) - 1]);  // Last part is ALWAYS panel_chain

// FAILSAFE: If panel_chain is above 6, cap it at 6
$panel_chain = ($panel_chain_raw > 6) ? 6 : $panel_chain_raw;
if ($debug && $panel_chain_raw > 6) {
    echo "[DEBUG] Panel chain was $panel_chain_raw, capped at 6\n";
}

$gif_type = intval($parts[count($parts) - 2]);  // Second to last part is gif_type (numeric)

// The type is everything between league and the last two parts
$type_parts = array_slice($parts, 1, -2);
$type = implode('_', $type_parts);  // Join them back in case type has underscores (like H-1)

if ($debug) {
    echo "[DEBUG] Parsed values:\n";
    echo "[DEBUG]   - League: '$league'\n";
    echo "[DEBUG]   - Type: '$type'\n";
    echo "[DEBUG]   - Gif_type: $gif_type\n";
    echo "[DEBUG]   - Panel chain (raw): $panel_chain_raw\n";
    echo "[DEBUG]   - Panel chain (used): $panel_chain\n";
}

// Connect to DB
try {
    if ($debug) echo "[DEBUG] Attempting database connection...\n";
    $db = new PDO("mysql:host=$host_gscroll;dbname=$database_gscroll", $username_gscroll, $password_gscroll);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    if ($debug) echo "[DEBUG] Database connected successfully\n";
    
    if ($debug) {
        // Show what's in the database for this league
        $debug_sql = "SELECT league, type, gif_type, panel_chain, frame_count, cycle_num, delay_time 
                      FROM score_animation_frame_mapping 
                      WHERE league = :league";
        $debug_stmt = $db->prepare($debug_sql);
        $debug_stmt->execute([':league' => $league]);
        $debug_results = $debug_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo "[DEBUG] All rows for league '$league':\n";
        foreach ($debug_results as $row) {
            echo "[DEBUG]   - type: '{$row['type']}', gif_type: {$row['gif_type']}, panel_chain: {$row['panel_chain']}, frame_count: {$row['frame_count']}, cycle_num: {$row['cycle_num']}, delay_time: {$row['delay_time']}\n";
        }
    }
    
    // Run the actual query with correct column names
    $sql = "SELECT frame_count, cycle_num, delay_time 
            FROM score_animation_frame_mapping 
            WHERE league = :league 
            AND type = :type
            AND gif_type = :gif_type
            AND panel_chain = :panel_chain
            LIMIT 1";
    
    if ($debug) {
        echo "[DEBUG] Executing query with:\n";
        echo "[DEBUG]   - :league = '$league'\n";
        echo "[DEBUG]   - :type = '$type'\n";
        echo "[DEBUG]   - :gif_type = $gif_type\n";
        echo "[DEBUG]   - :panel_chain = $panel_chain\n";
    }
    
    $stmt = $db->prepare($sql);
    $stmt->execute([
        ':league' => $league,
        ':type' => $type,
        ':gif_type' => $gif_type,
        ':panel_chain' => $panel_chain
    ]);
    
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($result) {
        if ($debug) {
            echo "[DEBUG] Query returned a result:\n";
            echo "[DEBUG]   - Raw result: " . json_encode($result) . "\n";
        }
        
        // Build response with actual values or defaults for missing fields
        $response = [
            'frame_count' => isset($result['frame_count']) ? intval($result['frame_count']) : $default_response['frame_count'],
            'cycle_num' => isset($result['cycle_num']) ? intval($result['cycle_num']) : $default_response['cycle_num'],
            'delay_time' => isset($result['delay_time']) ? intval($result['delay_time']) : $default_response['delay_time']
        ];
        
        if ($debug) {
            echo "[DEBUG] Final response: " . json_encode($response) . "\n";
            echo "\n[FINAL OUTPUT]\n";
        }
        echo json_encode($response);
    } else {
        if ($debug) {
            echo "[DEBUG] No matching row found!\n";
            echo "[DEBUG] Looking for: League='$league', type='$type', gif_type=$gif_type, panel_chain=$panel_chain (Input: $input)\n";
            echo "[DEBUG] Returning default response\n";
            echo "\n[FINAL OUTPUT]\n";
        }
        echo json_encode($default_response);
    }
    
} catch (PDOException $e) {
    if ($debug) {
        echo "[ERROR] Database error in returnGIFframes.php: " . $e->getMessage() . "\n";
        echo "[ERROR] Stack trace: " . $e->getTraceAsString() . "\n";
        echo "\n[FINAL OUTPUT]\n";
    }
    echo json_encode($default_response);
}
?>