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

use Dompdf\Dompdf;

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

$user_id = $_SESSION['user_id'];
$song_id = $_GET['song_id'] ?? null;

if (!$song_id) {
    die("Song ID is missing.");
}

// Fetch song and user details
try {
    $stmt = db()->prepare("SELECT s.title, s.artist, s.file_path, s.uploaded_at, u.name as user_name FROM songs s JOIN users u ON s.user_id = u.id WHERE s.id = ? AND s.user_id = ?");
    $stmt->execute([$song_id, $user_id]);
    $song = $stmt->fetch();

    if (!$song) {
        die("Song not found or you don't have permission to access it.");
    }
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}

// Check daily limit
$today = date('Y-m-d');
$stmt = db()->prepare("SELECT upload_count FROM daily_uploads WHERE user_id = ? AND upload_date = ?");
$stmt->execute([$user_id, $today]);
$daily_upload = $stmt->fetch();

if ($daily_upload && $daily_upload['upload_count'] >= 20) {
    // Check if user has a pro plan
    $stmt = db()->prepare("SELECT status FROM subscriptions WHERE user_id = ? AND status = 'active'");
    $stmt->execute([$user_id]);
    $subscription = $stmt->fetch();
    if (!$subscription) {
        die("You have reached your daily limit of 20 free certificates. Please upgrade to a Pro plan for unlimited certificates.");
    }
}

// Generate certificate
$certificate_hash = hash('sha256', $song['file_path'] . $song['uploaded_at'] . uniqid());
$certificate_path = 'certificates/' . $certificate_hash . '.pdf';

// Generate PDF
$dompdf = new Dompdf();
$html = "<h1>Certificate of Copyright</h1>";
$html .= "<p>This certificate is awarded to <strong>" . htmlspecialchars($song['user_name']) . "</strong></p>";
$html .= "<p>for the song titled <strong>\"" . htmlspecialchars($song['title']) . "\"</strong></p>";
if ($song['artist']) {
    $html .= "<p>by artist <strong>" . htmlspecialchars($song['artist']) . "</strong></p>";
}
$html .= "<p>Uploaded on: " . date('M d, Y', strtotime($song['uploaded_at'])) . "</p>";
$html .= "<p>Certificate ID: " . $certificate_hash . "</p>";

$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$pdf_output = $dompdf->output();

file_put_contents($certificate_path, $pdf_output);

// Save certificate to database
try {
    $stmt = db()->prepare("INSERT INTO certificates (song_id, certificate_hash, file_path) VALUES (?, ?, ?)");
    $stmt->execute([$song_id, $certificate_hash, $certificate_path]);
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}

// Increment daily upload count
if ($daily_upload) {
    $stmt = db()->prepare("UPDATE daily_uploads SET upload_count = upload_count + 1 WHERE user_id = ? AND upload_date = ?");
    $stmt->execute([$user_id, $today]);
} else {
    $stmt = db()->prepare("INSERT INTO daily_uploads (user_id, upload_date, upload_count) VALUES (?, ?, 1)");
    $stmt->execute([$user_id, $today]);
}

// Force download
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($certificate_path) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($certificate_path));
readfile($certificate_path);
exit;