<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

require_once '../layouts/dbconn.php';

/**
 * M-Pesa STK Push for Property Management Payments
 * Initiates STK push to prompt user to pay via M-Pesa
 */

try {
    $phone = $_POST['phone'] ?? '';
    $amount = floatval($_POST['amount'] ?? 0);
    $invoice_id = $_POST['invoice_id'] ?? null;
    $lease_id = $_POST['lease_id'] ?? null;
    
    if (empty($phone) || $amount <= 0) {
        throw new Exception('Invalid phone number or amount');
    }
    
    // Format phone number (convert to 254 format)
    $phone = preg_replace('/[^0-9]/', '', $phone);
    if (strlen($phone) === 10 && substr($phone, 0, 1) === '0') {
        $phone = '254' . substr($phone, 1);
    } elseif (strlen($phone) === 9) {
        $phone = '254' . $phone;
    }
    
    if (!preg_match('/^254[0-9]{9}$/', $phone)) {
        throw new Exception('Invalid phone number format. Use 254XXXXXXXXX or 0XXXXXXXXX');
    }
    
    // Get M-Pesa settings from system_settings
    $settings_sql = "SELECT setting_key, setting_value FROM system_settings 
                     WHERE setting_key LIKE 'mpesa_%'";
    $settings_result = $conn->query($settings_sql);
    $settings = [];
    while ($row = $settings_result->fetch_assoc()) {
        $key = str_replace('mpesa_', '', $row['setting_key']);
        $settings[$key] = $row['setting_value'];
    }
    
    // Check if M-Pesa is enabled
    if (!isset($settings['enabled']) || $settings['enabled'] != '1') {
        throw new Exception('M-Pesa integration is not enabled. Please contact administrator.');
    }
    
    $environment = $settings['environment'] ?? 'sandbox';
    $shortcode = $settings['shortcode'] ?? '174379';
    $consumer_key = $settings['consumer_key'] ?? '';
    $consumer_secret = $settings['consumer_secret'] ?? '';
    $passkey = $settings['passkey'] ?? '';
    
    if (empty($consumer_key) || empty($consumer_secret) || empty($passkey)) {
        throw new Exception('M-Pesa credentials not configured. Please contact administrator.');
    }
    
    // Get base URL for callback
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $callback_url = $protocol . '://' . $host . '/api/mpesa_callback_payment.php';
    
    // Generate account reference
    $account_reference = 'PROP-' . ($invoice_id ?? 'PAY') . '-' . date('Ymd');
    
    // Determine API URLs
    $auth_url = ($environment === 'production') 
        ? 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'
        : 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
    
    $stk_url = ($environment === 'production')
        ? 'https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest'
        : 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
    
    // Step 1: Get OAuth Access Token
    $credentials = base64_encode($consumer_key . ':' . $consumer_secret);
    
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $auth_url,
        CURLOPT_HTTPHEADER => ['Authorization: Basic ' . $credentials],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT => 30
    ]);
    
    $auth_response = curl_exec($curl);
    $auth_result = json_decode($auth_response);
    
    if (!isset($auth_result->access_token)) {
        curl_close($curl);
        throw new Exception('Failed to get M-Pesa access token. Please try again.');
    }
    
    $access_token = $auth_result->access_token;
    
    // Step 2: Initiate STK Push
    $timestamp = date('YmdHis');
    $password = base64_encode($shortcode . $passkey . $timestamp);
    
    $stk_data = [
        'BusinessShortCode' => $shortcode,
        'Password' => $password,
        'Timestamp' => $timestamp,
        'TransactionType' => 'CustomerPayBillOnline',
        'Amount' => round($amount),
        'PartyA' => $phone,
        'PartyB' => $shortcode,
        'PhoneNumber' => $phone,
        'CallBackURL' => $callback_url,
        'AccountReference' => $account_reference,
        'TransactionDesc' => 'Property Management Payment'
    ];
    
    curl_setopt_array($curl, [
        CURLOPT_URL => $stk_url,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $access_token,
            'Content-Type: application/json'
        ],
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($stk_data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT => 30
    ]);
    
    $stk_response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    
    $stk_result = json_decode($stk_response);
    
    if ($http_code === 200 && isset($stk_result->ResponseCode) && $stk_result->ResponseCode == '0') {
        // Success - Save pending transaction
        $checkout_request_id = $stk_result->CheckoutRequestID;
        $merchant_request_id = $stk_result->MerchantRequestID;
        
        // Insert into mpesa_transactions or create pending payment record
        $insert_sql = "INSERT INTO mpesa_transactions 
                      (invoice_id, lease_id, phone_number, amount, merchant_request_id, checkout_request_id, 
                       account_reference, status, created_at) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, 'PENDING', NOW())";
        $stmt = $conn->prepare($insert_sql);
        $stmt->bind_param("iisdsss", $invoice_id, $lease_id, $phone, $amount, 
                         $merchant_request_id, $checkout_request_id, $account_reference);
        $stmt->execute();
        
        $transaction_id = $conn->insert_id;
        
        echo json_encode([
            'success' => true,
            'message' => 'Payment prompt sent to your phone. Please check your M-Pesa menu and enter your PIN.',
            'checkout_request_id' => $checkout_request_id,
            'merchant_request_id' => $merchant_request_id,
            'transaction_id' => $transaction_id
        ]);
    } else {
        $error_message = isset($stk_result->errorMessage) 
            ? $stk_result->errorMessage 
            : (isset($stk_result->ResponseDescription) ? $stk_result->ResponseDescription : 'Failed to initiate M-Pesa payment');
        
        throw new Exception($error_message);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
