<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

date_default_timezone_set('Africa/Dar_es_Salaam');
include '../config.php';

// Pokea data kutoka POST
$customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;
$loan_amount = isset($_POST['loan_amount']) ? floatval($_POST['loan_amount']) : 0;
$interest = isset($_POST['interest']) ? floatval($_POST['interest']) : 0; // NEW: interest from UI
$collateral1 = $_POST['collateral1'] ?? '';
$collateral2 = $_POST['collateral2'] ?? '';
$collateral3 = $_POST['collateral3'] ?? '';
$guarantor_firstname = $_POST['guarantor_firstname'] ?? '';
$guarantor_lastname = $_POST['guarantor_lastname'] ?? '';
$guarantor_phone = $_POST['guarantor_phone'] ?? '';
$guarantor_collateral1 = $_POST['guarantor_collateral1'] ?? '';
$guarantor_collateral2 = $_POST['guarantor_collateral2'] ?? '';
$guarantor_collateral3 = $_POST['guarantor_collateral3'] ?? '';
$loan_period = $_POST['loan_period'] ?? ''; // in months
$loan_purpose = $_POST['loan_purpose'] ?? '';
$payment_method = $_POST['payment_method'] ?? '';
$repayment_type = isset($_POST['repayment_type']) ? strtolower(trim($_POST['repayment_type'])) : 'siku';
$user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
$branch_id = isset($_POST['branch_id']) ? intval($_POST['branch_id']) : 0;
$loan_date = $_POST['loan_date'] ?? date('Y-m-d H:i:s');
$status = (isset($_POST['status']) && $_POST['status'] !== '') ? $_POST['status'] : null;

// Required fields check
if ($customer_id == 0 || $loan_amount == 0 || $user_id == 0 || $branch_id == 0) {
    echo json_encode(["success" => false, "message" => "Missing required fields"]);
    exit;
}

// Normalize repayment_type to expected values
$allowed = ['siku', 'wiki', 'mwezi'];
if (!in_array($repayment_type, $allowed)) {
    $repayment_type = 'siku';
}

// Process guarantor image
$guarantor_image_path = NULL;
if (isset($_FILES['guarantor_image']) && $_FILES['guarantor_image']['error'] == 0) {
    $target_dir = "../uploads/guarantors/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    $file_ext = pathinfo($_FILES['guarantor_image']['name'], PATHINFO_EXTENSION);
    $file_name = "guarantor_" . time() . "." . $file_ext;
    $target_file = $target_dir . $file_name;

    if (move_uploaded_file($_FILES['guarantor_image']['tmp_name'], $target_file)) {
        $guarantor_image_path = "../uploads/guarantors/" . $file_name;
    } else {
        echo json_encode(["success" => false, "message" => "Failed to upload guarantor image"]);
        exit;
    }
}

// Prepare insert into loans including interest
$sql = "INSERT INTO loans 
    (customer_id, branch_id, loan_amount, interest, collateral1, collateral2, collateral3, 
     guarantor_firstname, guarantor_lastname, guarantor_phone, 
     guarantor_collateral1, guarantor_collateral2, guarantor_collateral3, 
     loan_period, loan_purpose, payment_method, repayment_type, user_id, guarantor_image, loan_date, status) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(["success" => false, "message" => "SQL error: " . $conn->error]);
    exit;
}

// Build types string safely: i i d d (then 13 s's) then i s s s  => keep as before
$types = "iidd" . str_repeat("s", 13) . "isss";

$stmt->bind_param($types, 
    $customer_id,
    $branch_id,
    $loan_amount,
    $interest,
    $collateral1,
    $collateral2,
    $collateral3,
    $guarantor_firstname,
    $guarantor_lastname,
    $guarantor_phone,
    $guarantor_collateral1,
    $guarantor_collateral2,
    $guarantor_collateral3,
    $loan_period,
    $loan_purpose,
    $payment_method,
    $repayment_type,
    $user_id,
    $guarantor_image_path,
    $loan_date,
    $status
);

if ($stmt->execute()) {
    $loan_id = $conn->insert_id;

    // USE provided $interest (from POST) instead of fetching from branches
    // Ensure interest is numeric and reasonable
    $interest = floatval($interest);
    if ($interest < 0) $interest = 0;

    // Compute total due using provided interest:
    // total_due = loan_amount * (1 + (interest * loan_period))
    $period_months = max(1, intval($loan_period));
    $total_due = $loan_amount * (1 + ($interest * $period_months));

    // Convert loan_period (months) to days (30 days per month) — keep old behaviour for day calculations
    $total_days = $period_months * 30;
    if ($total_days <= 0) $total_days = 30;

    // Decide schedule frequency based on repayment_type
    if ($repayment_type === 'siku') {
        // daily schedule: one entry per day
        $periods = $total_days;
        $modify_interval = '+1 day';
    } elseif ($repayment_type === 'wiki') {
        // weekly schedule: one entry every 7 days until loan ends
        $periods = (int) ceil($total_days / 7.0);
        if ($periods < 1) $periods = 1;
        $modify_interval = '+7 day';
    } else { // 'mwezi'
        // monthly schedule: one entry per month (based on loan_period)
        $periods = $period_months;
        if ($periods < 1) $periods = 1;
        $modify_interval = '+1 month';
    }

    // scheduled amount per period
    $scheduled_amount = $total_due / $periods;

    // Create schedule records
    $loanDateObj = new DateTime($loan_date);
    for ($i = 0; $i < $periods; $i++) {
        $schedule_date = $loanDateObj->format('Y-m-d');

        $sqlSchedule = "INSERT INTO loans_schedule (loan_id, customer_id, branch_id, scheduled_amount, schedule_date) VALUES (?, ?, ?, ?, ?)";
        $stmtSchedule = $conn->prepare($sqlSchedule);
        if ($stmtSchedule) {
            $stmtSchedule->bind_param("iiids", $loan_id, $customer_id, $branch_id, $scheduled_amount, $schedule_date);
            $stmtSchedule->execute();
            $stmtSchedule->close();
        }
        $loanDateObj->modify($modify_interval);
    }

    echo json_encode([
        "success" => true,
        "message" => "Loan provided and schedule created successfully",
        "loan_id" => $loan_id,
        "repayment_type" => $repayment_type,
        "periods" => $periods
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Error: " . $stmt->error]);
}

$stmt->close();
$conn->close();
?>
