<?php
session_start();
header('Content-Type: application/json');

// Check authentication
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit();
}

require_once '../includes/config.php';
require_once '../includes/db.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit();
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['format_id']) || !isset($input['changes'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid input data']);
    exit();
}

$formatId = $input['format_id'];
$changes = $input['changes'];

if (empty($changes)) {
    echo json_encode(['success' => true, 'message' => 'No changes to save']);
    exit();
}

try {
    // Validate format exists and user has permission
    $checkQuery = $pdo->prepare("SELECT sf.*, u.role FROM scoring_formats sf 
                                 JOIN users u ON u.id = ? 
                                 WHERE sf.format_id = ?");
    $checkQuery->execute([$_SESSION['user_id'], $formatId]);
    $format = $checkQuery->fetch(PDO::FETCH_ASSOC);
    
    if (!$format) {
        echo json_encode(['success' => false, 'error' => 'Format not found']);
        exit();
    }
    
    // Check permissions - only admins can edit formats
    if ($format['role'] !== 'admin') {
        echo json_encode(['success' => false, 'error' => 'Insufficient permissions']);
        exit();
    }
    
    // Define allowed fields for security
    $allowedFields = [
        'name' => 'string',
        'is_active' => 'boolean',
        'sport' => 'string',
        'mode' => 'string',
        'min_judges' => 'integer',
        'max_judges' => 'integer',
        'scale_min' => 'numeric',
        'scale_max' => 'numeric',
        'precision_decimal' => 'integer',
        'scale_custom' => 'string',
        'drop_rule' => 'string'
    ];
    
    // Validate and sanitize changes
    $validatedChanges = [];
    $updateFields = [];
    $updateValues = [];
    
    foreach ($changes as $field => $value) {
        if (!array_key_exists($field, $allowedFields)) {
            echo json_encode(['success' => false, 'error' => "Field '$field' is not allowed to be updated"]);
            exit();
        }
        
        $fieldType = $allowedFields[$field];
        
        // Validate and convert value based on type
        switch ($fieldType) {
            case 'boolean':
                $value = $value === '1' || $value === 1 || $value === true ? 1 : 0;
                break;
                
            case 'integer':
                if (!is_numeric($value) || $value < 0) {
                    echo json_encode(['success' => false, 'error' => "Invalid integer value for field '$field'"]);
                    exit();
                }
                $value = (int)$value;
                break;
                
            case 'numeric':
                if (!is_numeric($value)) {
                    echo json_encode(['success' => false, 'error' => "Invalid numeric value for field '$field'"]);
                    exit();
                }
                $value = (float)$value;
                break;
                
            case 'string':
                $value = trim($value);
                if (strlen($value) > 255) {
                    echo json_encode(['success' => false, 'error' => "Value too long for field '$field'"]);
                    exit();
                }
                
                // Additional validation for specific fields
                if ($field === 'sport') {
                    $allowedSports = ['snowboard', 'freeski', 'skateboard', 'bmx', 'inline', 'surf', 'kitesurf', 'parkour', 'breaking', 'wakeboard'];
                    if (!in_array($value, $allowedSports)) {
                        echo json_encode(['success' => false, 'error' => "Invalid sport value"]);
                        exit();
                    }
                }
                
                if ($field === 'mode') {
                    $allowedModes = ['slopestyle', 'halfpipe', 'big_air', 'rail_jam', 'street', 'park', 'vert', 'freestyle', 'battle', 'jam'];
                    if (!in_array($value, $allowedModes)) {
                        echo json_encode(['success' => false, 'error' => "Invalid mode value"]);
                        exit();
                    }
                }
                
                if ($field === 'drop_rule') {
                    $allowedDropRules = ['none', 'highest', 'lowest', 'highest_and_lowest', 'median'];
                    if (!in_array($value, $allowedDropRules)) {
                        echo json_encode(['success' => false, 'error' => "Invalid drop rule value"]);
                        exit();
                    }
                }
                break;
        }
        
        $validatedChanges[$field] = $value;
        $updateFields[] = "$field = ?";
        $updateValues[] = $value;
    }
    
    if (empty($validatedChanges)) {
        echo json_encode(['success' => true, 'message' => 'No valid changes to save']);
        exit();
    }
    
    // Add format_id and updated timestamp
    $updateValues[] = date('Y-m-d H:i:s');
    $updateValues[] = $formatId;
    
    // Build and execute update query
    $updateSQL = "UPDATE scoring_formats SET " . implode(', ', $updateFields) . ", updated_at = ? WHERE format_id = ?";
    
    $pdo->beginTransaction();
    
    $updateQuery = $pdo->prepare($updateSQL);
    $updateQuery->execute($updateValues);
    
    if ($updateQuery->rowCount() === 0) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'error' => 'No rows were updated']);
        exit();
    }
    
    // Log the changes for audit trail
    $logQuery = $pdo->prepare("INSERT INTO admin_logs (user_id, action, details, created_at) VALUES (?, ?, ?, NOW())");
    $logDetails = json_encode([
        'action' => 'update_scoring_format',
        'format_id' => $formatId,
        'changes' => $validatedChanges,
        'user_ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ]);
    
    try {
        $logQuery->execute([$_SESSION['user_id'], 'update_scoring_format', $logDetails]);
    } catch (PDOException $e) {
        // Log error but don't fail the main operation
        error_log("Failed to log admin action: " . $e->getMessage());
    }
    
    $pdo->commit();
    
    // Return success response with updated values
    echo json_encode([
        'success' => true,
        'message' => 'Format updated successfully',
        'updated_values' => $validatedChanges,
        'updated_fields' => array_keys($validatedChanges),
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    error_log("Database error in scoring_format_update.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Database error occurred']);
    
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    error_log("General error in scoring_format_update.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'An unexpected error occurred']);
}
?>
