<?php
header("Content-Type: application/json");
include '../config.php';

date_default_timezone_set('Africa/Dar_es_Salaam');

if (
    isset($_POST['loan_id']) &&
    isset($_POST['amount']) &&
    isset($_POST['payment_method']) &&
    isset($_POST['branch_id']) &&
    isset($_POST['customer_id'])
) {
    $loan_id = intval($_POST['loan_id']);
    $amount = floatval($_POST['amount']);
    $payment_method = $_POST['payment_method'];
    $branch_id = intval($_POST['branch_id']);
    $customer_id = intval($_POST['customer_id']);

    $payment_date = date("Y-m-d H:i:s");
    $paid_now      = $amount;

    // Angalia kama mteja amefanya malipo leo
    $stmt_check_payments = $conn->prepare("SELECT COUNT(*) FROM loans_collection WHERE customer_id = ? AND loan_id = ? AND DATE(payment_date) = CURDATE()");
    $stmt_check_payments->bind_param("ii", $customer_id, $loan_id);
    $stmt_check_payments->execute();
    $stmt_check_payments->bind_result($payment_count);
    $stmt_check_payments->fetch();
    $stmt_check_payments->close();

    if ($payment_count > 0) {
        echo json_encode(["success" => false, "error" => "Customer has already made a payment today. Try again tomorrow."]);
        exit;
    }

    // Chukua Interest kutoka kwenye Loan (sio Branch)
    $stmt_interest = $conn->prepare("SELECT interest FROM loans WHERE loan_id = ?");
    if (!$stmt_interest) {
        echo json_encode(["success" => false, "error" => "Query preparation failed: " . $conn->error]);
        exit;
    }
    $stmt_interest->bind_param("i", $loan_id);
    if (!$stmt_interest->execute()) {
        echo json_encode(["success" => false, "error" => "Execution failed when fetching interest: " . $stmt_interest->error]);
        exit;
    }
    $stmt_interest->bind_result($interest);
    if (!$stmt_interest->fetch()) {
        // Loan haikuwepo au interest haipo
        echo json_encode(["success" => false, "error" => "Loan not found or interest data missing."]);
        $stmt_interest->close();
        exit;
    }
    $stmt_interest->close();

    // Make sure interest is numeric (default 0 kama NULL)
    $interest = is_null($interest) ? 0.0 : floatval($interest);

    // Chukua Loan Amount
    $stmt_loan = $conn->prepare("SELECT loan_amount FROM loans WHERE loan_id = ?");
    $stmt_loan->bind_param("i", $loan_id);
    $stmt_loan->execute();
    $stmt_loan->bind_result($loan_amount);
    if (!$stmt_loan->fetch()) {
        echo json_encode(["success" => false, "error" => "Loan not found."]);
        exit;
    }
    $stmt_loan->close();

    // Hesabu total due: total_due = loan_amount + (loan_amount * interest)
    $total_due = $loan_amount * (1 + $interest);

    // Ingiza rekodi ya malipo kwenye loans_collection
    $sql = "INSERT INTO loans_collection (customer_id, loan_id, branch_id, amount_paid, payment_method, payment_date) VALUES (?, ?, ?, ?, ?, ?)";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("iiidss", $customer_id, $loan_id, $branch_id, $amount, $payment_method, $payment_date);
        if ($stmt->execute()) {
            $stmt->close();

            // ------------------------------
            // Update ya loans_schedule:
            $stmt_schedules = $conn->prepare("SELECT id, scheduled_amount, paid_amount FROM loans_schedule WHERE loan_id = ? AND status != 'Full Paid' ORDER BY schedule_date ASC");
            $stmt_schedules->bind_param("i", $loan_id);
            $stmt_schedules->execute();
            $result = $stmt_schedules->get_result();

            if ($result->num_rows > 0) {
                while (($row = $result->fetch_assoc()) && $amount > 0) {
                    $schedule_id     = $row['id'];
                    $scheduled_amount= floatval($row['scheduled_amount']);
                    $paid_amount     = floatval($row['paid_amount']);
                    $remaining       = $scheduled_amount - $paid_amount;

                    if ($amount >= $remaining) {
                        $new_paid_amount = $scheduled_amount;
                        $new_status      = "Full Paid";
                        $amount         -= $remaining;
                    } else {
                        $new_paid_amount = $paid_amount + $amount;
                        $new_status      = ($new_paid_amount == $scheduled_amount) ? "Full Paid" : "Partial Paid";
                        $amount          = 0;
                    }

                    $stmt_update = $conn->prepare("UPDATE loans_schedule SET paid_amount = ?, status = ? WHERE id = ?");
                    $stmt_update->bind_param("dsi", $new_paid_amount, $new_status, $schedule_id);
                    $stmt_update->execute();
                    $stmt_update->close();
                }
            } else {
                echo json_encode(["success" => false, "error" => "No active loan schedule found."]);
                exit;
            }
            $stmt_schedules->close();

            // Angalia kama zote zimefanyika (hakuna schedule iliyo pending)
            $stmt_check_pending = $conn->prepare("SELECT COUNT(*) FROM loans_schedule WHERE loan_id = ? AND status != 'Full Paid'");
            $stmt_check_pending->bind_param("i", $loan_id);
            $stmt_check_pending->execute();
            $stmt_check_pending->bind_result($pending_count);
            $stmt_check_pending->fetch();
            $stmt_check_pending->close();

            if ($pending_count == 0) {
                // Malipo yote yamefanyika
                $stmt_update_loan = $conn->prepare("UPDATE loans SET status = 'Paid' WHERE loan_id = ?");
                $stmt_update_loan->bind_param("i", $loan_id);
                $stmt_update_loan->execute();
                $stmt_update_loan->close();
            }

            // === New: Tuma SMS kwa mteja akisema malipo yamepokelewa na saldo iliyobaki ===

            // 1. Chukua simu ya mteja
            $stmt_phone = $conn->prepare("SELECT phone FROM customers WHERE id = ?");
            $stmt_phone->bind_param("i", $customer_id);
            $stmt_phone->execute();
            $stmt_phone->bind_result($phone);
            if (!$stmt_phone->fetch()) {
                // Hata kama hapatikani simu, tuendele
                $phone = null;
            }
            $stmt_phone->close();

            if ($phone) {
                // 2. Hesabu total paid na salio
                $stmt_totals = $conn->prepare("
                    SELECT 
                      SUM(scheduled_amount) AS total_schedule, 
                      SUM(paid_amount) AS total_paid 
                    FROM loans_schedule 
                    WHERE loan_id = ?
                ");
                $stmt_totals->bind_param("i", $loan_id);
                $stmt_totals->execute();
                $stmt_totals->bind_result($total_schedule, $total_paid_so_far);
                $stmt_totals->fetch();
                $stmt_totals->close();

                $remaining_balance = $total_schedule - $total_paid_so_far;

                // 3. Prepare SMS
                // Format number to start with 255
                $formatted_phone = preg_replace('/^(0|255)/', '255', $phone);

                $message = "Tumeipokea malipo yako ya Tsh " 
                         . number_format($paid_now, 0, '.', ',') 
                         . ". Deni lako ni Tsh " 
                         . number_format($remaining_balance, 0, '.', ',') 
                         . ". Asante. kwa maswali zaidi piga 0718340258";

                // Beem Africa credentials
                $api_key    = "106de5fd0d63b2de";
                $secret_key = "NDY1NGE3NjZjYTgzZmE5MTFkOThkODg1MDZjMmE1NTVmOTc2OGJlMzc1MDRmYjNlMDkxODE1MWFiM2JkY2FlNg==";
                $sender_name= "Bexa Mikopo";
                $url        = "https://apisms.beem.africa/v1/send";

                $data = [
                    'source_addr' => $sender_name,
                    'encoding'    => 0,
                    'message'     => $message,
                    'recipients'  => [
                        ['recipient_id' => "1", 'dest_addr' => $formatted_phone]
                    ]
                ];
                $payload = json_encode($data);

                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Content-Type: application/json',
                    'Authorization: Basic ' . base64_encode("$api_key:$secret_key")
                ]);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_TIMEOUT, 30);

                $sms_response = curl_exec($ch);
                $sms_httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                // optionally log $sms_response or $sms_httpcode for troubleshooting
            }

            // === End SMS section ===

            echo json_encode(["success" => true]);
        } else {
            echo json_encode(["success" => false, "error" => "Execution failed: " . $conn->error]);
        }
    } else {
        echo json_encode(["success" => false, "error" => "Query preparation failed: " . $conn->error]);
    }
} else {
    echo json_encode(["success" => false, "error" => "Missing required fields"]);
}

$conn->close();
?>
