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

date_default_timezone_set('Africa/Dar_es_Salaam');
include '../config.php'; // adjust path if needed

$loan_id = isset($_POST['loan_id']) ? intval($_POST['loan_id']) : 0;
$repayment_type = isset($_POST['repayment_type']) ? trim(strtolower($_POST['repayment_type'])) : '';

if ($loan_id <= 0) {
    echo json_encode(["success" => false, "message" => "Invalid loan_id"]);
    exit;
}

// Accept only allowed types (you can expand if needed)
$allowed = ['siku', 'wiki', 'mwezi'];
if ($repayment_type === '') {
    // If not provided, default to 'siku'
    $repayment_type = 'siku';
} elseif (!in_array($repayment_type, $allowed)) {
    // If provided value is unknown, reject
    echo json_encode(["success" => false, "message" => "Invalid repayment_type"]);
    exit;
}

// Update the loans table repayment_type column
$sql = "UPDATE loans SET repayment_type = ? WHERE loan_id = ?";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(["success" => false, "message" => "SQL prepare error: " . $conn->error]);
    exit;
}
$stmt->bind_param("si", $repayment_type, $loan_id);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Repayment type updated successfully"]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to update: " . $stmt->error]);
}

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