<?php
session_start();
require_once 'db/config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'];

$upload_error = '';
$upload_success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['song'])) {
    $title = $_POST['title'] ?? '';
    $artist = $_POST['artist'] ?? '';
    $file = $_FILES['song'];

    if (empty($title)) {
        $upload_error = 'Please provide a title for your song.';
    } elseif ($file['error'] !== UPLOAD_ERR_OK) {
        $upload_error = 'An error occurred during file upload.';
    } else {
        $allowed_types = ['audio/mpeg', 'audio/wav', 'audio/ogg'];
        if (!in_array($file['type'], $allowed_types)) {
            $upload_error = 'Invalid file type. Please upload an MP3, WAV, or OGG file.';
        } elseif ($file['size'] > 50000000) { // 50 MB
            $upload_error = 'File is too large. Maximum size is 50 MB.';
        } else {
            $file_name = uniqid() . '-' . basename($file['name']);
            $upload_path = 'uploads/' . $file_name;

            if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                try {
                    $stmt = db()->prepare("INSERT INTO songs (user_id, title, artist, file_path) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$user_id, $title, $artist, $upload_path]);
                    $upload_success = 'Song uploaded successfully!';
                } catch (PDOException $e) {
                    $upload_error = "Database error: " . $e->getMessage();
                }
            } else {
                $upload_error = 'Failed to move uploaded file.';
            }
        }
    }
}

// Fetch user's songs
$songs = [];
try {
    $stmt = db()->prepare("SELECT id, title, artist, uploaded_at FROM songs WHERE user_id = ? ORDER BY uploaded_at DESC");
    $stmt->execute([$user_id]);
    $songs = $stmt->fetchAll();
} catch (PDOException $e) {
    // Handle database error
}

// Fetch user's subscription
$subscription = null;
try {
    $stmt = db()->prepare("SELECT plan, status, end_date FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
    $stmt->execute([$user_id]);
    $subscription = $stmt->fetch();
} catch (PDOException $e) {
    // Handle database error
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Veritune</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&family=Inter:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/custom.css">
</head>
<body class="bg-light-gray">
    <?php include 'includes/header.php'; ?>

    <main class="container py-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1>Welcome, <?php echo htmlspecialchars($user_name); ?>!</h1>
        </div>

        <div class="card mb-4">
            <h2>Subscription Status</h2>
            <?php if ($subscription): ?>
                <p><strong>Plan:</strong> <?php echo htmlspecialchars(ucfirst($subscription['plan'])); ?></p>
                <p><strong>Status:</strong> <?php echo htmlspecialchars(ucfirst($subscription['status'])); ?></p>
                <?php if ($subscription['status'] === 'active'): ?>
                    <p><strong>Next Billing Date:</strong> <?php echo date('M d, Y', strtotime($subscription['end_date'])); ?></p>
                <?php endif; ?>
            <?php else: ?>
                <p>You are currently on the Free plan.</p>
                <a href="index.php#pricing" class="btn btn-primary">Upgrade to Pro</a>
            <?php endif; ?>
        </div>

        <div class="card mb-4">
            <h2>Upload a New Song</h2>
            <?php if ($upload_error): ?>
                <p class="text-danger"><?php echo $upload_error; ?></p>
            <?php endif; ?>
            <?php if ($upload_success): ?>
                <p class="text-success"><?php echo $upload_success; ?></p>
            <?php endif; ?>
            <form action="dashboard.php" method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="title">Song Title</label>
                    <input type="text" id="title" name="title" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="artist">Artist (Optional)</label>
                    <input type="text" id="artist" name="artist" class="form-control">
                </div>
                <div class="form-group">
                    <label for="song">Song File (MP3, WAV, OGG)</label>
                    <input type="file" id="song" name="song" class="form-control" accept=".mp3,.wav,.ogg" required>
                </div>
                <button type="submit" class="btn btn-primary">Upload Song</button>
            </form>
        </div>

        <div class="card">
            <h2>Your Songs</h2>
            <table class="table">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Artist</th>
                        <th>Uploaded On</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($songs)): ?>
                        <tr>
                            <td colspan="4" class="text-center">You haven't uploaded any songs yet.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($songs as $song): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($song['title']); ?></td>
                                <td><?php echo htmlspecialchars($song['artist']); ?></td>
                                <td><?php echo date('M d, Y', strtotime($song['uploaded_at'])); ?></td>
                                <td><a href="generate_certificate.php?song_id=<?php echo $song['id']; ?>" class="btn btn-sm btn-secondary">Generate Certificate</a></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </main>

    <footer class="footer bg-white">
        <div class="container">
            <p>&copy; <?php echo date("Y"); ?> Veritune. All rights reserved.</p>
        </div>
    </footer>
</body>
</html>
