<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$installment_id = $_GET['installment_id'] ?? '';

if (empty($installment_id)) {
    header('Location: my_installments.php');
    exit();
}

// Get installment details
$sql = "SELECT si.*, s.id as sale_id, s.buyer_id,
               u.unit_number, p.name as property_name
        FROM sale_installments si
        JOIN unit_sales s ON si.sale_id = s.id
        JOIN units u ON s.unit_id = u.id
        JOIN properties p ON u.property_id = p.id
        WHERE si.id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $installment_id);
$stmt->execute();
$result = $stmt->get_result();
$installment = $result->fetch_assoc();

if (!$installment) {
    header('Location: my_installments.php');
    exit();
}

// Check if user is the buyer
if ($installment['buyer_id'] != $_SESSION['user_id']) {
    header('Location: my_installments.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $payment_method = $_POST['payment_method'] ?? '';
    $mpesa_code = $_POST['mpesa_code'] ?? '';
    $reference_number = $_POST['reference_number'] ?? '';
    $phone_number = $_POST['phone_number'] ?? '';
    
    if (empty($payment_method)) {
        $error_message = "Please select payment method";
    } else {
        // Generate transaction reference
        $transaction_ref = 'INST-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -8));
        
        if ($payment_method == 'M-Pesa' && !empty($mpesa_code)) {
            $transaction_ref = $mpesa_code;
        } elseif ($payment_method == 'Bank Transfer' && !empty($reference_number)) {
            $transaction_ref = $reference_number;
        }
        
        // Record payment
        $sql_payment = "INSERT INTO payments (sale_id, installment_id, payer_id, amount, payment_method, 
                                             transaction_reference, transaction_date, status, created_at) 
                       VALUES (?, ?, ?, ?, ?, ?, NOW(), 'completed', NOW())";
        $stmt_payment = $conn->prepare($sql_payment);
        $stmt_payment->bind_param("iiidss", $installment['sale_id'], $installment_id, 
                                 $_SESSION['user_id'], $installment['amount'], 
                                 $payment_method, $transaction_ref);
        
        if ($stmt_payment->execute()) {
            // Update installment status
            $sql_update = "UPDATE sale_installments SET status = 'paid', paid_date = NOW() WHERE id = ?";
            $stmt_update = $conn->prepare($sql_update);
            $stmt_update->bind_param("i", $installment_id);
            $stmt_update->execute();
            
            $_SESSION['success_message'] = "Payment recorded successfully! Reference: " . $transaction_ref;
            header('Location: my_installments.php');
            exit();
        } else {
            $error_message = "Error recording payment: " . $conn->error;
        }
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pay Installment')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Payments', 'title' => 'Pay Installment')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="my_installments.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Installments
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Pay Installment</h4>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-info mb-3">
                                        <p><strong>Property:</strong> <?php echo htmlspecialchars($installment['property_name']); ?></p>
                                        <p><strong>Unit:</strong> <?php echo htmlspecialchars($installment['unit_number']); ?></p>
                                        <p><strong>Milestone:</strong> <?php echo htmlspecialchars($installment['milestone_name'] ?? 'Installment'); ?></p>
                                        <p><strong>Amount:</strong> <span class="fw-bold">KES <?php echo number_format($installment['amount'], 2); ?></span></p>
                                        <p><strong>Due Date:</strong> <?php echo date('M d, Y', strtotime($installment['due_date'])); ?></p>
                                    </div>

                                    <?php if (isset($error_message)): ?>
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                            <?php echo htmlspecialchars($error_message); ?>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                        </div>
                                    <?php endif; ?>

                                    <form id="paymentForm" method="POST">
                                        <input type="hidden" name="installment_id" value="<?php echo $installment_id; ?>">
                                        <input type="hidden" name="amount" value="<?php echo $installment['amount']; ?>">
                                        <div class="mb-3">
                                            <label class="form-label">Payment Method <span class="text-danger">*</span></label>
                                            <select class="form-select" name="payment_method" id="paymentMethod" required>
                                                <option value="">Select method...</option>
                                                <option value="M-Pesa">M-Pesa</option>
                                                <option value="Bank Transfer">Bank Transfer</option>
                                                <option value="Cash">Cash</option>
                                            </select>
                                        </div>
                                        <div class="mb-3" id="mpesaFields" style="display: none;">
                                            <label class="form-label">Phone Number <span class="text-danger">*</span></label>
                                            <input type="tel" class="form-control" name="phone_number" id="mpesaPhone" 
                                                   placeholder="254XXXXXXXXX or 0XXXXXXXXX" required>
                                            <small class="text-muted">You will receive an M-Pesa prompt on this number</small>
                                            <div id="mpesaStatus" class="mt-2" style="display: none;"></div>
                                        </div>
                                        <div class="mb-3" id="bankFields" style="display: none;">
                                            <label class="form-label">Reference Number <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" name="reference_number">
                                        </div>
                                        <div class="mt-4">
                                            <button type="button" id="submitPaymentBtn" class="btn btn-primary" onclick="processPayment()">
                                                <span id="submitBtnText">
                                                    <i class="ri-money-dollar-circle-line align-bottom me-1"></i>Submit Payment
                                                </span>
                                                <span id="submitBtnSpinner" class="spinner-border spinner-border-sm ms-2" style="display: none;"></span>
                                            </button>
                                            <a href="my_installments.php" class="btn btn-light ms-2">
                                                <i class="ri-close-line align-bottom me-1"></i>Cancel
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        let checkoutRequestId = null;
        let statusCheckInterval = null;
        
        document.getElementById('paymentMethod').addEventListener('change', function() {
            document.getElementById('mpesaFields').style.display = this.value === 'M-Pesa' ? 'block' : 'none';
            document.getElementById('bankFields').style.display = this.value === 'Bank Transfer' ? 'block' : 'none';
            document.getElementById('mpesaStatus').style.display = 'none';
        });
        
        function processPayment() {
            const form = document.getElementById('paymentForm');
            const formData = new FormData(form);
            const paymentMethod = formData.get('payment_method');
            
            if (paymentMethod === 'M-Pesa') {
                initiateMpesaSTK(formData);
            } else {
                form.submit();
            }
        }
        
        function initiateMpesaSTK(formData) {
            const submitBtn = document.getElementById('submitPaymentBtn');
            const submitBtnText = document.getElementById('submitBtnText');
            const submitBtnSpinner = document.getElementById('submitBtnSpinner');
            const statusDiv = document.getElementById('mpesaStatus');
            
            submitBtn.disabled = true;
            submitBtnText.innerHTML = '<i class="ri-loader-4-line me-1"></i>Sending request...';
            submitBtnSpinner.style.display = 'inline-block';
            statusDiv.style.display = 'none';
            
            const data = {
                phone: formData.get('phone_number'),
                amount: formData.get('amount'),
                invoice_id: null,
                lease_id: null,
                installment_id: formData.get('installment_id')
            };
            
            fetch('api/mpesa_stk_push_payment.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    checkoutRequestId = result.checkout_request_id;
                    statusDiv.innerHTML = '<div class="alert alert-info"><i class="ri-phone-line me-2"></i>' + result.message + '</div>';
                    statusDiv.style.display = 'block';
                    startStatusCheck(result.transaction_id);
                } else {
                    statusDiv.innerHTML = '<div class="alert alert-danger">' + result.message + '</div>';
                    statusDiv.style.display = 'block';
                    submitBtn.disabled = false;
                    submitBtnText.innerHTML = '<i class="ri-money-dollar-circle-line me-1"></i>Submit Payment';
                    submitBtnSpinner.style.display = 'none';
                }
            })
            .catch(error => {
                statusDiv.innerHTML = '<div class="alert alert-danger">Error: ' + error.message + '</div>';
                statusDiv.style.display = 'block';
                submitBtn.disabled = false;
                submitBtnText.innerHTML = '<i class="ri-money-dollar-circle-line me-1"></i>Submit Payment';
                submitBtnSpinner.style.display = 'none';
            });
        }
        
        function startStatusCheck(transactionId) {
            let attempts = 0;
            const maxAttempts = 30;
            
            statusCheckInterval = setInterval(() => {
                attempts++;
                
                fetch('api/check_mpesa_payment_status.php?transaction_id=' + transactionId)
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            if (result.status === 'COMPLETED') {
                                clearInterval(statusCheckInterval);
                                document.getElementById('mpesaStatus').innerHTML = 
                                    '<div class="alert alert-success"><i class="ri-checkbox-circle-line me-2"></i>' + 
                                    result.message + '<br><small>Receipt: ' + result.mpesa_receipt + '</small></div>';
                                setTimeout(() => {
                                    window.location.href = 'my_installments.php';
                                }, 2000);
                            } else if (result.status === 'FAILED') {
                                clearInterval(statusCheckInterval);
                                document.getElementById('mpesaStatus').innerHTML = 
                                    '<div class="alert alert-danger">' + result.message + '</div>';
                                document.getElementById('submitPaymentBtn').disabled = false;
                                document.getElementById('submitBtnText').innerHTML = '<i class="ri-money-dollar-circle-line me-1"></i>Try Again';
                                document.getElementById('submitBtnSpinner').style.display = 'none';
                            }
                        }
                    });
                
                if (attempts >= maxAttempts) {
                    clearInterval(statusCheckInterval);
                    document.getElementById('mpesaStatus').innerHTML = 
                        '<div class="alert alert-warning">Payment status check timed out. Please check your M-Pesa or payment history.</div>';
                    document.getElementById('submitPaymentBtn').disabled = false;
                    document.getElementById('submitBtnText').innerHTML = '<i class="ri-money-dollar-circle-line me-1"></i>Check Status';
                    document.getElementById('submitBtnSpinner').style.display = 'none';
                }
            }, 1000);
        }
    </script>
</body>
</html>
