<?php
// api/account.php - Account Management API

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);

if ($method === 'GET') {
    if ($action === 'info') {
        // Get account information
        try {
            $stmt = $db->prepare("SELECT * FROM account_info LIMIT 1");
            $stmt->execute();
            $account = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($account) {
                $account['account_data'] = json_decode($account['account_data'], true);
                echo json_encode([
                    'success' => true,
                    'data' => $account
                ]);
            } else {
                // Fetch from API
                $api_response = $admob->getAccountInfo();
                
                if ($api_response['http_code'] === 200 && isset($api_response['data']['accounts'])) {
                    $accounts = $api_response['data']['accounts'];
                    
                    if (count($accounts) > 0) {
                        $account = $accounts[0];
                        
                        // Save to database
                        $stmt = $db->prepare("
                            INSERT INTO account_info (publisher_id, account_name, timezone, currency_code, account_data, last_updated)
                            VALUES (:publisher_id, :account_name, :timezone, :currency_code, :account_data, NOW())
                            ON DUPLICATE KEY UPDATE
                            account_data = :account_data,
                            last_updated = NOW()
                        ");
                        
                        $stmt->execute([
                            ':publisher_id' => $account['name'] ?? '',
                            ':account_name' => $account['displayName'] ?? 'AdMob Account',
                            ':timezone' => $account['timezone'] ?? 'UTC',
                            ':currency_code' => $account['currencyCode'] ?? 'USD',
                            ':account_data' => json_encode($account)
                        ]);
                        
                        echo json_encode([
                            'success' => true,
                            'data' => $account
                        ]);
                    } else {
                        http_response_code(404);
                        echo json_encode(['error' => 'No accounts found']);
                    }
                } else {
                    http_response_code($api_response['http_code']);
                    echo json_encode([
                        'success' => false,
                        'error' => $api_response['data']['error']['message'] ?? 'Failed to fetch account info'
                    ]);
                }
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Database error']);
        }

    } elseif ($action === 'sync') {
        // Sync account info from API
        $api_response = $admob->getAccountInfo();
        
        if ($api_response['http_code'] === 200 && isset($api_response['data']['accounts'])) {
            $accounts = $api_response['data']['accounts'];
            
            if (count($accounts) > 0) {
                $account = $accounts[0];
                
                try {
                    $stmt = $db->prepare("
                        INSERT INTO account_info (publisher_id, account_name, timezone, currency_code, account_data, last_updated)
                        VALUES (:publisher_id, :account_name, :timezone, :currency_code, :account_data, NOW())
                        ON DUPLICATE KEY UPDATE
                        account_name = :account_name,
                        timezone = :timezone,
                        currency_code = :currency_code,
                        account_data = :account_data,
                        last_updated = NOW()
                    ");
                    
                    $stmt->execute([
                        ':publisher_id' => $account['name'] ?? '',
                        ':account_name' => $account['displayName'] ?? 'AdMob Account',
                        ':timezone' => $account['timezone'] ?? 'UTC',
                        ':currency_code' => $account['currencyCode'] ?? 'USD',
                        ':account_data' => json_encode($account)
                    ]);
                    
                    echo json_encode([
                        'success' => true,
                        'message' => 'Account synced successfully'
                    ]);
                } catch (PDOException $e) {
                    http_response_code(500);
                    echo json_encode(['error' => 'Database error']);
                }
            } else {
                http_response_code(404);
                echo json_encode(['error' => 'No accounts found']);
            }
        } else {
            http_response_code($api_response['http_code']);
            echo json_encode([
                'success' => false,
                'error' => $api_response['data']['error']['message'] ?? 'Failed to sync account'
            ]);
        }

    } elseif ($action === 'stats') {
        // Get dashboard statistics
        try {
            $stmt = $db->query("
                SELECT 
                    COUNT(DISTINCT app_id) as total_apps,
                    COUNT(DISTINCT ad_unit_id) as total_ad_units
                FROM ad_units
            ");
            
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'data' => $stats
            ]);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Database error']);
        }

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

} elseif ($method === 'POST') {
    if ($action === 'update') {
        // Update account preferences
        $input = json_decode(file_get_contents('php://input'), true);
        
        // This would update user preferences
        // For now, just return success
        echo json_encode([
            'success' => true,
            'message' => 'Preferences updated'
        ]);

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

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

?>