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

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

$current_user_id = get_user_id();

$pageTitle = 'My Drills';
$pageDescription = 'Manage your created drills.';

// Fetch drills for the current coach
$drills = [];
try {
    $pdo = db();

    // Fetch categories for the filter
    $category_stmt = $pdo->query("SELECT * FROM categories ORDER BY name");
    $categories = $category_stmt->fetchAll();

    // Filtering logic
    $selected_categories = isset($_GET['categories']) && is_array($_GET['categories']) ? $_GET['categories'] : [];
    $show_favorites = isset($_GET['favorites']) && $_GET['favorites'] == '1';

    $sql = "SELECT d.*, (uf.id IS NOT NULL) as is_favorite FROM drills d LEFT JOIN user_favorites uf ON d.id = uf.drill_id AND uf.user_id = ?";
    $params = [$current_user_id];

    $where_clauses = ["d.coach_id = ?"];
    $params[] = $current_user_id;

    if (!empty($selected_categories)) {
        $sql .= " JOIN drill_categories dc ON d.id = dc.drill_id";
        $where_clauses[] = "dc.category_id IN (" . str_repeat('?,', count($selected_categories) - 1) . "?)";
        $params = array_merge($params, $selected_categories);
    }
    
    if ($show_favorites) {
        $where_clauses[] = "uf.id IS NOT NULL";
    }

    if (!empty($where_clauses)) {
        $sql .= " WHERE " . implode(' AND ', $where_clauses);
    }

    $sql .= " GROUP BY d.id ORDER BY d.created_at DESC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $drills = $stmt->fetchAll();
} catch (PDOException $e) {
    // In a real app, log this error.
    error_log("Database error: " . $e->getMessage());
}
?>
<header class="py-5 text-center container-fluid">
    <div class="row py-lg-5">
        <div class="col-lg-6 col-md-8 mx-auto">
            <h1 class="display-4 fw-bold">My Drills</h1>
            <p class="lead text-muted">Here you can manage all the drills you have created.</p>
            <a href="create_drill.php" class="btn btn-primary">Create New Drill</a>
        </div>
    </div>
</header>

<main class="container">
    <div class="mb-4 p-3 border rounded bg-light">
        <form method="GET" action="my_drills.php">
            <h5 class="mb-3">Filter</h5>
            <div class="row">
                <div class="col-12">
                    <h6>By Category</h6>
                    <div class="row">
                        <?php foreach ($categories as $category) : ?>
                            <div class="col-md-3 col-sm-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="categories[]" value="<?php echo $category['id']; ?>" id="cat_<?php echo $category['id']; ?>" <?php echo in_array($category['id'], $selected_categories) ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="cat_<?php echo $category['id']; ?>">
                                        <?php echo htmlspecialchars($category['name']); ?>
                                    </label>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="col-12 mt-3">
                    <h6>By Favorites</h6>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="favorites" value="1" id="favorites_filter" <?php echo $show_favorites ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="favorites_filter">
                            Show only favorites
                        </label>
                    </div>
                </div>
            </div>
            <div class="mt-3">
                <button type="submit" class="btn btn-primary">Filter</button>
                <a href="my_drills.php" class="btn btn-secondary">Clear</a>
            </div>
        </form>
    </div>

    <?php if (isset($_GET['success'])) : ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($_GET['success']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    <?php if (isset($_GET['error'])) : ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($_GET['error']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (empty($drills)) : ?>
        <div class="text-center p-5 border rounded-3 bg-light shadow-sm">
            <p class="lead">You haven't created any drills yet.</p>
            <p>Why not start now?</p>
            <a href="create_drill.php" class="btn btn-lg btn-success">Create Your First Drill</a>
        </div>
    <?php else : ?>
        <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-4">
            <?php foreach ($drills as $drill) : ?>
                <div class="col">
                    <div class="card h-100 card-drill">
                        <a href="drill.php?id=<?php echo $drill['id']; ?>">
                            <img src="<?php echo $drill['image_path'] ? htmlspecialchars($drill['image_path']) : 'https://via.placeholder.com/400x250.png?text=No+Image'; ?>" class="card-img-top" alt="Drill Image">
                        </a>
                        <div class="card-body">
                            <h5 class="card-title fw-bold"><?php echo htmlspecialchars($drill['title']); ?></h5>
                            <p class="card-text text-muted"><?php echo htmlspecialchars(substr($drill['description'], 0, 80)); ?>...</p>
                        </div>
                        <div class="card-footer bg-transparent border-top-0">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <a href="drill.php?id=<?php echo $drill['id']; ?>" class="btn btn-sm btn-outline-primary">View</a>
                                <i class="material-icons favorite-icon" data-drill-id="<?php echo $drill['id']; ?>" style="cursor: pointer;">
                                    <?php echo $drill['is_favorite'] ? 'favorite' : 'favorite_border'; ?>
                                </i>
                                <div>
                                    <span class="badge bg-light text-dark me-1"><?php echo htmlspecialchars($drill['age_group']); ?></span>
                                    <span class="badge 
                                    <?php
                                    switch (strtolower($drill['difficulty'])) {
                                        case 'easy': echo 'bg-success'; break;
                                        case 'medium': echo 'bg-warning text-dark'; break;
                                        case 'hard': echo 'bg-danger'; break;
                                        default: echo 'bg-secondary';
                                    }
                                    ?>">
                                    <?php echo htmlspecialchars($drill['difficulty']); ?>
                                    </span>
                                </div>
                            </div>
                            <div class="d-flex justify-content-end gap-2">
                                <a href="edit_drill.php?id=<?php echo $drill['id']; ?>" class="btn btn-sm btn-outline-secondary">Edit</a>
                                <a href="delete_drill.php?id=<?php echo $drill['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure you want to delete this drill?');">Delete</a>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</main>

<script>
document.querySelectorAll('.favorite-icon').forEach(icon => {
    icon.addEventListener('click', function() {
        const drillId = this.dataset.drillId;
        const isFavorited = this.textContent.trim() === 'favorite';
        
        const formData = new FormData();
        formData.append('drill_id', drillId);

        fetch('toggle_favorite.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (data.status === 'added') {
                    this.textContent = 'favorite';
                } else {
                    this.textContent = 'favorite_border';
                }
            } else {
                alert(data.message || 'An error occurred.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred while favoriting this drill.');
        });
    });
});
</script>

<?php require_once __DIR__ . '/partials/footer.php'; ?>
