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

$action = $_GET['action'] ?? '';

if ($action == 'get_products') {
    echo json_encode(getAllProducts($pdo));
    exit;
}

if ($action == 'track_lead') {
    $source = $_POST['source'] ?? 'Unknown'; $detail = $_POST['detail'] ?? 'General';
    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;
}

if ($action == 'calculate_credit') {
    $price = floatval($_POST['price']);
    $dp_percent = floatval($_POST['dp']);
    $tenor = intval($_POST['tenor']); 
    
    // Fetch Data
    $creditData = getCreditData($pdo);
    $umum = $creditData['umum'];
    
    // 1. Cari Rate Tenor (Bunga & ACP & Admin)
    $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;
    
    // 2. Cari Rate Asuransi (Berdasarkan Tier Harga & Tenor)
    $rateAsuransi = 0.025; // Default fallback
    foreach ($creditData['insurance'] as $ins) {
        if ($price >= $ins['min_price'] && $price <= $ins['max_price']) {
            // Ambil kolom 'tenor_X' (misal tenor_3)
            $colName = 'tenor_' . $tenor; 
            if (isset($ins[$colName])) {
                $rateAsuransi = floatval($ins[$colName]) / 100; // Database simpan persen (2.47), jadi bagi 100
            }
            break;
        }
    }

    $rateProvisi = floatval($umum['rate_provisi']); // Desimal (0.01)
    $biayaFiducia = floatval($umum['biaya_fiducia']);

    // --- RUMUS LOGIC BARU ---
    
    // A. DP Murni
    if ($dp_percent < 20) $dp_percent = 20;
    $dp_murni = $price * ($dp_percent / 100);
    
    // B. Base Hutang
    $baseHutang = $price - $dp_murni;

    // C. Komponen Kapitalisasi
    $biayaAsuransi = $price * $rateAsuransi; // Asuransi dari OTR
    
    // D. Pokok Bunga (Hutang Awal + Asuransi)
    $pokokBunga = $baseHutang + $biayaAsuransi;

    // E. Total Bunga
    $total_bunga = $pokokBunga * $bungaFlat * $tenor;
    
    // F. Komponen Lain
    $biayaACP = $baseHutang * $rateACP * $tenor; // ACP dari Base * Tenor
    $biayaProvisi = $baseHutang * $rateProvisi; // Provisi dari Base

    // G. Total Hutang (Plafon Kredit Akhir)
    $total_hutang = $pokokBunga + $total_bunga + $biayaACP + $biayaProvisi;
    
    // H. Angsuran
    $angsuran = $total_hutang / ($tenor * 12);
    
    // I. TDP (Hanya DP + Admin + Fiducia)
    $total_dp = $dp_murni + $biayaAdmin + $biayaFiducia;

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