<?php
// download.php — Secure file download + external link redirect handler
require_once '../config/database.php';
require_once '../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

// ── Auth ─────────────────────────────────────────────────────────────────────
if (!isset($_SESSION['user_id'])) {
    header('Location: http://quicktasks.co.ke/login.php'); exit;
}
$userId = intval($_SESSION['user_id']);

$token = trim($_GET['token'] ?? '');
if (empty($token)) {
    die(renderError('Invalid download link.', 'The download token is missing or malformed.'));
}

$conn = getConnection();

// ── Find purchase — now also fetches delivery_type + delivery_link ────────────
$stmt = $conn->prepare("
    SELECT pp.*,
           dp.file_path, dp.file_name, dp.file_type, dp.title, dp.id AS dp_id,
           dp.delivery_type, dp.delivery_link
    FROM product_purchases pp
    JOIN digital_products dp ON pp.product_id = dp.id
    WHERE pp.download_token = ?
      AND pp.status         = 'completed'
      AND pp.user_id        = ?
    LIMIT 1
");
$stmt->bind_param("si", $token, $userId);
$stmt->execute();
$purchase = $stmt->get_result()->fetch_assoc();

if (!$purchase) {
    // Debug hint
    $dbg = $conn->prepare("SELECT user_id, status FROM product_purchases WHERE download_token=? LIMIT 1");
    $dbg->bind_param("s", $token);
    $dbg->execute();
    $dbgRow = $dbg->get_result()->fetch_assoc();

    $hint = '';
    if ($dbgRow) {
        if (intval($dbgRow['user_id']) !== $userId) $hint = 'This link belongs to a different account.';
        elseif ($dbgRow['status'] !== 'completed')  $hint = 'Purchase status: '.$dbgRow['status'].'. Payment may still be processing.';
    } else {
        $hint = 'Token not found in database.';
    }

    die(renderError('Invalid or expired download link', $hint, true));
}

// ── Check access limit ────────────────────────────────────────────────────────
$dlCount = intval($purchase['download_count'] ?? 0);
$dlMax   = intval($purchase['max_downloads']  ?? 10);

if ($dlCount >= $dlMax) {
    die(renderError(
        'Access limit reached',
        'You have used all '.$dlMax.' accesses for "'.$purchase['title'].'". Please contact support if you need more.',
        false,
        '#f59e0b'
    ));
}

// ── Determine delivery type ───────────────────────────────────────────────────
$deliveryType = $purchase['delivery_type'] ?? 'file';

// ── Increment counter BEFORE serving (partial downloads still count) ──────────
$up = $conn->prepare("UPDATE product_purchases SET download_count = download_count + 1 WHERE download_token = ? AND user_id = ?");
$up->bind_param("si", $token, $userId);
$up->execute();

$dp2 = $conn->prepare("UPDATE digital_products SET downloads_count = COALESCE(downloads_count,0) + 1 WHERE id = ?");
$dp2->bind_param("i", $purchase['product_id']);
$dp2->execute();

/* ══════════════════════════════════════════════════════════════════════════════
   LINK DELIVERY — redirect to external URL
══════════════════════════════════════════════════════════════════════════════ */
if ($deliveryType === 'link') {

    // Use link stored on purchase row first, fall back to product table
    $link = $purchase['delivery_link'] ?? '';
    if (empty($link)) {
        $ls = $conn->prepare("SELECT delivery_link FROM digital_products WHERE id = ? LIMIT 1");
        $ls->bind_param("i", $purchase['product_id']); $ls->execute();
        $link = $ls->get_result()->fetch_assoc()['delivery_link'] ?? '';
    }

    if (empty($link)) {
        // Roll back counter since delivery failed
        $rb = $conn->prepare("UPDATE product_purchases SET download_count = download_count - 1 WHERE download_token = ? AND user_id = ?");
        $rb->bind_param("si", $token, $userId); $rb->execute();
        die(renderError('Delivery link not configured', 'The admin has not set a delivery link for this product. Please contact support. Reference: purchase #'.$purchase['id'].'.'));
    }

    // Validate URL for safety — prevent open redirect to javascript:, etc.
    if (!filter_var($link, FILTER_VALIDATE_URL) || !preg_match('/^https?:\/\//i', $link)) {
        die(renderError('Invalid delivery link', 'The configured delivery URL is malformed. Please contact support. Reference: purchase #'.$purchase['id'].'.'));
    }

    // Flush buffers and redirect
    while (ob_get_level()) ob_end_clean();
    header('Location: ' . $link);
    exit;
}

/* ══════════════════════════════════════════════════════════════════════════════
   FILE DELIVERY — resolve and serve file
══════════════════════════════════════════════════════════════════════════════ */
$basePath = dirname(dirname(__FILE__)) . '/secure_uploads/products/';
if (!is_dir($basePath)) {
    $basePath = dirname(__FILE__) . '/../secure_files/products/';
}

$filePath = rtrim($basePath, '/') . '/' . basename($purchase['file_path']);

// Fallback: admin may have stored absolute path
if (!file_exists($filePath)) {
    $filePath = $purchase['file_path'];
}

if (!file_exists($filePath) || !is_readable($filePath)) {
    error_log("Download failed: file not found. Purchase #{$purchase['id']}, path: {$filePath}");
    // Roll back counter
    $rb = $conn->prepare("UPDATE product_purchases SET download_count = download_count - 1 WHERE download_token = ? AND user_id = ?");
    $rb->bind_param("si", $token, $userId); $rb->execute();
    die(renderError('File not found on server', 'Please contact support. Reference: purchase #'.$purchase['id'].'.'));
}

// ── Serve file ────────────────────────────────────────────────────────────────
$mimeType = !empty($purchase['file_type'])
    ? $purchase['file_type']
    : (mime_content_type($filePath) ?: 'application/octet-stream');

$fileName = !empty($purchase['file_name'])
    ? $purchase['file_name']
    : basename($filePath);

$fileSize = filesize($filePath);

while (ob_get_level()) ob_end_clean();

header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="' . str_replace('"', '\\"', $fileName) . '"');
header('Content-Length: ' . $fileSize);
header('Cache-Control: private, no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

readfile($filePath);
exit;

/* ── Error page renderer ─────────────────────────────────────────────────────── */
function renderError($title, $msg = '', $showBack = true, $color = '#ef4444') {
    $back = $showBack ? '<br><br><a href="my_purchases.php" style="color:#6366f1;font-weight:700;font-size:13px">← Back to My Purchases</a>' : '<br><br><a href="my_purchases.php" style="color:#6366f1;font-weight:700;font-size:13px">← Back to My Purchases</a>';
    return '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Download Error</title>
    <style>body{font-family:Inter,sans-serif;background:#0a0f1e;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0}
    .box{text-align:center;padding:40px 32px;background:#1a2035;border-radius:16px;border:1.5px solid rgba(255,255,255,.1);max-width:420px;width:90%}
    h2{color:'.$color.';font-size:17px;margin:0 0 10px}p{color:#94a3b8;font-size:13px;line-height:1.6;margin:0}</style></head>
    <body><div class="box"><h2>'.$title.'</h2><p>'.$msg.'</p>'.$back.'</div></body></html>';
}