<?php
/**
 * ============================================================================
 * ajax/track-download.php - Track Resource Downloads
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

// Check if user is logged in
if (!isLoggedIn()) {
    jsonError('Unauthorized access', 401);
}

// Check if request is POST
if (!isPost()) {
    jsonError('Invalid request method');
}

// Check if resource ID is provided
if (!isset($_POST['resource_id']) || empty($_POST['resource_id'])) {
    jsonError('Resource ID is required');
}

$resourceId = (int)$_POST['resource_id'];
$userId = getUserId();

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // In production, you would:
    // 1. Fetch resource details from database
    // 2. Increment download counter
    // 3. Log download activity
    // 4. Return actual download URL
    
    // Log download activity
    $sql = "INSERT INTO activity_log (user_id, action, description) 
            VALUES (?, 'download_resource', ?)";
    $stmt = $db->prepare($sql);
    $stmt->execute([$userId, "Downloaded resource ID: $resourceId"]);
    
    // For demo purposes, return success
    jsonSuccess('Download tracked successfully', [
        'download_url' => APP_URL . '/assets/resources/sample.pdf',
        'resource_id' => $resourceId
    ]);
    
} catch (PDOException $e) {
    error_log("Error tracking download: " . $e->getMessage());
    jsonError('Failed to track download');
}
?>