<?php
// File: api/get_my_loans.php

// Allow CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Content-Type: application/json');

require_once '../../config.php';

// Get customer_id from GET or POST
$customer_id = isset($_GET['customer_id']) ? intval($_GET['customer_id']) :
               (isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0);

if ($customer_id <= 0) {
    echo json_encode(["success" => false, "message" => "Missing or invalid customer_id"]);
    exit;
}

// SQL to fetch loans directly using interest from loans table
$sql = "
  SELECT
    l.loan_id,
    l.branch_id,
    l.loan_amount,
    l.loan_date,
    l.status,
    l.loan_period,
    l.interest,
    IFNULL(SUM(c.amount_paid), 0) AS paid_amount
  FROM loans l
  LEFT JOIN loans_collection c ON c.loan_id = l.loan_id
  WHERE l.customer_id = ?
  GROUP BY l.loan_id
  ORDER BY l.loan_date DESC
";

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

$stmt->bind_param('i', $customer_id);
$stmt->execute();
$result = $stmt->get_result();

$active = [];
$inactive = [];

while ($row = $result->fetch_assoc()) {
    $principal       = (float)$row['loan_amount'];
    $interest        = (float)$row['interest'];    // sasa inachukuliwa moja kwa moja kutoka loans
    $period          = (int)$row['loan_period'];
    $paid            = (float)$row['paid_amount'];

    // Total due = principal + (principal × interest × period)
    $total_due       = $principal + ($principal * $interest * $period);
    $remaining       = $total_due - $paid;
    if ($remaining < 0) {
        $remaining = 0; // epuka hasi
    }

    $item = [
        "loan_id"           => (int)$row['loan_id'],
        "branch_id"         => (int)$row['branch_id'],
        "loan_amount"       => round($principal, 2),
        "loan_period"       => $period,
        "loan_date"         => $row['loan_date'],
        "status"            => $row['status'],
        "interest"          => $interest,
        "total_due"         => round($total_due, 2),
        "paid_amount"       => round($paid, 2),
        "remaining_amount"  => round($remaining, 2),
    ];

    if (is_null($row['status'])) {
        $active[] = $item;
    } elseif (strtolower($row['status']) === 'paid') {
        $inactive[] = $item;
    } else {
        $active[] = $item;
    }
}

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

echo json_encode([
    "success"           => true,
    "active_loans"      => $active,
    "non_active_loans"  => $inactive
]);
?>
