<?php
function pdo() {
    $db = new Database();
    return $db->getConnection();
}
// src/MpesaStk.php
function get_credential($ussd) {
    $stmt = pdo()->prepare('SELECT * FROM ussd_mpesa_credentials WHERE ussd = ? LIMIT 1');
    $stmt->execute([$ussd]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function generateMpesaToken($consumer_key, $consumer_secret) {
    $url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
    $credentials = base64_encode("$consumer_key:$consumer_secret");
    $headers = [
        "Authorization: Basic $credentials"
    ];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    $access_token = $data['access_token'] ?? null;
    return $access_token;
}

function preparePayload($phone, $amount, $reference, $callback, $shortcode, $passkey, $party_b, $account, $transactionType) {
    $timestamp = date('YmdHis');
    $password = base64_encode($shortcode . $passkey . $timestamp);
    return [
        'BusinessShortCode' => $shortcode,
        'Password' => $password,
        'Timestamp' => $timestamp,
        'TransactionType' => $transactionType,
        'Amount' => $amount,
        'PartyA' => $phone,
        'PartyB' => $party_b,
        'PhoneNumber' => $phone,
        'CallBackURL' => $callback,
        'AccountReference' => $account,
        'TransactionDesc' => $reference
    ];
}

function mpesaMakeHttp($body, $consumer_key, $consumer_secret, $token) {
    $url = 'https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
    $headers = [
        "Authorization: Bearer $token",
        "Content-Type: application/json"
    ];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    return $data['CheckoutRequestID'] ?? null;
}



function enqueue_stk_push( $phone, $amount, $meta,$code,$type='loan',$extension='11'): void
{
    $cred = get_credential($code);
    $token = generateMpesaToken($cred['consumer_key'], $cred['consumer_secret']);
    $body = preparePayload($phone, $amount, $meta['reference'], 'https://chomoahela.co.ke/ussd/callback.php', $cred['shortcode'], $cred['passkey'], $cred['party_b'], $cred['account'],$cred['transaction_type']);

    $checkout = mpesaMakeHttp($body, $cred['consumer_key'], $cred['consumer_secret'], $token);

    $st = pdo()->prepare('INSERT INTO mpesa_stk_queue (phone,amount,checkout_id,created_at,type,extension) VALUES (?,?,?,NOW(),?,?)');
    $st->execute([$phone, $amount, $checkout, $type,$extension]);
}
