<?php
// api/apps.php - API Endpoint for Apps Management

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

session_start();

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Database.php';
require_once __DIR__ . '/../src/OAuth.php';
require_once __DIR__ . '/../src/AdMobAPI.php';

$db = Database::getInstance();
$oauth = new OAuth(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI);

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

$access_token = $oauth->ensureValidToken($_SESSION['user_id']);

if (!$access_token) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid or expired token']);
    exit;
}

$admob = new AdMobAPI($access_token);

try {
    $stmt = $db->prepare("SELECT publisher_id FROM account_info LIMIT 1");
    $stmt->execute();
    $account = $stmt->fetch(PDO::FETCH_ASSOC);
    $account_id = $account['publisher_id'] ?? '';
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
    exit;
}

if (empty($account_id)) {
    http_response_code(400);
    echo json_encode(['error' => 'Account not configured']);
    exit;
}

if ($method === 'GET') {
    if ($action === 'list') {
        // Get apps from database first, then sync if needed
        try {
            $stmt = $db->prepare("SELECT * FROM apps_inventory ORDER BY app_name ASC");
            $stmt->execute();
            $cached_apps = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Try to fetch fresh data from API
            $api_response = $admob->listApps($account_id);

            if ($api_response['http_code'] === 200 && isset($api_response['data']['apps'])) {
                // Update cache with fresh data
                foreach ($api_response['data']['apps'] as $app) {
                    try {
                        $stmt = $db->prepare("
                            INSERT INTO apps_inventory (app_id, app_name, package_name, platform, store_id, app_data, last_updated)
                            VALUES (:app_id, :app_name, :package_name, :platform, :store_id, :app_data, NOW())
                            ON DUPLICATE KEY UPDATE
                            app_name = :app_name,
                            package_name = :package_name,
                            platform = :platform,
                            store_id = :store_id,
                            app_data = :app_data,
                            last_updated = NOW()
                        ");

                        $stmt->execute([
                            ':app_id' => $app['appId'] ?? $app['name'] ?? '',
                            ':app_name' => $app['displayName'] ?? $app['name'] ?? '',
                            ':package_name' => $app['name'] ?? '',
                            ':platform' => $app['platform'] ?? 'ANDROID',
                            ':store_id' => $app['appStore'] ?? '',
                            ':app_data' => json_encode($app)
                        ]);
                    } catch (PDOException $e) {
                        error_log('App Cache Error: ' . $e->getMessage());
                    }
                }

                $cached_apps = $api_response['data']['apps'];
            }

            echo json_encode([
                'success' => true,
                'data' => $cached_apps
            ]);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Database error']);
        }

    } elseif ($action === 'get' && isset($_GET['id'])) {
        $app_id = $_GET['id'];

        try {
            $stmt = $db->prepare("SELECT * FROM apps_inventory WHERE app_id = :app_id");
            $stmt->execute([':app_id' => $app_id]);
            $app = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($app) {
                $app['app_data'] = json_decode($app['app_data'], true);
                echo json_encode([
                    'success' => true,
                    'data' => $app
                ]);
            } else {
                http_response_code(404);
                echo json_encode(['error' => 'App not found']);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Database error']);
        }

    } elseif ($action === 'sync') {
        // Sync apps from AdMob API
        $api_response = $admob->listApps($account_id);

        if ($api_response['http_code'] === 200) {
            $synced_count = 0;

            foreach ($api_response['data']['apps'] ?? [] as $app) {
                try {
                    $stmt = $db->prepare("
                        INSERT INTO apps_inventory (app_id, app_name, package_name, platform, store_id, app_data, last_updated)
                        VALUES (:app_id, :app_name, :package_name, :platform, :store_id, :app_data, NOW())
                        ON DUPLICATE KEY UPDATE
                        app_name = :app_name,
                        package_name = :package_name,
                        platform = :platform,
                        store_id = :store_id,
                        app_data = :app_data,
                        last_updated = NOW()
                    ");

                    $stmt->execute([
                        ':app_id' => $app['appId'] ?? $app['name'] ?? '',
                        ':app_name' => $app['displayName'] ?? $app['name'] ?? '',
                        ':package_name' => $app['name'] ?? '',
                        ':platform' => $app['platform'] ?? 'ANDROID',
                        ':store_id' => $app['appStore'] ?? '',
                        ':app_data' => json_encode($app)
                    ]);

                    $synced_count++;
                } catch (PDOException $e) {
                    error_log('App Sync Error: ' . $e->getMessage());
                }
            }

            echo json_encode([
                'success' => true,
                'message' => $synced_count . ' apps synced',
                'count' => $synced_count
            ]);
        } else {
            http_response_code($api_response['http_code']);
            echo json_encode([
                'success' => false,
                'error' => $api_response['data']['error']['message'] ?? 'Failed to sync apps'
            ]);
        }

    } else {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
    }

} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

?>