<?php
header("X-Robots-Tag: noindex, nofollow", true);

// Include the database connection
include("include/connection.php");

$conn = new mysqli($host, $user, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$message = "";  // Variable to store the success or error message

// Get form data
$memberNo = $_POST['memberNo'];
$amountPaid = $_POST['amountPaid'];
$officerID = $_POST['officerID'];
$loanNo = $_POST['loanNo'];

// Generate a unique receipt number (e.g., based on timestamp and random number)
$receiptNo = 'RPT-' . time() . '-' . rand(1000, 9999);

// Begin transaction to update loan table and insert into collection table
$conn->begin_transaction();

try {
    // Insert the collection record into the collection table
    $insertSql = "
        INSERT INTO collection (memberNo, amountPaid, paidDate, officerID, loanNo, receiptNo) 
        VALUES (?, ?, NOW(), ?, ?, ?)";
    $stmt = $conn->prepare($insertSql);
    $stmt->bind_param("iiiis", $memberNo, $amountPaid, $officerID, $loanNo, $receiptNo);
    $stmt->execute();
    
    // Update the loan table, reducing the loan amount
    $updateSql = "UPDATE loan SET LoanBalance = LoanBalance - ? WHERE loanNo = ?";
    $stmt = $conn->prepare($updateSql);
    $stmt->bind_param("ii", $amountPaid, $loanNo);
    $stmt->execute();

    // Fetch the updated loan balance after the payment
    $loanQuery = "SELECT LoanBalance, endDate FROM loan WHERE loanNo = ?";
    $stmt = $conn->prepare($loanQuery);
    $stmt->bind_param("i", $loanNo);
    $stmt->execute();
    $result = $stmt->get_result();
    $loan = $result->fetch_assoc();
    $remainingBalance = $loan['LoanBalance'];
	$endDate = date("d-m-Y", strtotime($loan['endDate'])); //Formate end date
	
	
	// Insert into logs table
    $logSql = "
        INSERT INTO logs (memberNo, amount_Paid, LoanBalance, paidDate, receiptNo) 
        VALUES (?, ?, ?, NOW(), ?)";
    $stmt = $conn->prepare($logSql);
    $stmt->bind_param("iiis", $memberNo, $amountPaid, $remainingBalance, $receiptNo);
    $stmt->execute();

    // Commit the transaction
    $conn->commit();

    // Now send SMS to the member to confirm the payment with receipt number and loan balance
    $memberQuery = "SELECT memberPhoneNo, memberName FROM member WHERE memberNo = ?";
    $stmt = $conn->prepare($memberQuery);
    $stmt->bind_param("i", $memberNo);
    $stmt->execute();
    $result = $stmt->get_result();
    $member = $result->fetch_assoc();

    // Beem API credentials
    $api_key = '8c4d89acc5393807';
    $secret_key = 'MzU4MmUyYjBmZDFmYTIxODc2ODBjYTAxMWRjOWRjOThiMjRmNjllYmMwMmQ4Yjc4YmM2MDAxZjg5YWY5MzdlYg==';
    
    // Format the amountPaid and remainingBalance as currency with commas
    $formattedAmountPaid = number_format($amountPaid, 2);  // e.g., 1,234.00
    $formattedRemainingBalance = number_format($remainingBalance, 2);  // e.g., 5,678.00

    // Prepare SMS message
    $message = ' ' . $member['memberName'] . 
			   ', Tumepokea Tsh ' . $formattedAmountPaid . 
			   '. Risiti: ' . $receiptNo . 
			   '. Baki yako ya mkopo ni Tsh ' . $formattedRemainingBalance .
			   '. Tarehe ya mwisho kulipa mkopo ni ' . $endDate .
			   '. .';

    $postData = array(
        'source_addr' => 'MKOMBOZI MF',
        'encoding' => 0,
        'schedule_time' => '',
        'message' => $message,
        'recipients' => [array('recipient_id' => '1', 'dest_addr' => '255' . $member['memberPhoneNo'])]
    );

    $Url = 'https://apisms.beem.africa/v1/send';

    // Initialize cURL
    $ch = curl_init($Url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt_array($ch, array(
        CURLOPT_POST => TRUE,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_HTTPHEADER => array(
            'Authorization:Basic ' . base64_encode("$api_key:$secret_key"),
            'Content-Type: application/json'
        ),
        CURLOPT_POSTFIELDS => json_encode($postData)
    ));

    // Execute the request
    $response = curl_exec($ch);

    // Check for errors
    if ($response === FALSE) {
        echo $response;
        die(curl_error($ch));
    }

    curl_close($ch);

    // Success message
    $message = "Collection successfully recorded with receipt number: $receiptNo, and SMS has been sent.";
	
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    $message = "Error: " . $e->getMessage();
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Collection Process</title>
    <!-- Bootstrap CSS for responsive design -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container mt-5">
    <!-- Display success or error message -->
    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- Button to redirect to the main page -->
    <a href="home.php" class="btn btn-secondary mt-3">Go to Main Page</a>
</div>

<!-- Bootstrap JS for responsiveness and alerts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>
