<?php
require_once '../../includes/functions.php';
setCORSHeaders();

// Enable comprehensive error logging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// Start detailed logging
error_log("=== REWARD HISTORY API CALL START ===");
error_log("Timestamp: " . date('Y-m-d H:i:s'));
error_log("Request Method: " . $_SERVER['REQUEST_METHOD']);
error_log("Request URI: " . $_SERVER['REQUEST_URI']);
error_log("Request Headers: " . json_encode(getallheaders()));
error_log("Query Parameters: " . json_encode($_GET));
error_log("Request Body: " . file_get_contents('php://input'));

// Verify API Hash
try {
    verifyAPIHash();
    error_log("✅ API Hash verification passed");
} catch (Exception $e) {
    error_log("❌ API Hash verification failed: " . $e->getMessage());
    sendError('Invalid API hash', 401);
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    error_log("❌ Invalid request method: " . $_SERVER['REQUEST_METHOD']);
    sendError('Method not allowed', 405);
}

// Get authorization header
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
error_log("Authorization Header: " . $authHeader);

if (empty($authHeader)) {
    error_log("❌ Missing Authorization header");
    sendError('Authorization header required', 401);
}

// Extract token from Bearer format
$token = str_replace('Bearer ', '', $authHeader);
error_log("Extracted Token: " . substr($token, 0, 20) . "...");

// Verify JWT token
try {
    $payload = verifyJWT($token);
    if (!$payload) {
        error_log("❌ Invalid JWT token");
        sendError('Invalid or expired token', 401);
    }
    error_log("✅ JWT token verified successfully");
    error_log("Token payload: " . json_encode($payload));
} catch (Exception $e) {
    error_log("❌ JWT verification error: " . $e->getMessage());
    sendError('Token verification failed', 401);
}

$userId = $payload['user_id'];
error_log("User ID: " . $userId);

// Get pagination parameters
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
$offset = ($page - 1) * $limit;

error_log("Pagination - Page: $page, Limit: $limit, Offset: $offset");

// Validate pagination parameters
if ($page < 1 || $limit < 1 || $limit > 100) {
    error_log("❌ Invalid pagination parameters");
    sendError('Invalid pagination parameters', 400);
}

try {
    // Check if video_rewards table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'video_rewards'");
    $tableExists = $stmt->fetch();
    error_log("Video rewards table exists: " . ($tableExists ? "YES" : "NO"));
    
    if (!$tableExists) {
        error_log("❌ Video rewards table does not exist");
        sendError('Reward history not available', 404);
    }
    
    // Get total count for pagination
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM video_rewards WHERE user_id = ?");
    $stmt->execute([$userId]);
    $totalCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    error_log("Total reward records for user $userId: $totalCount");
    
    // Get reward history with pagination
    $stmt = $pdo->prepare("
        SELECT 
            vr.id,
            vr.ad_unit_id,
            vr.coins_earned,
            vr.viewed_at,
            'video_reward' as reward_type
        FROM video_rewards vr
        WHERE vr.user_id = ?
        ORDER BY vr.viewed_at DESC
        LIMIT " . (int)$limit . " OFFSET " . (int)$offset
    );
    $stmt->execute([$userId]);
    $rewards = $stmt->fetchAll(PDO::FETCH_ASSOC);
    error_log("Retrieved " . count($rewards) . " reward records");
    error_log("SQL Query executed successfully with LIMIT " . (int)$limit . " OFFSET " . (int)$offset);
    
    // Format the response data according to Android app expectations
    $formattedRewards = [];
    foreach ($rewards as $reward) {
        $formattedRewards[] = [
            'id' => (int)$reward['id'],
            'userId' => (int)$userId,
            'adUnitId' => $reward['ad_unit_id'],
            'rewardCoins' => (int)$reward['coins_earned'],
            'rewardType' => $reward['reward_type'],
            'status' => 'completed', // All video rewards are completed
            'createdAt' => $reward['viewed_at'],
            'completedAt' => $reward['viewed_at']
        ];
    }
    
    $response = [
        'success' => true,
        'message' => 'Reward history retrieved successfully',
        'data' => [
            'rewardHistory' => $formattedRewards
        ]
    ];
    
    error_log("✅ Success response prepared");
    error_log("Response data: " . json_encode($response));
    error_log("=== REWARD HISTORY API CALL END SUCCESS ===");
    
    sendResponse($response);
    
} catch (Exception $e) {
    error_log("❌ Exception occurred: " . $e->getMessage());
    error_log("Exception stack trace: " . $e->getTraceAsString());
    error_log("=== REWARD HISTORY API CALL END WITH ERROR ===");
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>
