<?php
/**
 * Calculate Loan Breakdown
 * Performs loan calculations based on user input
 * This is an optional AJAX endpoint if you want server-side calculations
 */

header('Content-Type: application/json');
require_once('class.php');

try {
    // Get POST data
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }
    
    $loanTypeId = isset($_POST['loan_type_id']) ? intval($_POST['loan_type_id']) : 0;
    $loanAmount = isset($_POST['loan_amount']) ? floatval($_POST['loan_amount']) : 0;
    $loanTerm = isset($_POST['loan_term']) ? intval($_POST['loan_term']) : 0;
    
    // Validate inputs
    if ($loanTypeId <= 0) {
        throw new Exception('Invalid loan type');
    }
    if ($loanAmount < 1000) {
        throw new Exception('Loan amount must be at least MWK 1,000');
    }
    if ($loanTerm < 1 || $loanTerm > 60) {
        throw new Exception('Loan term must be between 1 and 60 months');
    }
    
    // Initialize database connection
    $con = new DB;
    
    // Fetch loan type details
    $conditions = array(
        'where' => array('id' => $loanTypeId),
        'return_type' => 'single'
    );
    
    $loanType = $con->getRows('loan_types', $conditions);
    
    if (!$loanType) {
        throw new Exception('Loan type not found');
    }
    
    // Extract rates
    $interestRate = floatval($loanType['interest_rate_monthly']);
    $processingFee = floatval($loanType['processing_fee']);
    $insuranceRate = floatval($loanType['insurance_fee_yearly']);
    
    // Calculations
    $processingFeeAmount = ($loanAmount * $processingFee) / 100;
    $actualDisbursement = $loanAmount - $processingFeeAmount;
    
    $monthlyPrincipal = $actualDisbursement / $loanTerm;
    $monthlyInterest = ($actualDisbursement * $interestRate) / 100;
    $monthlyInsurance = ($loanAmount * $insuranceRate) / 100 / 12;
    $monthlyPayment = $monthlyPrincipal + $monthlyInterest + $monthlyInsurance;
    
    $totalInterest = $monthlyInterest * $loanTerm;
    $totalInsurance = $monthlyInsurance * $loanTerm;
    $totalRepayment = $actualDisbursement + $totalInterest + $totalInsurance;
    $totalCost = $totalInterest + $totalInsurance;
    
    // Return results
    echo json_encode([
        'success' => true,
        'data' => [
            'requestedAmount' => round($loanAmount, 2),
            'processingFeeAmount' => round($processingFeeAmount, 2),
            'actualDisbursement' => round($actualDisbursement, 2),
            'loanTerm' => $loanTerm,
            'interestRate' => round($interestRate, 2),
            'monthlyPrincipal' => round($monthlyPrincipal, 2),
            'monthlyInterest' => round($monthlyInterest, 2),
            'monthlyInsurance' => round($monthlyInsurance, 2),
            'monthlyPayment' => round($monthlyPayment, 2),
            'totalPrincipal' => round($actualDisbursement, 2),
            'totalInterest' => round($totalInterest, 2),
            'totalInsurance' => round($totalInsurance, 2),
            'totalRepayment' => round($totalRepayment, 2),
            'totalCost' => round($totalCost, 2)
        ]
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
