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

requireLogin();

$basePath = '..';

$canUpload = hasRole(['admin','diocesan_secretary','diocesan_treasurer','diocesan_dom','diocese_chairman','circuit_secretary','circuit_treasurer','circuit_dom','circuit_chairman']);
if (!$canUpload) {
    header('Location: index.php?error=permission_denied');
    exit;
}

$errors = [];
$success = false;

$title = '';
$description = '';
$owner_type = '';
$price = '0';

// Suggest defaults based on user role
if (hasRole(['diocesan_secretary','diocesan_treasurer','diocesan_dom','diocese_chairman'])) {
    $owner_type = 'diocese';
} elseif (hasRole(['circuit_secretary','circuit_treasurer','circuit_dom','circuit_chairman'])) {
    $owner_type = 'circuit';
} else {
    $owner_type = 'connexion';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $owner_type = trim($_POST['owner_type'] ?? $owner_type);
    $price = trim($_POST['price'] ?? '0');

    if ($title === '') { $errors[] = 'Title is required'; }
    if (!in_array($owner_type, ['connexion','diocese','circuit'])) { $errors[] = 'Invalid owner type'; }
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) { $errors[] = 'Song sheet file is required'; }
    if ($price !== '' && !is_numeric($price)) { $errors[] = 'Price must be a number'; }

    if (empty($errors)) {
        $owner_id = null;
        if ($owner_type === 'diocese') {
            $owner_id = $_SESSION['diocese_id'] ?? null;
        } elseif ($owner_type === 'circuit') {
            $owner_id = $_SESSION['circuit_id'] ?? null;
        }

        $dir = __DIR__ . '/../uploads/song_sheets/';
        if (!file_exists($dir)) { @mkdir($dir, 0777, true); }

        $allowedExt = ['pdf','doc','docx','png','jpg','jpeg'];
        $fileExt = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
        if (!in_array($fileExt, $allowedExt)) {
            $errors[] = 'Invalid file type for song sheet';
        }

        $previewImageName = null;
        if (isset($_FILES['preview_image']) && $_FILES['preview_image']['size'] > 0) {
            $imgExt = strtolower(pathinfo($_FILES['preview_image']['name'], PATHINFO_EXTENSION));
            if (!in_array($imgExt, ['jpg','jpeg','png','gif'])) {
                $errors[] = 'Invalid preview image type';
            }
        }

        if (empty($errors)) {
            $newFileName = 'sheet_' . time() . '_' . bin2hex(random_bytes(3)) . '.' . $fileExt;
            $targetPath = $dir . $newFileName;
            if (!move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
                $errors[] = 'Failed to upload song sheet file';
            } else {
                if (isset($_FILES['preview_image']) && $_FILES['preview_image']['size'] > 0) {
                    $previewImageName = 'sheet_prev_' . time() . '_' . bin2hex(random_bytes(3)) . '.' . $imgExt;
                    if (!move_uploaded_file($_FILES['preview_image']['tmp_name'], $dir . $previewImageName)) {
                        $previewImageName = null; // non-fatal
                    }
                }

                $ok = executeQuery(
                    "INSERT INTO song_sheets (title, description, owner_type, owner_id, price, file_path, preview_image, status, created_by, created_at) VALUES (?,?,?,?,?,?,?,?,?, NOW())",
                    [
                        $title,
                        $description ?: null,
                        $owner_type,
                        $owner_id,
                        (float)$price,
                        $newFileName,
                        $previewImageName,
                        'published',
                        $_SESSION['user_id']
                    ]
                );
                if ($ok) {
                    $success = true;
                    logInfo('Song sheet uploaded', ['title' => $title, 'owner_type' => $owner_type, 'owner_id' => $owner_id]);
                    // reset
                    $title = $description = '';
                    $price = '0';
                } else {
                    $errors[] = 'Database error while saving song sheet';
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Song Sheet - 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">
</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">Upload Song Sheet</h1>
                <a href="index.php" class="btn btn-secondary">Back</a>
            </div>
            <?php if ($success): ?>
                <div class="alert alert-success">Song sheet uploaded successfully.</div>
            <?php endif; ?>
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        <?php foreach ($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
            <div class="card">
                <div class="card-body">
                    <form method="post" enctype="multipart/form-data">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Title</label>
                                <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($title); ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Owner Level</label>
                                <select name="owner_type" class="form-select" required>
                                    <option value="connexion" <?php echo $owner_type==='connexion'?'selected':''; ?>>Connexion</option>
                                    <option value="diocese" <?php echo $owner_type==='diocese'?'selected':''; ?>>Diocese</option>
                                    <option value="circuit" <?php echo $owner_type==='circuit'?'selected':''; ?>>Circuit</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Price (GH₵)</label>
                                <input type="number" step="0.01" name="price" class="form-control" value="<?php echo htmlspecialchars($price); ?>">
                                <div class="form-text">Set 0 for free</div>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Description</label>
                                <textarea name="description" rows="4" class="form-control"><?php echo htmlspecialchars($description); ?></textarea>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Song Sheet File</label>
                                <input type="file" name="file" class="form-control" accept=".pdf,.doc,.docx,.png,.jpg,.jpeg" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Preview Image (optional)</label>
                                <input type="file" name="preview_image" class="form-control" accept="image/*">
                            </div>
                            <div class="col-12 mt-3">
                                <button class="btn btn-primary" type="submit">Upload</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
