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

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

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

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

try {
    $pdo = db();

    // First, verify the drill belongs to the current user
    $stmt = $pdo->prepare("SELECT coach_id FROM drills WHERE id = ?");
    $stmt->execute([$drill_id]);
    $drill = $stmt->fetch();

    if ($drill && $drill['coach_id'] == $current_coach_id) {
        // Delete the drill
        $delete_stmt = $pdo->prepare("DELETE FROM drills WHERE id = ?");
        $delete_stmt->execute([$drill_id]);
        
        header('Location: my_drills.php?success=Drill deleted successfully');
        exit();
    } else {
        // Either drill doesn't exist or user doesn't have permission
        header('Location: my_drills.php?error=Drill not found or you do not have permission to delete it');
        exit();
    }

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