<?php
session_start();
require_once '../FinancialAnalytics.php';
include '../layouts/dbconn.php';

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

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

$analytics = new FinancialAnalytics($conn);
$corporate_id = $_GET['corp_id'] ?? null;
$metric = $_GET['metric'] ?? null;

if (!$corporate_id || !$metric) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing parameters']);
    exit;
}

try {
    switch ($metric) {
        case 'premium':
            $data = $analytics->analyzePremiumPerformance($corporate_id);
            break;
        case 'loss_ratio':
            $data = $analytics->calculateLossRatio($corporate_id);
            break;
        case 'forecast':
            $data = $analytics->forecastRevenue($corporate_id);
            break;
        case 'risk':
            $data = $analytics->assessUnderwritingRisk($corporate_id);
            break;
        default:
            throw new Exception('Invalid metric');
    }
    
    echo json_encode([
        'success' => true,
        'data' => $data
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => $e->getMessage()
    ]);
}
?>