<?php
require_once '../config.php';
require_once '../lib.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $user_id = getUserIdFromToken($_COOKIE['auth_token'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? null);

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        if (!$user_id) {
            throw new Exception('Authentication required');
        }

        $type = $_GET['type'] ?? 'overview';
        
        if ($type === 'overview') {
            // Get user loyalty overview
            $stmt = $pdo->prepare("
                SELECT * FROM user_loyalty_points WHERE user_id = ?
            ");
            $stmt->execute([$user_id]);
            $loyalty = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$loyalty) {
                // Create loyalty account
                $stmt = $pdo->prepare("
                    INSERT INTO user_loyalty_points (user_id) VALUES (?)
                ");
                $stmt->execute([$user_id]);
                
                $stmt = $pdo->prepare("
                    SELECT * FROM user_loyalty_points WHERE user_id = ?
                ");
                $stmt->execute([$user_id]);
                $loyalty = $stmt->fetch(PDO::FETCH_ASSOC);
            }
            
            // Get recent transactions
            $stmt = $pdo->prepare("
                SELECT * FROM points_transactions 
                WHERE user_id = ? 
                ORDER BY created_at DESC 
                LIMIT 10
            ");
            $stmt->execute([$user_id]);
            $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'loyalty' => $loyalty,
                'transactions' => $transactions
            ]);
            
        } elseif ($type === 'rewards') {
            // Get available rewards
            $stmt = $pdo->prepare("
                SELECT ulp.tier_level, ulp.available_points
                FROM user_loyalty_points ulp 
                WHERE ulp.user_id = ?
            ");
            $stmt->execute([$user_id]);
            $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user_data) {
                $user_data = ['tier_level' => 'bronze', 'available_points' => 0];
            }
            
            $stmt = $pdo->prepare("
                SELECT * FROM rewards_catalog 
                WHERE is_active = TRUE 
                AND (tier_required = ? OR tier_required = 'bronze')
                ORDER BY points_required ASC
            ");
            $stmt->execute([$user_data['tier_level']]);
            $rewards = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Mark affordable rewards
            foreach ($rewards as &$reward) {
                $reward['can_afford'] = $user_data['available_points'] >= $reward['points_required'];
            }
            
            echo json_encode([
                'success' => true,
                'rewards' => $rewards,
                'user_points' => $user_data['available_points'],
                'user_tier' => $user_data['tier_level']
            ]);
            
        } elseif ($type === 'referral') {
            // Get referral info
            $stmt = $pdo->prepare("
                SELECT u.first_name, u.last_name, u.id
                FROM users u WHERE u.id = ?
            ");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $referral_code = strtoupper(substr($user['first_name'], 0, 3) . substr($user['last_name'], 0, 3) . $user['id']);
            
            // Get referral stats
            $stmt = $pdo->prepare("
                SELECT COUNT(*) as total_referrals,
                       SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_referrals,
                       SUM(referrer_points) as total_points_earned
                FROM referrals 
                WHERE referrer_id = ?
            ");
            $stmt->execute([$user_id]);
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'referral_code' => $referral_code,
                'stats' => $stats
            ]);
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$user_id) {
            throw new Exception('Authentication required');
        }
        
        $input = json_decode(file_get_contents('php://input'), true);
        $action = $input['action'] ?? 'redeem';
        
        if ($action === 'redeem') {
            $reward_id = $input['reward_id'] ?? null;
            if (!$reward_id) {
                throw new Exception('Reward ID is required');
            }
            
            // Get reward details
            $stmt = $pdo->prepare("
                SELECT * FROM rewards_catalog WHERE id = ? AND is_active = TRUE
            ");
            $stmt->execute([$reward_id]);
            $reward = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$reward) {
                throw new Exception('Reward not found');
            }
            
            // Get user points
            $stmt = $pdo->prepare("
                SELECT * FROM user_loyalty_points WHERE user_id = ?
            ");
            $stmt->execute([$user_id]);
            $loyalty = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$loyalty || $loyalty['available_points'] < $reward['points_required']) {
                throw new Exception('Insufficient points');
            }
            
            // Check tier requirement
            $tier_order = ['bronze' => 1, 'silver' => 2, 'gold' => 3, 'platinum' => 4];
            if ($tier_order[$loyalty['tier_level']] < $tier_order[$reward['tier_required']]) {
                throw new Exception('Tier requirement not met');
            }
            
            // Generate redemption code
            $redemption_code = strtoupper(uniqid('RWD'));
            
            // Start transaction
            $pdo->beginTransaction();
            
            try {
                // Deduct points
                $stmt = $pdo->prepare("
                    UPDATE user_loyalty_points 
                    SET available_points = available_points - ? 
                    WHERE user_id = ?
                ");
                $stmt->execute([$reward['points_required'], $user_id]);
                
                // Record redemption
                $stmt = $pdo->prepare("
                    INSERT INTO reward_redemptions (user_id, reward_id, points_used, redemption_code, expires_at)
                    VALUES (?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL 30 DAY))
                ");
                $stmt->execute([$user_id, $reward_id, $reward['points_required'], $redemption_code]);
                
                // Record transaction
                $stmt = $pdo->prepare("
                    INSERT INTO points_transactions (user_id, transaction_type, points, reason, reference_type, reference_id)
                    VALUES (?, 'redeemed', ?, ?, 'redemption', ?)
                ");
                $stmt->execute([$user_id, -$reward['points_required'], 'Redeemed: ' . $reward['name'], $pdo->lastInsertId()]);
                
                $pdo->commit();
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Reward redeemed successfully',
                    'redemption_code' => $redemption_code
                ]);
                
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            
        } elseif ($action === 'add_points') {
            // Add points (for system use)
            $points = $input['points'] ?? 0;
            $reason = $input['reason'] ?? 'Points awarded';
            $reference_type = $input['reference_type'] ?? 'bonus';
            $reference_id = $input['reference_id'] ?? null;
            
            if ($points <= 0) {
                throw new Exception('Invalid points amount');
            }
            
            // Add points to user account
            $stmt = $pdo->prepare("
                INSERT INTO user_loyalty_points (user_id, total_points, available_points, lifetime_points)
                VALUES (?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                total_points = total_points + VALUES(total_points),
                available_points = available_points + VALUES(available_points),
                lifetime_points = lifetime_points + VALUES(lifetime_points)
            ");
            $stmt->execute([$user_id, $points, $points, $points]);
            
            // Record transaction
            $stmt = $pdo->prepare("
                INSERT INTO points_transactions (user_id, transaction_type, points, reason, reference_type, reference_id)
                VALUES (?, 'earned', ?, ?, ?, ?)
            ");
            $stmt->execute([$user_id, $points, $reason, $reference_type, $reference_id]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Points added successfully'
            ]);
        }
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>