<?php
// File: api.php
header('Content-Type: application/json');

ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once 'includes/db_connect.php';
require_once 'includes/functions.php';
require_once 'includes/security.php';

$action = preg_replace('/[^a-z_]/', '', $_GET['action'] ?? '');

// ----------------------------------------------------------------
// TRACK LEAD — dengan rate limiting (30 req/menit per IP)
// ----------------------------------------------------------------
if ($action === 'track_lead') {
    if (!checkRateLimit('track_lead', 30, 60)) {
        http_response_code(429);
        echo json_encode(['status' => 'rate_limited']);
        exit;
    }
    $source = sanitizeInput($_POST['source'] ?? 'Unknown', 50);
    $detail = sanitizeInput($_POST['detail'] ?? 'General', 100);
    try {
        $pdo->prepare("INSERT INTO leads_log (source, detail) VALUES (?, ?)")->execute([$source, $detail]);
        echo json_encode(['status' => 'success']);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error']);
    }
    exit;
}

// ----------------------------------------------------------------
// GET PRODUCTS — dengan cache
// ----------------------------------------------------------------
if ($action === 'get_products') {
    require_once 'includes/cache.php';
    $data = cacheRemember('api_products', fn() => getAllProducts($pdo), 300);
    echo json_encode($data);
    exit;
}

// ----------------------------------------------------------------
// CALCULATE CREDIT
// ----------------------------------------------------------------
if ($action === 'calculate_credit') {
    $price      = floatval($_POST['price']  ?? 0);
    $dp_percent = floatval($_POST['dp']     ?? 20);
    $tenor      = intval($_POST['tenor']    ?? 1);

    if ($price <= 0 || $dp_percent < 20 || $dp_percent > 80 || $tenor < 1 || $tenor > 8) {
        echo json_encode(['status' => 'invalid_input']);
        exit;
    }

    $creditData  = getCreditData($pdo);
    $umum        = $creditData['umum'];
    $tenorData   = null;
    foreach ($creditData['tenors'] as $t) {
        if ($t['tenor_tahun'] == $tenor) { $tenorData = $t; break; }
    }
    $bungaFlat  = $tenorData ? floatval($tenorData['bunga_per_tahun']) : 0.08;
    $rateACP    = $tenorData ? floatval($tenorData['rate_acp'])        : 0;
    $biayaAdmin = $tenorData ? floatval($tenorData['biaya_admin'])     : 2500000;

    $rateAsuransi = 0.025;
    foreach ($creditData['insurance'] as $ins) {
        if ($price >= $ins['min_price'] && $price <= $ins['max_price']) {
            $col = 'tenor_' . $tenor;
            if (isset($ins[$col])) $rateAsuransi = floatval($ins[$col]) / 100;
            break;
        }
    }
    $rateProvisi  = floatval($umum['rate_provisi']);
    $biayaFiducia = floatval($umum['biaya_fiducia']);

    $dp_murni    = $price * ($dp_percent / 100);
    $baseHutang  = $price - $dp_murni;
    $biayaAsuransi = $price * $rateAsuransi;
    $pokokBunga  = $baseHutang + $biayaAsuransi;
    $total_bunga = $pokokBunga * $bungaFlat * $tenor;
    $biayaACP    = $baseHutang * $rateACP * $tenor;
    $biayaProvisi = $baseHutang * $rateProvisi;
    $total_hutang = $pokokBunga + $total_bunga + $biayaACP + $biayaProvisi;
    $angsuran    = $total_hutang / ($tenor * 12);
    $total_dp    = $dp_murni + $biayaAdmin + $biayaFiducia;

    echo json_encode([
        'total_dp'  => ceil($total_dp  / 1000) * 1000,
        'angsuran'  => ceil($angsuran  / 1000) * 1000,
    ]);
    exit;
}

http_response_code(404);
echo json_encode(['status' => 'unknown_action']);
