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

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

// Start logging
error_log("=== VIDEO REWARD API CALL START ===");
error_log("Request Method: " . $_SERVER['REQUEST_METHOD']);
error_log("Request Headers: " . json_encode(getallheaders()));
error_log("Request Body: " . file_get_contents('php://input'));

// Verify API Hash
verifyAPIHash();

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

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    error_log("❌ Invalid JSON data");
    sendError('Invalid JSON data');
}

$token = $input['token'] ?? '';
$adUnitId = $input['ad_unit_id'] ?? '';

error_log("Token: " . substr($token, 0, 20) . "...");
error_log("Ad Unit ID: " . $adUnitId);

// Validate input
if (empty($token) || empty($adUnitId)) {
    error_log("❌ Missing token or ad_unit_id");
    sendError('Token and ad_unit_id are required');
}

// Verify JWT token
$payload = verifyJWT($token);
if (!$payload) {
    error_log("❌ Invalid JWT token");
    sendError('Invalid or expired token', 401);
}

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

// Debug current state
debugUserVideoRewards($pdo, $userId);

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("Creating video_rewards table...");
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS video_rewards (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                ad_unit_id VARCHAR(255) NOT NULL,
                coins_earned INT NOT NULL,
                viewed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_user_date (user_id, DATE(viewed_at)),
                INDEX idx_user_ad_date (user_id, ad_unit_id, DATE(viewed_at))
            )
        ");
        error_log("Video rewards table created successfully");
    }
    
    // Get AdMob settings
    $stmt = $pdo->query("SELECT reward_coins, daily_limit, is_active FROM admob_settings LIMIT 1");
    $settings = $stmt->fetch(PDO::FETCH_ASSOC);
    
    error_log("AdMob Settings: " . json_encode($settings));
    
    if (!$settings) {
        error_log("❌ AdMob settings not found");
        sendError('AdMob settings not configured', 404);
    }
    
    if (!$settings['is_active']) {
        error_log("❌ AdMob is disabled");
        sendError('AdMob is currently disabled', 403);
    }
    
    // Check daily limit
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as today_views 
        FROM video_rewards 
        WHERE user_id = ? AND DATE(viewed_at) = CURDATE()
    ");
    $stmt->execute([$userId]);
    $todayViews = $stmt->fetch(PDO::FETCH_ASSOC)['today_views'];
    
    error_log("Today's views for user $userId: $todayViews");
    error_log("Daily limit: " . $settings['daily_limit']);
    
    if ($todayViews >= $settings['daily_limit']) {
        error_log("❌ Daily limit reached for user $userId");
        sendError('Daily video limit reached. Try again tomorrow.', 429);
    }
    
    // Remove the check for duplicate ad_unit_id - allow multiple views of same ad
    // as long as daily limit is not exceeded
    
    // Get current user data before update
    $stmt = $pdo->prepare("SELECT coins, free_coins FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $userBefore = $stmt->fetch(PDO::FETCH_ASSOC);
    error_log("User data before reward: " . json_encode($userBefore));
    
    // Start transaction
    $pdo->beginTransaction();
    error_log("Database transaction started");
    
    // Add free coins to user
    $stmt = $pdo->prepare("UPDATE users SET free_coins = free_coins + ? WHERE id = ?");
    $updateResult = $stmt->execute([$settings['reward_coins'], $userId]);
    error_log("Update users result: " . ($updateResult ? "SUCCESS" : "FAILED"));
    
    // Record video reward
    $stmt = $pdo->prepare("
        INSERT INTO video_rewards (user_id, ad_unit_id, coins_earned, viewed_at) 
        VALUES (?, ?, ?, NOW())
    ");
    $insertResult = $stmt->execute([$userId, $adUnitId, $settings['reward_coins']]);
    error_log("Insert video_rewards result: " . ($insertResult ? "SUCCESS" : "FAILED"));
    
    // Add transaction record
    $stmt = $pdo->prepare("
        INSERT INTO transactions (user_id, type, amount, coin_type, description, created_at) 
        VALUES (?, 'video_reward', ?, 'free', 'Video ad reward', NOW())
    ");
    $transactionResult = $stmt->execute([$userId, $settings['reward_coins']]);
    error_log("Insert transactions result: " . ($transactionResult ? "SUCCESS" : "FAILED"));
    
    $pdo->commit();
    error_log("Database transaction committed successfully");
    
    // Get updated user data
    $stmt = $pdo->prepare("SELECT coins, free_coins FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $userAfter = $stmt->fetch(PDO::FETCH_ASSOC);
    error_log("User data after reward: " . json_encode($userAfter));
    
    $response = [
        'success' => true,
        'message' => 'Video reward claimed successfully',
        'data' => [
            'coins_earned' => $settings['reward_coins'],
            'total_coins' => $userAfter['coins'],
            'total_free_coins' => $userAfter['free_coins'],
            'daily_views_remaining' => $settings['daily_limit'] - ($todayViews + 1)
        ]
    ];
    
    error_log("✅ Success response: " . json_encode($response));
    error_log("=== VIDEO REWARD API CALL END ===");
    
    sendResponse($response);
    
} catch (Exception $e) {
    error_log("❌ Exception occurred: " . $e->getMessage());
    error_log("Exception stack trace: " . $e->getTraceAsString());
    
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
        error_log("Database transaction rolled back");
    }
    
    error_log("=== VIDEO REWARD API CALL END WITH ERROR ===");
    sendError('Database error: ' . $e->getMessage(), 500);
}

// Debug function to check user's video reward status
function debugUserVideoRewards($pdo, $userId) {
    error_log("=== DEBUG USER VIDEO REWARDS ===");
    error_log("User ID: $userId");
    
    // Check user's current coins
    $stmt = $pdo->prepare("SELECT coins, free_coins FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $userData = $stmt->fetch(PDO::FETCH_ASSOC);
    error_log("User coins: " . json_encode($userData));
    
    // Check today's video rewards count
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as today_count 
        FROM video_rewards 
        WHERE user_id = ? AND DATE(viewed_at) = CURDATE()
    ");
    $stmt->execute([$userId]);
    $todayCount = $stmt->fetch(PDO::FETCH_ASSOC)['today_count'];
    error_log("Today's video count: $todayCount");
    
    // Check today's video rewards details
    $stmt = $pdo->prepare("
        SELECT ad_unit_id, coins_earned, viewed_at 
        FROM video_rewards 
        WHERE user_id = ? AND DATE(viewed_at) = CURDATE()
        ORDER BY viewed_at DESC
    ");
    $stmt->execute([$userId]);
    $todayRewards = $stmt->fetchAll(PDO::FETCH_ASSOC);
    error_log("Today's video rewards: " . json_encode($todayRewards));
    
    // Check AdMob settings
    $stmt = $pdo->query("SELECT reward_coins, daily_limit, is_active FROM admob_settings LIMIT 1");
    $settings = $stmt->fetch(PDO::FETCH_ASSOC);
    error_log("AdMob settings: " . json_encode($settings));
    
    if ($settings) {
        $remaining = $settings['daily_limit'] - $todayCount;
        error_log("Remaining videos today: $remaining");
    }
    
    error_log("=== END DEBUG ===");
}
?>
