<?php
// api/reports.php - API Endpoint for Report Generation

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

session_start();

// Check authentication
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'] ?? '';

// Ensure valid token
$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);

// Get account ID (publisher ID)
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 === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    if ($action === 'network') {
        // Generate network report
        $start_date = $input['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
        $end_date = $input['end_date'] ?? date('Y-m-d');
        $dimensions = $input['dimensions'] ?? ['DATE'];
        $metrics = $input['metrics'] ?? ['IMPRESSIONS', 'CLICKS', 'ESTIMATED_EARNINGS'];

        $response = $admob->generateNetworkReport($account_id, $start_date, $end_date, $dimensions, $metrics);

        if ($response['http_code'] === 200) {
            // Cache the report
            try {
                $stmt = $db->prepare("
                    INSERT INTO cached_reports (report_name, report_data, generated_at, cache_expiry)
                    VALUES (:name, :data, NOW(), DATE_ADD(NOW(), INTERVAL 1 HOUR))
                ");

                $stmt->execute([
                    ':name' => 'Network Report - ' . $start_date . ' to ' . $end_date,
                    ':data' => json_encode($response['data'])
                ]);
            } catch (PDOException $e) {
                error_log('Report Cache Error: ' . $e->getMessage());
            }

            echo json_encode([
                'success' => true,
                'data' => $response['data']
            ]);
        } else {
            http_response_code($response['http_code']);
            echo json_encode([
                'success' => false,
                'error' => $response['data']['error']['message'] ?? 'Failed to generate report'
            ]);
        }

    } elseif ($action === 'mediation') {
        // Generate mediation report
        $start_date = $input['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
        $end_date = $input['end_date'] ?? date('Y-m-d');
        $dimensions = $input['dimensions'] ?? ['DATE', 'AD_SOURCE'];
        $metrics = $input['metrics'] ?? ['IMPRESSIONS', 'CLICKS', 'ESTIMATED_EARNINGS'];

        $response = $admob->generateMediationReport($account_id, $start_date, $end_date, $dimensions, $metrics);

        if ($response['http_code'] === 200) {
            echo json_encode([
                'success' => true,
                'data' => $response['data']
            ]);
        } else {
            http_response_code($response['http_code']);
            echo json_encode([
                'success' => false,
                'error' => $response['data']['error']['message'] ?? 'Failed to generate report'
            ]);
        }

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

} elseif ($method === 'GET') {
    if ($action === 'cached') {
        // Get cached reports
        try {
            $stmt = $db->prepare("
                SELECT * FROM cached_reports
                WHERE cache_expiry > NOW()
                ORDER BY generated_at DESC
                LIMIT 10
            ");
            $stmt->execute();
            $reports = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach ($reports as &$report) {
                $report['report_data'] = json_decode($report['report_data'], true);
            }

            echo json_encode([
                'success' => true,
                'data' => $reports
            ]);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Database error']);
        }
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

?>