<?php
require_once 'db/config.php';

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

$profile_id = $_GET['id'] ?? null;

if (!$profile_id) {
    echo json_encode(['error' => 'Profile ID is missing.']);
    exit;
}

// Basic AI/Rule-based KPI generation
function generate_kpi_data($profile) {
    // Default values
    $base_mrr = 5000;
    $base_cac = 400;
    $base_nrr = 95;

    // Adjust KPIs based on profile data
    if (isset($profile['organization_size'])) {
        switch ($profile['organization_size']) {
            case '1-10':
                $base_mrr = 5000;
                break;
            case '11-50':
                $base_mrr = 25000;
                break;
            case '51-200':
                $base_mrr = 75000;
                break;
            case '201+':
                $base_mrr = 200000;
                break;
        }
    }

    if (isset($profile['market_approach'])) {
        if ($profile['market_approach'] === 'Product-led') {
            $base_nrr = 110;
            $base_cac = 200;
        } elseif ($profile['market_approach'] === 'Sales-led') {
            $base_nrr = 98;
            $base_cac = 800;
        }
    }
    
    $current_mrr = $base_mrr * (rand(80, 120) / 100);
    $target_mrr = $base_mrr * 2;

    $current_cac = $base_cac * (rand(90, 130) / 100);
    $target_cac = $base_cac * 0.8;

    $current_nrr = $base_nrr * (rand(95, 105) / 100);
    $target_nrr = $base_nrr * 1.1;

    $kpis = [
        ['name' => 'Monthly Recurring Revenue (MRR)', 'current' => number_format($current_mrr), 'target' => number_format($target_mrr)],
        ['name' => 'Customer Acquisition Cost (CAC)', 'current' => number_format($current_cac), 'target' => number_format($target_cac)],
        ['name' => 'Net Revenue Retention (NRR)', 'current' => round($current_nrr) . '%', 'target' => round($target_nrr) . '%']
    ];

    // Generate sample data for the chart
    $labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
    
    $mrr_growth_rate = ($target_mrr - $current_mrr) / 5;

    $datasets = [
        [
            'label' => 'MRR (Actual)',
            'data' => array_map(fn($i) => $current_mrr + ($mrr_growth_rate * $i * (rand(80,120)/100)), range(0, 5)),
            'borderColor' => '#0d6efd',
            'tension' => 0.2
        ],
        [
            'label' => 'MRR (Target)',
            'data' => array_map(fn($i) => $current_mrr + ($mrr_growth_rate * $i), range(0, 5)),
            'borderColor' => '#dc3545',
            'borderDash' => [5, 5],
            'tension' => 0.2
        ]
    ];

    return [
        'kpis' => $kpis,
        'chartData' => [
            'labels' => $labels,
            'datasets' => $datasets
        ]
    ];
}

try {
    $pdo = db();
    $stmt = $pdo->prepare("SELECT * FROM gtm_profiles WHERE id = ?");
    $stmt->execute([$profile_id]);
    $profile = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$profile) {
        echo json_encode(['error' => 'Profile not found.']);
        exit;
    }

    $kpi_data = generate_kpi_data($profile);
    $kpi_data_json = json_encode($kpi_data);

    // Save the generated data to the database
    $update_stmt = $pdo->prepare("UPDATE gtm_profiles SET kpi_data = ? WHERE id = ?");
    $update_stmt->execute([$kpi_data_json, $profile_id]);

    echo json_encode(['success' => true, 'kpi_data' => $kpi_data]);

} catch (PDOException $e) {
    error_log('KPI Generation Error: ' . $e->getMessage());
    echo json_encode(['error' => 'Database error during KPI generation.']);
}