<?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 (Lipa Na M-Pesa Online)
 * Initiates a payment request to customer's phone
 */

try {
    $phone = $_POST['phone'] ?? '';
    $amount = floatval($_POST['amount'] ?? 0);
    $visit_id = $_POST['visit_id'] ?? null;
    
    if (empty($phone) || $amount <= 0) {
        throw new Exception('Invalid phone number or amount');
    }
    
    // Format phone number
    $phone = preg_replace('/[^0-9]/', '', $phone);
    if (strlen($phone) === 10 && substr($phone, 0, 1) === '0') {
        $phone = '254' . substr($phone, 1);
    }
    if (!preg_match('/^254[0-9]{9}$/', $phone)) {
        throw new Exception('Invalid phone number format. Use 254XXXXXXXXX');
    }
    
    // Get M-Pesa settings
    $settings_sql = "SELECT setting_key, setting_value FROM system_settings 
                     WHERE category = 'mpesa'";
    $settings_result = $conn->query($settings_sql);
    $settings = [];
    while ($row = $settings_result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    if (!isset($settings['mpesa_enabled']) || $settings['mpesa_enabled'] != '1') {
        throw new Exception('M-Pesa integration is not enabled');
    }
    
    $environment = $settings['mpesa_environment'] ?? 'sandbox';
    $shortcode = $settings['mpesa_shortcode'] ?? '174379';
    $consumer_key = $settings['mpesa_consumer_key'] ?? '';
    $consumer_secret = $settings['mpesa_consumer_secret'] ?? '';
    $passkey = $settings['mpesa_passkey'] ?? '';
    $callback_url = $settings['mpesa_callback_url'] ?? '';
    $account_reference = $settings['mpesa_account_reference'] ?? 'ENT Hospital';
    
    if (empty($consumer_key) || empty($consumer_secret) || empty($passkey)) {
        throw new Exception('M-Pesa credentials not configured');
    }
    
    // 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');
    }
    
    $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' => $amount,
        'PartyA' => $phone,
        'PartyB' => $shortcode,
        'PhoneNumber' => $phone,
        'CallBackURL' => $callback_url,
        'AccountReference' => $account_reference,
        'TransactionDesc' => 'Payment for ENT Hospital services'
    ];
    
    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 transaction record
        $checkout_request_id = $stk_result->CheckoutRequestID;
        $merchant_request_id = $stk_result->MerchantRequestID;
        
        $insert_sql = "INSERT INTO mpesa_transactions 
                      (visit_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("isdsss", $visit_id, $phone, $amount, $merchant_request_id, 
                         $checkout_request_id, $account_reference);
        $stmt->execute();
        
        // Log activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_type, ip_address) 
                   VALUES (?, 'INITIATE', 'mpesa', 'stk_push', ?)";
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("is", $_SESSION['user_id'], $_SERVER['REMOTE_ADDR']);
        $log_stmt->execute();
        
        echo json_encode([
            'success' => true,
            'message' => 'Payment request sent successfully. Customer will receive a prompt on their phone.',
            'checkout_request_id' => $checkout_request_id,
            'merchant_request_id' => $merchant_request_id
        ]);
    } else {
        $error_message = isset($stk_result->errorMessage) 
            ? $stk_result->errorMessage 
            : 'Failed to initiate M-Pesa payment';
        
        throw new Exception($error_message);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>