<?php
// api/ad-units.php - API Endpoint for Ad Units 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 ($method === 'GET') {
    if ($action === 'list') {
        $app_id = $_GET['app_id'] ?? null;

        try {
            if ($app_id) {
                $stmt = $db->prepare("SELECT * FROM ad_units WHERE app_id = :app_id ORDER BY ad_unit_name ASC");
                $stmt->execute([':app_id' => $app_id]);
            } else {
                $stmt = $db->prepare("SELECT * FROM ad_units ORDER BY ad_unit_name ASC");
                $stmt->execute();
            }

            $cached_units = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

            if ($api_response['http_code'] === 200 && isset($api_response['data']['adUnits'])) {
                // Update cache
                foreach ($api_response['data']['adUnits'] as $unit) {
                    try {
                        $stmt = $db->prepare("
                            INSERT INTO ad_units (ad_unit_id, ad_unit_name, app_id, ad_format, ad_types, ad_unit_data, last_updated)
                            VALUES (:ad_unit_id, :ad_unit_name, :app_id, :ad_format, :ad_types, :ad_unit_data, NOW())
                            ON DUPLICATE KEY UPDATE
                            ad_unit_name = :ad_unit_name,
                            app_id = :app_id,
                            ad_format = :ad_format,
                            ad_types = :ad_types,
                            ad_unit_data = :ad_unit_data,
                            last_updated = NOW()
                        ");

                        $app_id_parsed = isset($unit['app']) ? ($unit['app']['appId'] ?? $unit['app']['name'] ?? '') : '';

                        $stmt->execute([
                            ':ad_unit_id' => $unit['adUnitId'] ?? $unit['name'] ?? '',
                            ':ad_unit_name' => $unit['displayName'] ?? $unit['name'] ?? '',
                            ':app_id' => $app_id_parsed,
                            ':ad_format' => $unit['adFormat'] ?? 'UNKNOWN',
                            ':ad_types' => json_encode($unit['adTypes'] ?? []),
                            ':ad_unit_data' => json_encode($unit)
                        ]);
                    } catch (PDOException $e) {
                        error_log('Ad Unit Cache Error: ' . $e->getMessage());
                    }
                }

                $cached_units = $api_response['data']['adUnits'];
            }

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

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

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

            if ($unit) {
                $unit['ad_unit_data'] = json_decode($unit['ad_unit_data'], true);
                $unit['ad_types'] = json_decode($unit['ad_types'], true);

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

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

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

            foreach ($api_response['data']['adUnits'] ?? [] as $unit) {
                try {
                    $app_id = isset($unit['app']) ? ($unit['app']['appId'] ?? $unit['app']['name'] ?? '') : '';

                    $stmt = $db->prepare("
                        INSERT INTO ad_units (ad_unit_id, ad_unit_name, app_id, ad_format, ad_types, ad_unit_data, last_updated)
                        VALUES (:ad_unit_id, :ad_unit_name, :app_id, :ad_format, :ad_types, :ad_unit_data, NOW())
                        ON DUPLICATE KEY UPDATE
                        ad_unit_name = :ad_unit_name,
                        app_id = :app_id,
                        ad_format = :ad_format,
                        ad_types = :ad_types,
                        ad_unit_data = :ad_unit_data,
                        last_updated = NOW()
                    ");

                    $stmt->execute([
                        ':ad_unit_id' => $unit['adUnitId'] ?? $unit['name'] ?? '',
                        ':ad_unit_name' => $unit['displayName'] ?? $unit['name'] ?? '',
                        ':app_id' => $app_id,
                        ':ad_format' => $unit['adFormat'] ?? 'UNKNOWN',
                        ':ad_types' => json_encode($unit['adTypes'] ?? []),
                        ':ad_unit_data' => json_encode($unit)
                    ]);

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

            echo json_encode([
                'success' => true,
                'message' => $synced_count . ' ad units 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 ad units'
            ]);
        }

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

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

?>