<?php
require_once '../includes/auth.php';
require_once '../config/database.php';

requireLogin();

$userId = $_SESSION['user_id'];

function hasPurchased($songId, $userId) {
    $row = fetchRow("SELECT id FROM song_sheet_purchases WHERE song_sheet_id = ? AND user_id = ? AND payment_status = 'paid'", [$songId, $userId]);
    return !empty($row);
}

$pageTitle = 'Song Sheets';
$basePath = '..';

$filters = [
    'q' => isset($_GET['q']) ? trim($_GET['q']) : '',
    'owner_type' => isset($_GET['owner_type']) ? trim($_GET['owner_type']) : '',
    'price' => isset($_GET['price']) ? trim($_GET['price']) : ''
];

$where = ["s.status = 'published'"];
$params = [];

if ($filters['q'] !== '') {
    $where[] = '(s.title LIKE ? OR s.description LIKE ?)';
    $q = '%' . $filters['q'] . '%';
    $params[] = $q;
    $params[] = $q;
}
if ($filters['owner_type'] !== '') {
    $where[] = 's.owner_type = ?';
    $params[] = $filters['owner_type'];
}
if ($filters['price'] === 'free') {
    $where[] = 's.price = 0';
} elseif ($filters['price'] === 'paid') {
    $where[] = 's.price > 0';
}

$whereSql = 'WHERE ' . implode(' AND ', $where);
$songSheets = fetchRows("SELECT s.* FROM song_sheets s $whereSql ORDER BY s.created_at DESC", $params);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - GHAMECC</title>
    <?php include '../includes/favicon.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
<?php include '../includes/navbar.php'; ?>
<div class="container-fluid">
    <div class="row">
        <?php include '../includes/sidebar.php'; ?>
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h1 class="h2">Song Sheets</h1>
                <?php 
                $canUpload = hasRole(['admin','diocesan_secretary','diocesan_treasurer','diocesan_dom','diocese_chairman','circuit_secretary','circuit_treasurer','circuit_dom','circuit_chairman']);
                if ($canUpload): ?>
                    <a href="upload.php" class="btn btn-primary"><i class="fas fa-upload me-2"></i>Upload Song Sheet</a>
                <?php endif; ?>
            </div>

            <div class="card mb-4">
                <div class="card-body">
                    <form class="row g-3" method="get">
                        <div class="col-md-4">
                            <input type="text" class="form-control" name="q" placeholder="Search title or description" value="<?php echo htmlspecialchars($filters['q']); ?>">
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" name="owner_type" onchange="this.form.submit()">
                                <option value="">All Levels</option>
                                <option value="connexion" <?php echo $filters['owner_type']==='connexion'?'selected':''; ?>>Connexion</option>
                                <option value="diocese" <?php echo $filters['owner_type']==='diocese'?'selected':''; ?>>Diocese</option>
                                <option value="circuit" <?php echo $filters['owner_type']==='circuit'?'selected':''; ?>>Circuit</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" name="price" onchange="this.form.submit()">
                                <option value="">All</option>
                                <option value="free" <?php echo $filters['price']==='free'?'selected':''; ?>>Free</option>
                                <option value="paid" <?php echo $filters['price']==='paid'?'selected':''; ?>>Premium</option>
                            </select>
                        </div>
                        <div class="col-md-2 text-end">
                            <button class="btn btn-outline-secondary" type="submit"><i class="fas fa-search"></i></button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="row g-4">
                <?php if (empty($songSheets)): ?>
                    <div class="col-12">
                        <div class="alert alert-info">No song sheets found.</div>
                    </div>
                <?php else: ?>
                    <?php foreach ($songSheets as $s): ?>
                        <div class="col-md-6 col-lg-4">
                            <div class="card h-100">
                                <?php if (!empty($s['preview_image'])): ?>
                                    <img src="../uploads/song_sheets/<?php echo htmlspecialchars($s['preview_image']); ?>" class="card-img-top" alt="Preview" style="height: 160px; object-fit: cover;">
                                <?php endif; ?>
                                <div class="card-body d-flex flex-column">
                                    <h5 class="card-title mb-1"><?php echo htmlspecialchars($s['title']); ?></h5>
                                    <div class="mb-2"><span class="badge bg-secondary text-uppercase"><?php echo htmlspecialchars($s['owner_type']); ?></span></div>
                                    <p class="card-text text-muted" style="flex:1;"><?php echo nl2br(htmlspecialchars(mb_strimwidth($s['description'] ?? '', 0, 160, '...'))); ?></p>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="fw-bold"><?php echo ($s['price']>0? 'GH₵ ' . number_format($s['price'],2) : 'Free'); ?></div>
                                        <div>
                                            <?php if ((float)$s['price'] == 0 || hasPurchased($s['id'], $userId)): ?>
                                                <a class="btn btn-sm btn-success" href="../uploads/song_sheets/<?php echo htmlspecialchars($s['file_path']); ?>" target="_blank"><i class="fas fa-download me-1"></i>Download</a>
                                            <?php else: ?>
                                                <a class="btn btn-sm btn-primary" href="purchase.php?id=<?php echo $s['id']; ?>"><i class="fas fa-shopping-cart me-1"></i>Buy</a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </main>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
