<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');
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.");
}

// Check if event ID is passed
if (!isset($_GET['id']) || empty($_GET['id']) || !is_numeric($_GET['id'])) {
    $error = "Invalid or missing event ID: " . ($_GET['id'] ?? 'not set');
    logError($error);
    echo "<div class='alert alert-danger'>Invalid event ID.</div>";
    exit();
}

$event_id = intval($_GET['id']);

// Fetch the event details
try {
    $stmt = $conn->prepare("SELECT event_name, event_description, event_date, start_date, end_date, event_image, entry_fee, game_id FROM events WHERE event_id = ?");
    $stmt->bind_param("i", $event_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        $error = "Event not found for ID: $event_id";
        logError($error);
        echo "<div class='alert alert-danger'>Event not found.</div>";
        exit();
    }

    $event = $result->fetch_assoc();
    $stmt->close();
} catch (Exception $e) {
    logError("Fetch event failed: " . $e->getMessage());
    http_response_code(500);
    die("Server error. Please try again later.");
}

// Handle form submission
$errors = [];
$success = '';

if (isset($_POST['update_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 = $event['event_image']; // Default to existing image
        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'];
        }

        // Update the 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("UPDATE events SET event_name = ?, event_description = ?, event_date = ?, start_date = ?, end_date = ?, event_image = ?, entry_fee = ?, game_id = ? WHERE event_id = ?");
                $stmt->bind_param("ssssssdii", $event_name, $event_description, $event_date, $start_date, $end_date, $event_image, $entry_fee, $game_id, $event_id);

                if ($stmt->execute()) {
                    if ($stmt->affected_rows >= 0) { // Using >= 0 because affected_rows is 0 if nothing changed but query was valid
                        $success = "Event updated successfully!";
                        logError("Event updated successfully. ID: $event_id, Name: $event_name, Entry Fee: $entry_fee, Game ID: $game_id, Start Date: $start_date, End Date: $end_date");
                        header("Location: events.php");
                        exit();
                    }
                } else {
                    $errors[] = "Error updating event: " . $stmt->error;
                }
                $stmt->close();
            }
        }
    } catch (Exception $e) {
        $errors[] = "Server error: " . $e->getMessage();
        logError("Update event failed: " . $e->getMessage());
    }
}

// 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>Edit Event</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container py-5">
        <h2>Edit Event</h2>

        <?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; ?>

        <form method="post" action="edit_event.php?id=<?php echo $event_id; ?>" 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"
                    value="<?php echo htmlspecialchars($event['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><?php echo htmlspecialchars($event['event_description']); ?></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 ($game['game_id'] == $event['game_id']) ? 'selected' : ''; ?>>
                            <?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"
                    value="<?php echo htmlspecialchars(date('Y-m-d\TH:i', strtotime($event['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"
                        value="<?php echo htmlspecialchars(date('Y-m-d\TH:i', strtotime($event['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"
                        value="<?php echo htmlspecialchars(date('Y-m-d\TH:i', strtotime($event['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="<?php echo htmlspecialchars(number_format($event['entry_fee'], 2, '.', '')); ?>" 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/*">
                <?php if (!empty($event['event_image'])): ?>
                    <img src="<?php echo htmlspecialchars($event['event_image']); ?>" alt="Event Image" width="100"
                        class="mt-2">
                <?php endif; ?>
            </div>
            <button type="submit" name="update_event" class="btn btn-primary">Update Event</button>
            <a href="events.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</body>

</html>

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