<?php
require_once __DIR__ . '/partials/header.php';

// Require login
if (!is_logged_in()) {
    header('Location: login.php');
    exit();
}

$drill_id = $_GET['id'] ?? null;
$current_coach_id = get_user_id();

if (!$drill_id) {
    header('Location: my_drills.php?error=No drill specified');
    exit();
}

$pdo = db();

try {
    $stmt = $pdo->prepare("SELECT * FROM drills WHERE id = ? AND coach_id = ?");
    $stmt->execute([$drill_id, $current_coach_id]);
    $drill = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$drill) {
        header('Location: my_drills.php?error=Drill not found or you do not have permission to edit it');
        exit();
    }

    // Fetch current categories for the drill
    $stmt = $pdo->prepare("SELECT category_id FROM drill_categories WHERE drill_id = ?");
    $stmt->execute([$drill_id]);
    $current_category_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

} catch (PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    header('Location: my_drills.php?error=A database error occurred.');
    exit();
}

$pageTitle = 'Edit Drill';
$pageDescription = 'Update the details of your football/soccer drill.';

$errors = [];

// Define selectable options
$age_groups = ['U6-U8', 'U9-U12', 'U13-U16', 'U17+', 'Adults'];
$skill_focuses = ['Dribbling', 'Passing', 'Shooting', 'Defense', 'Goalkeeping', 'Crossing', 'Finishing', 'First Touch'];
$difficulties = ['Beginner', 'Intermediate', 'Advanced'];

