<?php

// Get IPN data
$ipn_data = json_decode(file_get_contents('php://input'), true);

if (!isset($ipn_data["Body"]["stkCallback"])) {
    echo json_encode(['Response' => "Error", 'message' => "Invalid IPN data"]);
    exit;
}


$CheckoutRequestID = $ipn_data["Body"]["stkCallback"]["CheckoutRequestID"];
$ResponseCode = $ipn_data["Body"]["stkCallback"]["ResultCode"];

try {
    // Database connection
    $DB_HOST = 'localhost';
    $DB_NAME = 'kufgkmxh_loan';
    $DB_USER = 'kufgkmxh_ussd';
    $DB_PASSWORD = 'B80P4bGqN7NUyk';

    $pdo = new PDO("mysql:host=$DB_HOST;dbname=$DB_NAME;charset=utf8mb4", $DB_USER, $DB_PASSWORD);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Fetch record
    $stmt = $pdo->prepare("SELECT * FROM mpesa_stk_queue WHERE checkout_id = :checkout_id LIMIT 1");
    $stmt->execute([':checkout_id' => $CheckoutRequestID]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        echo json_encode(['Response' => "Error", 'message' => "Record not found"]);
        exit;
    }

    $MpesaReference = null;
        $phoneNumber = $result['phone'];
    $messageContent="";
    if ($ResponseCode == 0) {
        
         $items = $ipn_data["Body"]["stkCallback"]["CallbackMetadata"]["Item"] ?? [];

        foreach ($items as $item) {
            if (($item["Name"] ?? "") === "MpesaReceiptNumber") {
                $MpesaReference = $item["Value"] ?? null; // e.g. "RKT6G3JH2K"
                break;
            }
        }
    
        // Payment successful
        $messageContent = "Congratulations! You have successfully submitted your loan application. Dial *243*11# to withdraw to MPESA.";

        // Update payment status
        $updateStmt = $pdo->prepare("
                UPDATE mpesa_stk_queue
                SET is_paid = 'yes',
                    reference = :reference
                WHERE checkout_id = :checkout_id
            ");
            $updateStmt->execute([
                ':checkout_id' => $CheckoutRequestID,
                ':reference'   => $MpesaReference
            ]);

    } else {
        // Payment failed or canceled
        $messageContent = "Dear customer, you have cancelled loan request. Dial *243*11# and complete to receive KSH53,200 to MPESA $phoneNumber";
    }
    
 
$dataNew = json_encode([
     "mobile"=> "+".$phoneNumber,
        "response_type"=> "json",
        "sender_name"=> "INSTAPEX",
        "service_id"=> 0,
        "message"=> $messageContent
    ]);
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://api.mutexsms.com/sms/sendsms',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 15,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS =>$dataNew,
      CURLOPT_HTTPHEADER => array(
        'h_api_key: 12238dd3ae726c0ead3c0ccf97df999876af87265242b5c53f34f1413ef54ea3',
        'Content-Type: application/json'
      ),
    ));
    
    $response = curl_exec($curl);
    
    curl_close($curl);

} catch (PDOException $e) {
    echo json_encode(['Response' => "Error", 'message' => $e->getMessage()]);
}
