<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Seasons Management - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
// Current file: /HMSPOS/rooms/rates/seasons.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$base_path = dirname(__DIR__, 3);

// Method 2: If init.php doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/init.php')) {
    // Manual calculation: /HMSPOS/rooms/rates/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/init.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load the universal initializer
$init_file = $base_path . '/config/init.php';
if (file_exists($init_file)) {
    require_once $init_file;
} else {
    // Emergency fallback - load files directly
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/database.php';
    require_once $base_path . '/config/auth.php';
    
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
}

// Require authentication
require_auth();

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define audit constants if not defined
if (!defined('AUDIT_CREATE')) {
    define('AUDIT_CREATE', 'create');
}
if (!defined('AUDIT_UPDATE')) {
    define('AUDIT_UPDATE', 'update');
}
if (!defined('AUDIT_DELETE')) {
    define('AUDIT_DELETE', 'delete');
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if it doesn't exist
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        if (is_array($data)) {
            return array_map('sanitize_input', $data);
        }
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

// Define format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('rates.manage');
// }

// Set page title
$page_title = 'Seasons Management';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Handle form submissions
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $csrf_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
        $token = $_POST[$csrf_name] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $error = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'create':
                $season_name = $_POST['season_name'] ?? '';
                $start_date = $_POST['start_date'] ?? '';
                $end_date = $_POST['end_date'] ?? '';
                $multiplier = (float)($_POST['multiplier'] ?? 1.00);
                
                if (empty($season_name)) {
                    $error = 'Season name is required';
                } elseif (empty($start_date) || empty($end_date)) {
                    $error = 'Start and end dates are required';
                } elseif ($start_date > $end_date) {
                    $error = 'Start date must be before end date';
                } elseif ($multiplier <= 0) {
                    $error = 'Multiplier must be greater than 0';
                } else {
                    try {
                        // Check for overlapping seasons
                        $overlap = (int)db_fetch_value("
                            SELECT COUNT(*) FROM seasons 
                            WHERE is_active = 1
                            AND ((start_date BETWEEN ? AND ?) OR (end_date BETWEEN ? AND ?) OR (? BETWEEN start_date AND end_date))
                        ", [$start_date, $end_date, $start_date, $end_date, $start_date]) ?: 0;
                        
                        if ($overlap > 0) {
                            $error = 'Season dates overlap with existing seasons';
                        } else {
                            if (function_exists('db_insert')) {
                                db_insert('seasons', [
                                    'season_name' => $season_name,
                                    'start_date' => $start_date,
                                    'end_date' => $end_date,
                                    'multiplier' => $multiplier,
                                    'is_active' => 1
                                ]);
                            } else {
                                // Fallback direct insert
                                $pdo = get_db_connection();
                                $sql = "INSERT INTO seasons (season_name, start_date, end_date, multiplier, is_active) 
                                        VALUES (?, ?, ?, ?, 1)";
                                $stmt = $pdo->prepare($sql);
                                $stmt->execute([$season_name, $start_date, $end_date, $multiplier]);
                            }
                            
                            $message = 'Season created successfully';
                            if (function_exists('audit_log')) {
                                audit_log($user_id, 'create', 'seasons', null, null, $_POST);
                            }
                        }
                    } catch (Exception $e) {
                        $error = 'Failed to create season: ' . $e->getMessage();
                        if (function_exists('log_message')) {
                            log_message("Season creation failed: " . $e->getMessage(), 'ERROR');
                        }
                    }
                }
                break;
                
            case 'edit':
                $season_id = (int)($_POST['season_id'] ?? 0);
                $season_name = $_POST['season_name'] ?? '';
                $start_date = $_POST['start_date'] ?? '';
                $end_date = $_POST['end_date'] ?? '';
                $multiplier = (float)($_POST['multiplier'] ?? 1.00);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (!$season_id) {
                    $error = 'Invalid season ID';
                } elseif (empty($season_name)) {
                    $error = 'Season name is required';
                } elseif (empty($start_date) || empty($end_date)) {
                    $error = 'Start and end dates are required';
                } elseif ($start_date > $end_date) {
                    $error = 'Start date must be before end date';
                } elseif ($multiplier <= 0) {
                    $error = 'Multiplier must be greater than 0';
                } else {
                    try {
                        // Check for overlapping seasons (excluding current)
                        $overlap = (int)db_fetch_value("
                            SELECT COUNT(*) FROM seasons 
                            WHERE season_id != ?
                            AND is_active = 1
                            AND ((start_date BETWEEN ? AND ?) OR (end_date BETWEEN ? AND ?) OR (? BETWEEN start_date AND end_date))
                        ", [$season_id, $start_date, $end_date, $start_date, $end_date, $start_date]) ?: 0;
                        
                        if ($overlap > 0) {
                            $error = 'Season dates overlap with existing seasons';
                        } else {
                            $old = db_fetch_one("SELECT * FROM seasons WHERE season_id = ?", [$season_id]);
                            
                            if (function_exists('db_update')) {
                                db_update('seasons', [
                                    'season_name' => $season_name,
                                    'start_date' => $start_date,
                                    'end_date' => $end_date,
                                    'multiplier' => $multiplier,
                                    'is_active' => $is_active
                                ], 'season_id = ?', [$season_id]);
                            } else {
                                // Fallback direct update
                                $pdo = get_db_connection();
                                $sql = "UPDATE seasons SET 
                                        season_name = ?, start_date = ?, end_date = ?, 
                                        multiplier = ?, is_active = ? WHERE season_id = ?";
                                $stmt = $pdo->prepare($sql);
                                $stmt->execute([$season_name, $start_date, $end_date, $multiplier, $is_active, $season_id]);
                            }
                            
                            $message = 'Season updated successfully';
                            if (function_exists('audit_log')) {
                                audit_log($user_id, 'update', 'seasons', $season_id, $old, $_POST);
                            }
                        }
                    } catch (Exception $e) {
                        $error = 'Failed to update season: ' . $e->getMessage();
                        if (function_exists('log_message')) {
                            log_message("Season update failed: " . $e->getMessage(), 'ERROR');
                        }
                    }
                }
                break;
                
            case 'delete':
                $season_id = (int)($_POST['season_id'] ?? 0);
                
                if (!$season_id) {
                    $error = 'Invalid season ID';
                } else {
                    try {
                        // Check if season is used in rate plans
                        $in_use = (int)db_fetch_value("SELECT COUNT(*) FROM rate_plans WHERE season_id = ?", [$season_id]) ?: 0;
                        
                        if ($in_use > 0) {
                            $error = 'Cannot delete season that is used in rate plans';
                        } else {
                            if (function_exists('db_delete')) {
                                db_delete('seasons', 'season_id = ?', [$season_id]);
                            } else {
                                // Fallback direct delete
                                $pdo = get_db_connection();
                                $pdo->prepare("DELETE FROM seasons WHERE season_id = ?")->execute([$season_id]);
                            }
                            
                            $message = 'Season deleted successfully';
                            if (function_exists('audit_log')) {
                                audit_log($user_id, 'delete', 'seasons', $season_id);
                            }
                        }
                    } catch (Exception $e) {
                        $error = 'Failed to delete season: ' . $e->getMessage();
                        if (function_exists('log_message')) {
                            log_message("Season deletion failed: " . $e->getMessage(), 'ERROR');
                        }
                    }
                }
                break;
        }
    }
}