// Fetch all categories
$stmt = $pdo->query("SELECT * FROM categories ORDER BY name");
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and validate inputs
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $min_players = filter_input(INPUT_POST, 'min_players', FILTER_VALIDATE_INT);
    $max_players = filter_input(INPUT_POST, 'max_players', FILTER_VALIDATE_INT);
    $age_group = trim($_POST['age_group'] ?? '');
    $skill_focus = trim($_POST['skill_focus'] ?? '');
    $difficulty = trim($_POST['difficulty'] ?? '');
    $duration_minutes = filter_input(INPUT_POST, 'duration_minutes', FILTER_VALIDATE_INT);
    $equipment_required = trim($_POST['equipment_required'] ?? '');
    $youtube_url = filter_input(INPUT_POST, 'youtube_url', FILTER_VALIDATE_URL);
    $is_public = isset($_POST['is_public']) ? 1 : 0;
    $selected_categories = $_POST['categories'] ?? [];
    $image_path = $drill['image_path']; // Keep old image by default

    // Basic validation
    if (empty($title)) $errors[] = 'Title is required.';
    if (empty($description)) $errors[] = 'Description is required.';
    if ($min_players === false || $min_players < 1) $errors[] = 'Minimum players must be a positive number.';
    if ($max_players === false || $max_players < $min_players) $errors[] = 'Maximum players must be greater than or equal to minimum players.';
    if (!in_array($age_group, $age_groups)) $errors[] = 'Invalid age group selected.';
    if (!in_array($skill_focus, $skill_focuses)) $errors[] = 'Invalid skill focus selected.';
    if (!in_array($difficulty, $difficulties)) $errors[] = 'Invalid difficulty selected.';
    if ($duration_minutes === false || $duration_minutes < 1) $errors[] = 'Duration must be a positive number.';
    if ($youtube_url === false && !empty($_POST['youtube_url'])) $errors[] = 'YouTube URL is not a valid URL.';
    if (empty($selected_categories)) $errors[] = 'At least one category must be selected.';

    // New image upload handling
    if (isset($_FILES['drill_image']) && $_FILES['drill_image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = __DIR__ . '/assets/images/drills/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0775, true);
        }
        $file = $_FILES['drill_image'];
        $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];

        if (in_array($file_ext, $allowed_exts)) {
            if ($file['size'] <= 5 * 1024 * 1024) { // 5MB limit
                $new_filename = uniqid('', true) . '.' . $file_ext;
                $destination = $upload_dir . $new_filename;

                if (move_uploaded_file($file['tmp_name'], $destination)) {
                    // Delete old image if it exists
                    if ($drill['image_path'] && file_exists(__DIR__ . '/' . $drill['image_path'])) {
                        unlink(__DIR__ . '/' . $drill['image_path']);
                    }
                    $image_path = '/assets/images/drills/' . $new_filename;
                } else {
                    $errors[] = 'Failed to move uploaded file.';
                }
            } else {
                $errors[] = 'File is too large. Maximum size is 5MB.';
            }
        } else {
            $errors[] = 'Invalid file type. Only JPG, JPEG, PNG, and GIF are allowed.';
        }
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare(
                'UPDATE drills SET 
                    title = ?, 
                    description = ?, 
                    min_players = ?, 
                    max_players = ?, 
                    age_group = ?, 
                    skill_focus = ?, 
                    difficulty = ?, 
                    duration_minutes = ?, 
                    equipment_required = ?, 
                    youtube_url = ?, 
                    is_public = ?,
                    image_path = ?
                 WHERE id = ? AND coach_id = ?'
            );

            $stmt->execute([
                $title,
                $description,
                $min_players,
                $max_players,
                $age_group,
                $skill_focus,
                $difficulty,
                $duration_minutes,
                $equipment_required,
                $youtube_url ?: null,
                $is_public,
                $image_path,
                $drill_id,
                $current_coach_id
            ]);

            // Update categories
            // 1. Delete existing categories for this drill
            $stmt = $pdo->prepare("DELETE FROM drill_categories WHERE drill_id = ?");
            $stmt->execute([$drill_id]);

            // 2. Insert new categories
            $stmt = $pdo->prepare('INSERT INTO drill_categories (drill_id, category_id) VALUES (?, ?)');
            foreach ($selected_categories as $category_id) {
                $stmt->execute([$drill_id, $category_id]);
            }

            $pdo->commit();

            header("Location: my_drills.php?success=Drill updated successfully");
            exit;

        } catch (PDOException $e) {
            $pdo->rollBack();
            // In a real app, log this error instead of displaying it
            $errors[] = "Database error: " . $e->getMessage();
        }
    }
}
?>
<main class="container my-5">
    <div class="row justify-content-center">
        <div class="col-lg-9 col-xl-8">
            <div class="card shadow-lg border-0 rounded-4">
                <div class="card-body p-4 p-sm-5">
                    <div class="text-center mb-4">
                        <h1 class="h2 fw-bold">Edit Drill</h1>
                        <p class="text-muted">Update the details of your drill.</p>
                    </div>

                    <?php if (!empty($errors)) : ?>
                        <div class="alert alert-danger">
                            <p class="mb-0"><strong>Please fix the following errors:</strong></p>
                            <ul class="mb-0">
                                <?php foreach ($errors as $error) : ?>
                                    <li><?php echo htmlspecialchars($error); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>

                    <form action="edit_drill.php?id=<?php echo $drill_id; ?>" method="POST" enctype="multipart/form-data" novalidate>
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" id="title" name="title" placeholder="Drill Title" required value="<?php echo htmlspecialchars($drill['title']); ?>">
                            <label for="title">Drill Title</label>
                        </div>

                        <div class="form-floating mb-3">
                            <textarea class="form-control" id="description" name="description" placeholder="Description & Instructions" style="height: 150px" required><?php echo htmlspecialchars($drill['description']); ?></textarea>
                            <label for="description">Description & Instructions</label>
                        </div>

                        <div class="mb-3">
                            <label for="drill_image" class="form-label">Drill Image</label>
                            <?php if ($drill['image_path']) : ?>
                                <div class="mb-2">
                                    <img src="<?php echo htmlspecialchars($drill['image_path']); ?>" alt="Current Drill Image" style="max-width: 200px; height: auto; border-radius: 0.25rem;">
                                </div>
                            <?php endif; ?>
                            <input class="form-control" type="file" id="drill_image" name="drill_image">
                            <div class="form-text">Upload a new image to replace the current one (JPG, PNG, GIF - max 5MB).</div>
                        </div>

                        <div class="row g-3 mb-3">
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="number" class="form-control" id="min_players" name="min_players" placeholder="Min. Players" min="1" required value="<?php echo htmlspecialchars($drill['min_players']); ?>">
                                    <label for="min_players">Min. Players</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="number" class="form-control" id="max_players" name="max_players" placeholder="Max. Players" min="1" required value="<?php echo htmlspecialchars($drill['max_players']); ?>">
                                    <label for="max_players">Max. Players</label>
                                </div>
                            </div>
                        </div>

                        <div class="row g-3 mb-3">
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <select class="form-select" id="age_group" name="age_group" required>
                                        <?php foreach ($age_groups as $group) : ?>
                                            <option value="<?php echo $group; ?>" <?php echo ($drill['age_group'] === $group) ? 'selected' : ''; ?>><?php echo $group; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <label for="age_group">Age Group</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <select class="form-select" id="difficulty" name="difficulty" required>
                                        <?php foreach ($difficulties as $level) : ?>
                                            <option value="<?php echo $level; ?>" <?php echo ($drill['difficulty'] === $level) ? 'selected' : ''; ?>><?php echo $level; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <label for="difficulty">Difficulty</label>
                                </div>
                            </div>
                        </div>

                        <div class="form-floating mb-3">
                            <select class="form-select" id="skill_focus" name="skill_focus" required>
                                <?php foreach ($skill_focuses as $focus) : ?>
                                    <option value="<?php echo $focus; ?>" <?php echo (($drill['skill_focus'] ?? '') === $focus) ? 'selected' : ''; ?>><?php echo $focus; ?></option>
                                <?php endforeach; ?>
                            </select>
                            <label for="skill_focus">Primary Skill Focus</label>
                        </div>

                        <div class="mb-3">
                            <label for="categories" class="form-label">Categories</label>
                            <select class="form-select" id="categories" name="categories[]" multiple required size="5">
                                <?php foreach ($categories as $category) : ?>
                                    <option value="<?php echo $category['id']; ?>" <?php echo in_array($category['id'], $current_category_ids) ? 'selected' : ''; ?>><?php echo htmlspecialchars($category['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="form-text">Select one or more categories (hold Ctrl or Cmd to select multiple).</div>
                        </div>

                        <div class="form-floating mb-3">
                            <input type="number" class="form-control" id="duration_minutes" name="duration_minutes" placeholder="Duration (minutes)" min="1" required value="<?php echo htmlspecialchars($drill['duration_minutes']); ?>">
                            <label for="duration_minutes">Duration (minutes)</label>
                        </div>

                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" id="equipment_required" name="equipment_required" placeholder="e.g., Cones, balls, bibs" value="<?php echo htmlspecialchars($drill['equipment_required']); ?>">
                            <label for="equipment_required">Equipment Required</label>
                        </div>

                        <div class="form-floating mb-4">
                            <input type="url" class="form-control" id="youtube_url" name="youtube_url" placeholder="https://www.youtube.com/watch?v=..." value="<?php echo htmlspecialchars($drill['youtube_url']); ?>">
                            <label for="youtube_url">YouTube Video URL (Optional)</label>
                        </div>

                        <div class="form-check form-switch mb-4">
                            <input class="form-check-input" type="checkbox" role="switch" id="is_public" name="is_public" value="1" <?php echo $drill['is_public'] ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="is_public">Make this drill public</label>
                        </div>

                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary btn-lg rounded-pill">Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>
<?php require_once __DIR__ . '/partials/footer.php'; ?>