<?php
error_reporting(E_ALL);
ini_set('display_errors', 0); // Disable display_errors for production
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt'); // Consistent with other scripts
session_start();

// Function to log errors
function logError($message)
{
    $logFile = 'error_log.txt';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

// Check if admin is logged in
if (!isset($_SESSION['admin'])) {
    logError("Admin session not set. Redirecting to login.php");
    header('Location: login.php');
    exit();
}

// Include database connection
try {
    include 'db.php';
    if ($conn->connect_error) {
        $error = "Database connection failed: " . $conn->connect_error;
        logError($error);
        throw new Exception($error);
    }
} catch (Exception $e) {
    logError("Include db.php failed: " . $e->getMessage());
    http_response_code(500);
    die("Server error. Please try again later.");
}

// Add event functionality
$errors = [];
$success = '';

if (isset($_POST['add_event'])) {
    try {
        // Validate inputs
        $event_name = trim($_POST['event_name'] ?? '');
        $event_description = trim($_POST['event_description'] ?? '');
        $event_date = $_POST['event_date'] ?? '';
        $start_date = $_POST['start_date'] ?? '';
        $end_date = $_POST['end_date'] ?? '';
        $entry_fee = isset($_POST['entry_fee']) ? floatval($_POST['entry_fee']) : null;

        if (empty($event_name)) {
            $errors[] = "Event name is required.";
        }
        if (empty($event_description)) {
            $errors[] = "Event description is required.";
        }
        if (empty($event_date) || !DateTime::createFromFormat('Y-m-d\TH:i', $event_date)) {
            $errors[] = "Valid display event date is required.";
        }
        if (empty($start_date) || !DateTime::createFromFormat('Y-m-d\TH:i', $start_date)) {
            $errors[] = "Valid start date is required.";
        }
        if (empty($end_date) || !DateTime::createFromFormat('Y-m-d\TH:i', $end_date)) {
            $errors[] = "Valid end date is required.";
        }
        if (!is_numeric($entry_fee) || $entry_fee < 0) {
            $errors[] = "Entry fee must be a non-negative number.";
        }

        // Handle image upload
        $event_image = ''; // Default to empty
        if (isset($_FILES['event_image']) && $_FILES['event_image']['error'] === UPLOAD_ERR_OK) {
            $target_dir = "../../assets/images/";
            $image_name = uniqid('event_') . '_' . basename($_FILES['event_image']['name']);
            $target_file = $target_dir . $image_name;

            // Validate file type and size
            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
            $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
            if (!in_array($imageFileType, $allowed_types)) {
                $errors[] = "Only JPG, JPEG, PNG, and GIF files are allowed.";
            }
            if ($_FILES['event_image']['size'] > 5000000) { // 5MB limit
                $errors[] = "Image file is too large (max 5MB).";
            }

            // Ensure directory exists and is writable
            if (!is_dir($target_dir)) {
                if (!mkdir($target_dir, 0777, true)) {
                    $errors[] = "Failed to create upload directory.";
                }
            }
            if (!is_writable($target_dir)) {
                $errors[] = "Upload directory is not writable.";
            }

            // Move uploaded file
            if (empty($errors)) {
                if (move_uploaded_file($_FILES['event_image']['tmp_name'], $target_file)) {
                    $event_image = $image_name;
                } else {
                    $errors[] = "Error uploading the image.";
                }
            }
        } elseif ($_FILES['event_image']['error'] !== UPLOAD_ERR_NO_FILE) {
            $errors[] = "Image upload error: " . $_FILES['event_image']['error'];
        }

        // Insert event if no errors
        if (empty($errors)) {
            $game_id = isset($_POST['game_id']) ? intval($_POST['game_id']) : 0;
            if ($game_id <= 0) {
                $errors[] = "Please select a valid game.";
            } else {
                $stmt = $conn->prepare("INSERT INTO events (event_name, event_description, event_date, start_date, end_date, event_image, entry_fee, game_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->bind_param("ssssssdi", $event_name, $event_description, $event_date, $start_date, $end_date, $event_image, $entry_fee, $game_id);

                if ($stmt->execute()) {
                    $success = "Event added successfully!";
                    logError("Event added successfully. Name: $event_name, Entry Fee: $entry_fee, Game ID: $game_id, Start Date: $start_date, End Date: $end_date");
                } else {
                    $errors[] = "Error adding event: " . $stmt->error;
                }
                $stmt->close();
            }
        }
    } catch (Exception $e) {
        $errors[] = "Server error: " . $e->getMessage();
        logError("Add event failed: " . $e->getMessage());
    }
}

// Delete event functionality
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    try {
        $event_id = intval($_GET['delete']);
        $stmt = $conn->prepare("DELETE FROM events WHERE event_id = ?");
        $stmt->bind_param("i", $event_id);

        if ($stmt->execute()) {
            $success = "Event deleted successfully!";
            logError("Event deleted successfully. ID: $event_id");
        } else {
            $errors[] = "Error deleting event: " . $stmt->error;
        }
        $stmt->close();
    } catch (Exception $e) {
        $errors[] = "Server error: " . $e->getMessage();
        logError("Delete event failed: " . $e->getMessage());
    }
}

// Fetch events
try {
    $stmt = $conn->prepare("SELECT e.event_id, e.event_name, e.event_description, e.event_date, e.start_date, e.end_date, e.event_image, e.entry_fee, g.game_name FROM events e LEFT JOIN games g ON e.game_id = g.game_id ORDER BY e.event_date DESC");
    $stmt->execute();
    $result = $stmt->get_result();
} catch (Exception $e) {
    logError("Fetch events failed: " . $e->getMessage());
    http_response_code(500);
    die("Server error. Please try again later.");
}

// Fetch all games for the dropdown
$games = [];
try {
    $games_result = $conn->query("SELECT game_id, game_name FROM games ORDER BY game_name ASC");
    while ($row = $games_result->fetch_assoc()) {
        $games[] = $row;
    }
} catch (Exception $e) {
    logError("Fetch games for dropdown failed: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Events</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f0f4f8;
        }

        .sidebar {
            background-color: #343a40;
            min-height: 100vh;
            padding-top: 20px;
        }

        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 10px;
            display: block;
            border-radius: 5px;
            margin: 5px;
            transition: background-color 0.3s;
        }

        .sidebar a:hover {
            background-color: #007bff;
        }

        .content {
            margin-left: 250px;
            padding: 30px;
        }

        h2 {
            color: #343a40;
        }
    </style>
</head>

<body>
    <div class="d-flex">
        <!-- Sidebar -->
        <div class="sidebar col-md-2">
            <h3 class="text-center text-white">Admin Panel</h3>
            <a href="index.php">Dashboard</a>
            <a href="games.php">Manage Games</a>
            <a href="game_categories.php">Manage Categories</a>
            <a href="leaderboard.php">Leaderboard</a>
            <a href="events.php">Manage Events</a>
            <a href="profile_management.php">Profile Management</a>
            <a href="logout.php">Logout</a>
        </div>

        <!-- Main Content -->
        <div class="content col-md-9">
            <div class="container py-5">
                <h2>Manage Events</h2>
                <p>Here you can manage the events.</p>

                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger">
                        <ul>
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
                <?php endif; ?>

                <!-- Add Event Form -->
                <form method="post" action="events.php" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="event_name" class="form-label">Event Name</label>
                        <input type="text" class="form-control" id="event_name" name="event_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="event_description" class="form-label">Event Description</label>
                        <textarea class="form-control" id="event_description" name="event_description" rows="4"
                            required></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="game_id" class="form-label">Select Game</label>
                        <select class="form-select" id="game_id" name="game_id" required>
                            <option value="">-- Select Game --</option>
                            <?php foreach ($games as $game): ?>
                                <option value="<?php echo $game['game_id']; ?>">
                                    <?php echo htmlspecialchars($game['game_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="event_date" class="form-label">Display Date (Old Format)</label>
                        <input type="datetime-local" class="form-control" id="event_date" name="event_date" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="start_date" class="form-label">Start Date</label>
                            <input type="datetime-local" class="form-control" id="start_date" name="start_date"
                                required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="end_date" class="form-label">End Date</label>
                            <input type="datetime-local" class="form-control" id="end_date" name="end_date" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="entry_fee" class="form-label">Entry Fee (Espees)</label>
                        <input type="number" class="form-control" id="entry_fee" name="entry_fee" step="0.01" min="0"
                            value="0.00" required>
                    </div>
                    <div class="mb-3">
                        <label for="event_image" class="form-label">Event Image</label>
                        <input type="file" class="form-control" id="event_image" name="event_image" accept="image/*">
                    </div>
                    <button type="submit" name="add_event" class="btn btn-primary">Add Event</button>
                </form>

                <hr>

                <!-- Display Events -->
                <h3>Existing Events</h3>
                <?php if ($result->num_rows > 0): ?>
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Event Name</th>
                                <th>Game</th>
                                <th>Display Date</th>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Description</th>
                                <th>Entry Fee (Espees)</th>
                                <th>Image</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($event = $result->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($event['event_name']); ?></td>
                                    <td><?php echo htmlspecialchars($event['game_name'] ?? 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars($event['event_date']); ?></td>
                                    <td><?php echo htmlspecialchars($event['start_date']); ?></td>
                                    <td><?php echo htmlspecialchars($event['end_date']); ?></td>
                                    <td><?php echo htmlspecialchars($event['event_description']); ?></td>
                                    <td><?php echo htmlspecialchars(number_format($event['entry_fee'], 2)); ?></td>
                                    <td>
                                        <?php if ($event['event_image']): ?>
                                            <img src="<?php echo htmlspecialchars($event['event_image']); ?>" alt="Event Image"
                                                width="100">
                                        <?php else: ?>
                                            No image
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="edit_event.php?id=<?php echo $event['event_id']; ?>"
                                            class="btn btn-warning btn-sm">Edit</a>
                                        <a href="events.php?delete=<?php echo $event['event_id']; ?>"
                                            class="btn btn-danger btn-sm"
                                            onclick="return confirm('Are you sure you want to delete this event?');">Delete</a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <p>No events found.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>

</html>

<?php
$result->close();
$stmt->close();
$conn->close();
?>