<?php
/**
 * M-Pesa STK Push Callback Handler for Property Payments
 * This endpoint receives callbacks from Safaricom M-Pesa API
 */

include '../layouts/dbconn.php';

// Log the callback for debugging
$callback_data = file_get_contents('php://input');
$log_data = date('Y-m-d H:i:s') . " - Callback received: " . $callback_data . "\n";
file_put_contents('../logs/mpesa_callback.log', $log_data, FILE_APPEND);

// Parse callback data
$data = json_decode($callback_data, true);

if (!isset($data['Body']['stkCallback'])) {
    http_response_code(400);
    exit();
}

$callback = $data['Body']['stkCallback'];
$merchant_request_id = $callback['MerchantRequestID'] ?? '';
$checkout_request_id = $callback['CheckoutRequestID'] ?? '';
$result_code = $callback['ResultCode'] ?? '';
$result_desc = $callback['ResultDesc'] ?? '';

    // Get transaction details - check both checkout_request_id and merchant_request_id
    $sql = "SELECT * FROM mpesa_transactions 
            WHERE (checkout_request_id = ? OR merchant_request_id = ?) 
            ORDER BY created_at DESC LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $checkout_request_id, $merchant_request_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $transaction = $result->fetch_assoc();

    if (!$transaction) {
        // Log error but don't fail - M-Pesa expects 200 response
        $log_data = date('Y-m-d H:i:s') . " - Transaction not found: " . $checkout_request_id . "\n";
        file_put_contents('../logs/mpesa_callback.log', $log_data, FILE_APPEND);
        http_response_code(200);
        echo json_encode(['ResultCode' => 0, 'ResultDesc' => 'Transaction not found']);
        exit();
    }

if ($result_code == 0) {
    // Payment successful
    $callback_metadata = $callback['CallbackMetadata']['Item'] ?? [];
    $mpesa_receipt = '';
    $transaction_date = '';
    $phone_number = '';
    $amount = 0;
    
    foreach ($callback_metadata as $item) {
        switch ($item['Name']) {
            case 'MpesaReceiptNumber':
                $mpesa_receipt = $item['Value'];
                break;
            case 'TransactionDate':
                $transaction_date = $item['Value'];
                break;
            case 'PhoneNumber':
                $phone_number = $item['Value'];
                break;
            case 'Amount':
                $amount = $item['Value'];
                break;
        }
    }
    
    // Update transaction status
    $update_sql = "UPDATE mpesa_transactions 
                   SET status = 'COMPLETED', 
                       mpesa_receipt_number = ?,
                       transaction_date = ?,
                       updated_at = NOW()
                   WHERE id = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("ssi", $mpesa_receipt, $transaction_date, $transaction['id']);
    $update_stmt->execute();
    
    // Get lease_id from invoice if available
    $lease_id = $transaction['lease_id'];
    if ($transaction['invoice_id']) {
        $invoice_sql = "SELECT lease_id FROM invoices WHERE invoice_id = ?";
        $invoice_stmt = $conn->prepare($invoice_sql);
        $invoice_stmt->bind_param("i", $transaction['invoice_id']);
        $invoice_stmt->execute();
        $invoice_result = $invoice_stmt->get_result();
        $invoice = $invoice_result->fetch_assoc();
        if ($invoice) {
            $lease_id = $invoice['lease_id'];
        }
    }
    
    // Create payment record
    if ($transaction['invoice_id'] && $lease_id) {
        // Check if payment already exists (prevent duplicates)
        $check_payment_sql = "SELECT payment_id FROM rent_payments 
                             WHERE payment_reference = ? AND payment_status = 'COMPLETED'";
        $check_stmt = $conn->prepare($check_payment_sql);
        $check_stmt->bind_param("s", $mpesa_receipt);
        $check_stmt->execute();
        $existing = $check_stmt->get_result()->fetch_assoc();
        
        if (!$existing) {
            // Get invoice details
            $invoice_sql = "SELECT * FROM invoices WHERE invoice_id = ?";
            $invoice_stmt = $conn->prepare($invoice_sql);
            $invoice_stmt->bind_param("i", $transaction['invoice_id']);
            $invoice_stmt->execute();
            $invoice_result = $invoice_stmt->get_result();
            $invoice = $invoice_result->fetch_assoc();
            
            if ($invoice) {
                // Insert payment
                $payment_sql = "INSERT INTO rent_payments 
                               (lease_id, invoice_id, amount, payment_date, payment_method, 
                                payment_reference, payment_status, notes, created_at) 
                               VALUES (?, ?, ?, NOW(), 'M-Pesa', ?, 'COMPLETED', ?, NOW())";
                $payment_stmt = $conn->prepare($payment_sql);
                $notes = 'M-Pesa Payment - Receipt: ' . $mpesa_receipt;
                $payment_stmt->bind_param("iidss", $lease_id, $transaction['invoice_id'], 
                                         $amount, $mpesa_receipt, $notes);
                $payment_stmt->execute();
                
                // Update invoice balance
                $new_balance = max(0, $invoice['balance'] - $amount);
                $new_status = $new_balance == 0 ? 'paid' : ($new_balance < $invoice['total_amount'] ? 'partial' : $invoice['status']);
                
                $invoice_update_sql = "UPDATE invoices SET balance = ?, status = ? WHERE invoice_id = ?";
                $invoice_update_stmt = $conn->prepare($invoice_update_sql);
                $invoice_update_stmt->bind_param("dsi", $new_balance, $new_status, $transaction['invoice_id']);
                $invoice_update_stmt->execute();
            }
        }
    } elseif ($transaction['lease_id']) {
        // Payment without invoice (direct lease payment)
        $payment_sql = "INSERT INTO rent_payments 
                       (lease_id, invoice_id, amount, payment_date, payment_method, 
                        payment_reference, payment_status, notes, created_at) 
                       VALUES (?, NULL, ?, NOW(), 'M-Pesa', ?, 'COMPLETED', ?, NOW())";
        $payment_stmt = $conn->prepare($payment_sql);
        $notes = 'M-Pesa Payment - Receipt: ' . $mpesa_receipt;
        $payment_stmt->bind_param("idss", $transaction['lease_id'], $amount, $mpesa_receipt, $notes);
        $payment_stmt->execute();
    }
    
} else {
    // Payment failed or cancelled
    $update_sql = "UPDATE mpesa_transactions 
                   SET status = 'FAILED', 
                       error_message = ?,
                       updated_at = NOW()
                   WHERE id = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("si", $result_desc, $transaction['id']);
    $update_stmt->execute();
}

// Return success to M-Pesa
http_response_code(200);
echo json_encode(['ResultCode' => 0, 'ResultDesc' => 'Accepted']);
?>