// Get all seasons
$seasons = [];
try {
    $seasons = db_fetch_all("SELECT * FROM seasons ORDER BY start_date DESC") ?: [];
} catch (Exception $e) {
    error_log("Error fetching seasons: " . $e->getMessage());
}

// Get season to edit
$edit_season = null;
if (isset($_GET['edit'])) {
    try {
        $edit_season = db_fetch_one("SELECT * FROM seasons WHERE season_id = ?", [(int)$_GET['edit']]);
    } catch (Exception $e) {
        error_log("Error fetching season for edit: " . $e->getMessage());
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Seasons Management</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Seasons Management</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Seasons Management</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/rooms/dashboard.php">Rooms</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Rates</a></li>
                    <li class="breadcrumb-item active">Seasons</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if (!empty($message)): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Seasons List -->
            <div class="col-md-<?php echo $edit_season ? '7' : '12'; ?>">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-calendar-alt me-1"></i>
                            Seasons
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#createSeasonModal">
                                <i class="fas fa-plus"></i> New Season
                            </button>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($seasons)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-calendar fa-3x mb-3"></i>
                                <p>No seasons defined</p>
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createSeasonModal">
                                    Create First Season
                                </button>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Season Name</th>
                                            <th>Start Date</th>
                                            <th>End Date</th>
                                            <th class="text-end">Multiplier</th>
                                            <th>Duration</th>
                                            <th>Status</th>
                                            <th>Rate Plans</th>
                                            <th width="120">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $today = date('Y-m-d');
                                        foreach ($seasons as $season):
                                            $is_current = ($season['start_date'] ?? '') <= $today && ($season['end_date'] ?? '') >= $today;
                                            $rate_plan_count = 0;
                                            try {
                                                $rate_plan_count = (int)db_fetch_value("SELECT COUNT(*) FROM rate_plans WHERE season_id = ?", [$season['season_id']]) ?: 0;
                                            } catch (Exception $e) {
                                                error_log("Error counting rate plans: " . $e->getMessage());
                                            }
                                        ?>
                                        <tr class="<?php echo $is_current ? 'table-success' : ''; ?>">
                                            <td>
                                                <strong><?php echo escape_html($season['season_name'] ?? ''); ?></strong>
                                            </td>
                                            <td><?php echo !empty($season['start_date']) ? format_date($season['start_date']) : ''; ?></td>
                                            <td><?php echo !empty($season['end_date']) ? format_date($season['end_date']) : ''; ?></td>
                                            <td class="text-end">
                                                <span class="badge bg-info"><?php echo $season['multiplier'] ?? 1; ?>x</span>
                                            </td>
                                            <td>
                                                <?php 
                                                if (!empty($season['start_date']) && !empty($season['end_date'])) {
                                                    $start = new DateTime($season['start_date']);
                                                    $end = new DateTime($season['end_date']);
                                                    $interval = $start->diff($end);
                                                    echo ($interval->days + 1) . ' days';
                                                } else {
                                                    echo '-';
                                                }
                                                ?>
                                            </td>
                                            <td>
                                                <?php if (!empty($season['is_active'])): ?>
                                                    <?php if ($is_current): ?>
                                                        <span class="badge bg-success">Current</span>
                                                    <?php elseif (!empty($season['start_date']) && $season['start_date'] > $today): ?>
                                                        <span class="badge bg-info">Upcoming</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-secondary">Past</span>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span class="badge bg-danger">Inactive</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <span class="badge bg-info"><?php echo $rate_plan_count; ?></span>
                                            </td>
                                            <td>
                                                <div class="btn-group">
                                                    <a href="?edit=<?php echo $season['season_id'] ?? 0; ?>" class="btn btn-sm btn-warning">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    
                                                    <?php if ($rate_plan_count == 0): ?>
                                                        <button type="button" class="btn btn-sm btn-danger" 
                                                                onclick="deleteSeason(<?php echo $season['season_id'] ?? 0; ?>, '<?php echo escape_html($season['season_name'] ?? ''); ?>')">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Edit Form -->
            <?php if ($edit_season): ?>
            <div class="col-md-5">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit me-1"></i>
                            Edit Season: <?php echo escape_html($edit_season['season_name'] ?? ''); ?>
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                        <?php endif; ?>
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="season_id" value="<?php echo $edit_season['season_id'] ?? 0; ?>">
                        
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="edit_season_name">Season Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_season_name" name="season_name" 
                                       value="<?php echo escape_html($edit_season['season_name'] ?? ''); ?>" required>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="edit_start_date">Start Date <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="edit_start_date" name="start_date" 
                                               value="<?php echo $edit_season['start_date'] ?? ''; ?>" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="edit_end_date">End Date <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="edit_end_date" name="end_date" 
                                               value="<?php echo $edit_season['end_date'] ?? ''; ?>" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="edit_multiplier">Rate Multiplier</label>
                                <input type="number" class="form-control" id="edit_multiplier" name="multiplier" 
                                       value="<?php echo $edit_season['multiplier'] ?? 1.00; ?>" step="0.01" min="0.01" required>
                                <small class="text-muted">Base rate will be multiplied by this factor (e.g., 1.5 for 50% increase)</small>
                            </div>
                            
                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input type="checkbox" class="form-check-input" id="edit_is_active" name="is_active"
                                           <?php echo !empty($edit_season['is_active']) ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="edit_is_active">Active</label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-save me-1"></i> Update Season
                            </button>
                            <a href="?" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- Create Season Modal -->
<div class="modal fade" id="createSeasonModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h5 class="modal-title">Create New Season</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            
            <form method="POST">
                <?php if (function_exists('csrf_field')): ?>
                    <?php echo csrf_field(); ?>
                <?php else: ?>
                    <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                <?php endif; ?>
                <input type="hidden" name="action" value="create">
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="season_name">Season Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="season_name" name="season_name" 
                               placeholder="e.g., High Season, Low Season, Christmas" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="start_date">Start Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="start_date" name="start_date" required>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="end_date">End Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="end_date" name="end_date" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="multiplier">Rate Multiplier</label>
                        <input type="number" class="form-control" id="multiplier" name="multiplier" 
                               value="1.00" step="0.01" min="0.01" required>
                        <small class="text-muted">Base rate will be multiplied by this factor</small>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Season</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Season Modal -->
<div class="modal fade" id="deleteSeasonModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Delete Season</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete season <strong id="deleteSeasonName"></strong>?</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteSeasonForm">
                    <?php if (function_exists('csrf_field')): ?>
                        <?php echo csrf_field(); ?>
                    <?php else: ?>
                        <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                    <?php endif; ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="season_id" id="deleteSeasonId">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function deleteSeason(seasonId, seasonName) {
    document.getElementById('deleteSeasonId').value = seasonId;
    document.getElementById('deleteSeasonName').textContent = seasonName;
    
    const modal = new bootstrap.Modal(document.getElementById('deleteSeasonModal'));
    modal.show();
}

// Date validation
$('#start_date, #edit_start_date').on('change', function() {
    const start = $(this).val();
    const endField = $(this).attr('id') === 'start_date' ? '#end_date' : '#edit_end_date';
    const end = $(endField).val();
    
    if (start && end && start > end) {
        alert('Start date must be before end date');
        $(this).val('');
    }
});

$('#end_date, #edit_end_date').on('change', function() {
    const startField = $(this).attr('id') === 'end_date' ? '#start_date' : '#edit_start_date';
    const start = $(startField).val();
    const end = $(this).val();
    
    if (start && end && start > end) {
        alert('Start date must be before end date');
        $(this).val('');
    }
});
</script>

<style>
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.text-end { text-align: right; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-danger { background-color: #dc3545; color: #fff; }
.badge.bg-secondary { background-color: #6c757d; color: #fff; }
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>