<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: scoring_formats.php');
    exit();
}

$formatId = $_POST['format_id'] ?? null;
if (!$formatId) {
    header('Location: scoring_formats.php');
    exit();
}

try {
    // Check if 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) {
        $_SESSION['error_message'] = 'Format not found.';
        header('Location: scoring_formats.php');
        exit();
    }
    
    // Check permissions - only admins can delete formats
    if ($format['role'] !== 'admin') {
        $_SESSION['error_message'] = 'Insufficient permissions to delete formats.';
        header('Location: scoring_formats.php');
        exit();
    }
    
    // Check if format is being used in any events
    $usageQuery = $pdo->prepare("SELECT COUNT(*) as usage_count FROM events WHERE scoring_format_id = ?");
    $usageQuery->execute([$formatId]);
    $usage = $usageQuery->fetch(PDO::FETCH_ASSOC);
    
    if ($usage['usage_count'] > 0) {
        $_SESSION['error_message'] = 'Cannot delete format that is being used by active events.';
        header('Location: scoring_format_view.php?id=' . $formatId);
        exit();
    }
    
    $pdo->beginTransaction();
    
    // Delete related data first (if any foreign key constraints exist)
    // Delete from dependent tables in correct order
    
    // Delete mode configurations
    $deleteModeConfigs = $pdo->prepare("DELETE FROM mode_configurations WHERE format_id = ?");
    $deleteModeConfigs->execute([$formatId]);
    
    // Delete rounds
    $deleteRounds = $pdo->prepare("DELETE FROM rounds WHERE format_id = ?");
    $deleteRounds->execute([$formatId]);
    
    // Delete criteria
    $deleteCriteria = $pdo->prepare("DELETE FROM criteria WHERE format_id = ?");
    $deleteCriteria->execute([$formatId]);
    
    // Delete flow stages
    $deleteFlowStages = $pdo->prepare("DELETE FROM flow_stages WHERE format_id = ?");
    $deleteFlowStages->execute([$formatId]);
    
    // Delete result headers
    $deleteResultHeaders = $pdo->prepare("DELETE FROM result_headers WHERE format_id = ?");
    $deleteResultHeaders->execute([$formatId]);
    
    // Delete tiebreak rules
    $deleteTiebreakRules = $pdo->prepare("DELETE FROM tiebreak_rules WHERE format_id = ?");
    $deleteTiebreakRules->execute([$formatId]);
    
    // Finally, delete the main format
    $deleteFormat = $pdo->prepare("DELETE FROM scoring_formats WHERE format_id = ?");
    $deleteFormat->execute([$formatId]);
    
    if ($deleteFormat->rowCount() === 0) {
        $pdo->rollBack();
        $_SESSION['error_message'] = 'Failed to delete format.';
        header('Location: scoring_format_view.php?id=' . $formatId);
        exit();
    }
    
    // Log the deletion for audit trail
    $logQuery = $pdo->prepare("INSERT INTO admin_logs (user_id, action, details, created_at) VALUES (?, ?, ?, NOW())");
    $logDetails = json_encode([
        'action' => 'delete_scoring_format',
        'format_id' => $formatId,
        'format_name' => $format['name'],
        'user_ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ]);
    
    try {
        $logQuery->execute([$_SESSION['user_id'], 'delete_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();
    
    $_SESSION['success_message'] = 'Scoring format "' . htmlspecialchars($format['name']) . '" has been deleted successfully.';
    header('Location: scoring_formats.php');
    exit();
    
} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    error_log("Database error in scoring_format_delete.php: " . $e->getMessage());
    $_SESSION['error_message'] = 'Database error occurred while deleting format.';
    header('Location: scoring_format_view.php?id=' . $formatId);
    exit();
    
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    error_log("General error in scoring_format_delete.php: " . $e->getMessage());
    $_SESSION['error_message'] = 'An unexpected error occurred while deleting format.';
    header('Location: scoring_format_view.php?id=' . $formatId);
    exit();
}
?>
