<?php
/**
 * Subscription API for Ensi English Learning App
 * Clean version - Built from scratch based on working test files
 */

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

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Database credentials (from config.php)
define('DB_HOST', 'localhost');
define('DB_USER', 'playbdqv_finalensi');
define('DB_PASS', 'playbdqv_finalensi');
define('DB_NAME', 'playbdqv_finalensi');

// App Store shared secret (from App Store Connect)
define('APPLE_SHARED_SECRET', '8158a0d61c9649b9a132fe13d6559d63');

// Helper function to send JSON response
function sendResponse($success, $message, $data = null) {
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ], JSON_PRETTY_PRINT);
    exit();
}

// Helper function to log subscription actions
function logSubscription($conn, $userId, $action, $platform, $transactionId, $status, $message, $requestData = null, $responseData = null) {
    $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    
    $stmt = $conn->prepare("
        INSERT INTO subscription_logs 
        (user_id, action, platform, transaction_id, status, message, request_data, response_data, ip_address)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->bind_param(
        "issssssss",
        $userId,
        $action,
        $platform,
        $transactionId,
        $status,
        $message,
        $requestData,
        $responseData,
        $ipAddress
    );
    
    $stmt->execute();
    $stmt->close();
}

// Get user ID from token
function getUserIdFromToken($conn, $token) {
    if (empty($token)) {
        return null;
    }
    
    $stmt = $conn->prepare("
        SELECT user_id FROM user_sessions 
        WHERE token = ? AND expires_at > NOW()
        LIMIT 1
    ");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $stmt->close();
        return $row['user_id'];
    }
    
    $stmt->close();
    return null;
}

// Verify iOS receipt with Apple
function verifyAppleReceipt($receiptData, $isSandbox = false) {
    $endpoint = $isSandbox 
        ? 'https://sandbox.itunes.apple.com/verifyReceipt'
        : 'https://buy.itunes.apple.com/verifyReceipt';
    
    $postData = json_encode([
        'receipt-data' => $receiptData,
        'password' => APPLE_SHARED_SECRET,
        'exclude-old-transactions' => true
    ]);
    
    $ch = curl_init($endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        return ['status' => 'error', 'message' => 'Failed to connect to Apple'];
    }
    
    $result = json_decode($response, true);
    
    // If sandbox receipt sent to production, try sandbox
    if (!$isSandbox && isset($result['status']) && $result['status'] == 21007) {
        return verifyAppleReceipt($receiptData, true);
    }
    
    return $result;
}

// Main API logic
try {
    // Connect to database
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    
    if ($conn->connect_error) {
        sendResponse(false, 'Database connection failed: ' . $conn->connect_error);
    }
    
    $conn->set_charset("utf8mb4");
    
    $action = $_GET['action'] ?? $_POST['action'] ?? '';
    
    switch ($action) {
        
        // ============================================
        // Get available subscription products
        // ============================================
        case 'get_products':
            $platform = $_GET['platform'] ?? $_POST['platform'] ?? 'ios';
            
            $stmt = $conn->prepare("
                SELECT product_id, title, price_usd, duration_days, description, features
                FROM subscription_products
                WHERE is_active = 1 AND (platform = ? OR platform = 'both')
                ORDER BY price_usd ASC
            ");
            
            $stmt->bind_param("s", $platform);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $products = [];
            while ($row = $result->fetch_assoc()) {
                $products[] = [
                    'product_id' => $row['product_id'],
                    'title' => $row['title'],
                    'price_usd' => $row['price_usd'],
                    'duration_days' => (int)$row['duration_days'],
                    'description' => $row['description'],
                    'features' => json_decode($row['features'] ?? '[]')
                ];
            }
            
            $stmt->close();
            $conn->close();
            
            sendResponse(true, 'Products retrieved successfully', [
                'count' => count($products),
                'products' => $products
            ]);
            break;
        
        // ============================================
        // Get user's subscription status
        // ============================================
        case 'get_status':
            $token = $_GET['token'] ?? $_POST['token'] ?? '';
            $userId = getUserIdFromToken($conn, $token);
            
            if (!$userId) {
                sendResponse(false, 'Invalid or missing token');
            }
            
            // Get user subscription info
            $stmt = $conn->prepare("
                SELECT id, email, user_name, user_level, subscription_type, subscription_expires_at
                FROM users 
                WHERE id = ?
            ");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $result = $stmt->get_result();
            $user = $result->fetch_assoc();
            $stmt->close();
            
            if (!$user) {
                sendResponse(false, 'User not found');
            }
            
            // Get active subscription
            $stmt = $conn->prepare("
                SELECT * FROM subscriptions 
                WHERE user_id = ? AND is_active = 1 
                ORDER BY expires_at DESC LIMIT 1
            ");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $result = $stmt->get_result();
            $subscription = $result->fetch_assoc();
            $stmt->close();
            
            $conn->close();
            
            $hasActive = $user['subscription_expires_at'] && strtotime($user['subscription_expires_at']) > time();
            
            sendResponse(true, 'Status retrieved successfully', [
                'user' => $user,
                'subscription' => $subscription,
                'has_active_subscription' => $hasActive,
                'can_access_pro' => in_array($user['user_level'], ['pro', 'vip'])
            ]);
            break;
        
        // ============================================
        // Verify iOS purchase
        // ============================================
        case 'verify_ios':
            $token = $_POST['token'] ?? '';
            $receiptData = $_POST['receipt_data'] ?? '';
            $productId = $_POST['product_id'] ?? '';
            
            $userId = getUserIdFromToken($conn, $token);
            
            if (!$userId) {
                logSubscription($conn, null, 'verify_ios', 'ios', null, 'failed', 'Invalid token', json_encode($_POST), null);
                sendResponse(false, 'Invalid or missing token');
            }
            
            if (empty($receiptData)) {
                logSubscription($conn, $userId, 'verify_ios', 'ios', null, 'failed', 'Missing receipt data', json_encode($_POST), null);
                sendResponse(false, 'Receipt data is required');
            }
            
            // Verify with Apple
            $verification = verifyAppleReceipt($receiptData);
            
            logSubscription(
                $conn, 
                $userId, 
                'verify_ios', 
                'ios', 
                null, 
                'pending', 
                'Apple verification attempted',
                json_encode(['product_id' => $productId]),
                json_encode($verification)
            );
            
            if (!isset($verification['status']) || $verification['status'] !== 0) {
                $errorMsg = 'Apple verification failed';
                if (isset($verification['status'])) {
                    $errorMsg .= ' (Status: ' . $verification['status'] . ')';
                }
                sendResponse(false, $errorMsg);
            }
            
            // Extract purchase info
            $latestReceipt = $verification['latest_receipt_info'][0] ?? null;
            if (!$latestReceipt) {
                sendResponse(false, 'No receipt info found');
            }
            
            $transactionId = $latestReceipt['transaction_id'];
            $originalTransactionId = $latestReceipt['original_transaction_id'];
            $purchaseDate = date('Y-m-d H:i:s', $latestReceipt['purchase_date_ms'] / 1000);
            $expiresDate = date('Y-m-d H:i:s', $latestReceipt['expires_date_ms'] / 1000);
            
            // Determine subscription type and price
            $subscriptionType = strpos($productId, 'monthly') !== false ? 'pro_monthly' : 'pro_yearly';
            $price = strpos($productId, 'monthly') !== false ? 8.99 : 99.99;
            
            // Check if already processed
            $stmt = $conn->prepare("SELECT id FROM subscriptions WHERE transaction_id = ? AND platform = 'ios'");
            $stmt->bind_param("s", $transactionId);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $stmt->close();
                sendResponse(true, 'Purchase already processed', ['already_active' => true]);
            }
            $stmt->close();
            
            // Insert subscription record
            $stmt = $conn->prepare("
                INSERT INTO subscriptions 
                (user_id, subscription_type, platform, product_id, transaction_id, original_transaction_id, 
                 receipt_data, price, currency, purchase_date, expires_at, is_active)
                VALUES (?, ?, 'ios', ?, ?, ?, ?, ?, 'USD', ?, ?, 1)
            ");
            $stmt->bind_param(
                "isssssds",
                $userId,
                $subscriptionType,
                $productId,
                $transactionId,
                $originalTransactionId,
                $receiptData,
                $price,
                $purchaseDate,
                $expiresDate
            );
            $stmt->execute();
            $stmt->close();
            
            // Update user record
            $stmt = $conn->prepare("
                UPDATE users 
                SET user_level = 'pro', 
                    subscription_type = ?, 
                    subscription_expires_at = ?
                WHERE id = ?
            ");
            $stmt->bind_param("ssi", $subscriptionType, $expiresDate, $userId);
            $stmt->execute();
            $stmt->close();
            
            logSubscription(
                $conn, 
                $userId, 
                'verify_ios', 
                'ios', 
                $transactionId, 
                'success', 
                'Purchase verified and activated',
                json_encode(['product_id' => $productId]),
                json_encode($verification)
            );
            
            $conn->close();
            
            sendResponse(true, 'Purchase verified successfully', [
                'subscription_type' => $subscriptionType,
                'expires_at' => $expiresDate,
                'user_level' => 'pro'
            ]);
            break;
        
        // ============================================
        // Restore iOS purchases
        // ============================================
        case 'restore_ios':
            $token = $_POST['token'] ?? '';
            $receiptData = $_POST['receipt_data'] ?? '';
            
            $userId = getUserIdFromToken($conn, $token);
            
            if (!$userId) {
                sendResponse(false, 'Invalid or missing token');
            }
            
            if (empty($receiptData)) {
                sendResponse(false, 'Receipt data is required');
            }
            
            // Verify with Apple
            $verification = verifyAppleReceipt($receiptData);
            
            if (!isset($verification['status']) || $verification['status'] !== 0) {
                sendResponse(false, 'Apple verification failed');
            }
            
            // Find active subscriptions
            $latestReceiptInfo = $verification['latest_receipt_info'] ?? [];
            $activeCount = 0;
            
            foreach ($latestReceiptInfo as $receipt) {
                $expiresMs = $receipt['expires_date_ms'] ?? 0;
                if ($expiresMs > time() * 1000) {
                    $activeCount++;
                }
            }
            
            if ($activeCount > 0) {
                $latestReceipt = $latestReceiptInfo[0];
                $expiresDate = date('Y-m-d H:i:s', $latestReceipt['expires_date_ms'] / 1000);
                $productId = $latestReceipt['product_id'];
                $subscriptionType = strpos($productId, 'monthly') !== false ? 'pro_monthly' : 'pro_yearly';
                
                // Update user
                $stmt = $conn->prepare("
                    UPDATE users 
                    SET user_level = 'pro', 
                        subscription_type = ?, 
                        subscription_expires_at = ?
                    WHERE id = ?
                ");
                $stmt->bind_param("ssi", $subscriptionType, $expiresDate, $userId);
                $stmt->execute();
                $stmt->close();
                
                logSubscription($conn, $userId, 'restore_ios', 'ios', null, 'success', 'Purchases restored', null, null);
                
                $conn->close();
                
                sendResponse(true, 'Purchases restored successfully', [
                    'subscription_type' => $subscriptionType,
                    'expires_at' => $expiresDate,
                    'active_count' => $activeCount
                ]);
            } else {
                $conn->close();
                sendResponse(false, 'No active subscriptions found');
            }
            break;
        
        default:
            $conn->close();
            sendResponse(false, 'Invalid action: ' . $action);
            break;
    }
    
} catch (Exception $e) {
    if (isset($conn)) {
        $conn->close();
    }
    sendResponse(false, 'Server error: ' . $e->getMessage());
}
