<?php
if (isset($_POST['submit'])) {

    date_default_timezone_set('Africa/Nairobi');

    // ── Credentials ──────────────────────────────────────────
    $consumerKey       = 'cr6QwJnr2AeH3OA1C8M5ekGM1ZMqrnoKSXwQvYFAQCDFLmhJ';
    $consumerSecret    = 'bh8PUZt3LJARWqHdk3WmJqwkaiSKRAYraIpyy6175AqC2YBLEAwxHjqUANELcUBZ';
    $BusinessShortCode = '174379';
    $Passkey           = 'bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919';

    // ── Inputs ───────────────────────────────────────────────
    $Amount    = trim($_POST['amount']);
    $PartyA    = trim($_POST['phone']);

    // Normalize phone: strip leading 0 → 2547XXXXXXXX
    if (preg_match('/^0/', $PartyA)) {
        $PartyA = '254' . substr($PartyA, 1);
    }

    $AccountReference = 'Test001';
    $TransactionDesc  = 'Test Payment';
    $Timestamp        = date('YmdHis');
    $Password         = base64_encode($BusinessShortCode . $Passkey . $Timestamp);

    // ── FIX: use ngrok/localhost.run tunnel for callback ─────
    // Safaricom CANNOT reach localhost. Use ngrok:
    //   1. Download ngrok → https://ngrok.com/download
    //   2. Run: ngrok http 80
    //   3. Copy the https URL and paste below
    $CallBackURL = 'https://YOUR-NGROK-URL.ngrok.io/New%20folder/callback.php';
    // Example: 'https://a1b2-41-90-64-10.ngrok.io/New%20folder/callback.php'

    // ── API URLs ─────────────────────────────────────────────
    $access_token_url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
    $initiate_url     = 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';

    // ════════════════════════════════════════════════════════
    //  STEP 1 — Get access token
    // ════════════════════════════════════════════════════════
    $curl = curl_init($access_token_url);
    curl_setopt_array($curl, [
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER         => false,
        CURLOPT_USERPWD        => $consumerKey . ':' . $consumerSecret,
        // FIX ↓ — disables SSL verification on localhost (XAMPP has no certs)
        // Remove these two lines when deploying to a live server
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ]);

    $tokenResponse = curl_exec($curl);
    $httpCode      = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $curlError     = curl_error($curl);
    curl_close($curl);

    // ── Catch cURL-level failure (no internet, SSL block, etc.) ──
    if ($tokenResponse === false) {
        die('<b>cURL error getting token:</b> ' . $curlError .
            '<br>Check your internet connection and that XAMPP can reach the internet.');
    }

    $tokenData = json_decode($tokenResponse);

    // ── Catch API-level failure (wrong credentials, etc.) ────
    if (empty($tokenData->access_token)) {
        echo '<b>Failed to get access token.</b><br>';
        echo '<pre>HTTP ' . $httpCode . '</pre>';
        echo '<pre>' . htmlspecialchars($tokenResponse) . '</pre>';
        exit;
    }

    $access_token = $tokenData->access_token;

    // ════════════════════════════════════════════════════════
    //  STEP 2 — Initiate STK Push
    // ════════════════════════════════════════════════════════
    $payload = json_encode([
        'BusinessShortCode' => $BusinessShortCode,
        'Password'          => $Password,
        'Timestamp'         => $Timestamp,
        'TransactionType'   => 'CustomerPayBillOnline',
        'Amount'            => (int) $Amount,
        'PartyA'            => $PartyA,
        'PartyB'            => $BusinessShortCode,
        'PhoneNumber'       => $PartyA,
        'CallBackURL'       => $CallBackURL,
        'AccountReference'  => $AccountReference,
        'TransactionDesc'   => $TransactionDesc,
    ]);

    $curl = curl_init($initiate_url);
    curl_setopt_array($curl, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $access_token,
        ],
        CURLOPT_SSL_VERIFYPEER => false,   // remove on live server
        CURLOPT_SSL_VERIFYHOST => false,   // remove on live server
    ]);

    $stkResponse = curl_exec($curl);
    $stkError    = curl_error($curl);
    curl_close($curl);

    if ($stkResponse === false) {
        die('<b>cURL error during STK push:</b> ' . $stkError);
    }

    $stkData = json_decode($stkResponse, true);

    // ════════════════════════════════════════════════════════
    //  STEP 3 — Show result
    // ════════════════════════════════════════════════════════
    if (isset($stkData['ResponseCode']) && $stkData['ResponseCode'] === '0') {
        // ✅ STK push sent successfully
        echo '<div style="font-family:sans-serif;padding:20px;color:green">';
        echo '<h3>✅ STK Push Sent!</h3>';
        echo '<p>Check your phone <strong>' . htmlspecialchars($PartyA) . '</strong> for the M-Pesa prompt.</p>';
        echo '<p><b>CheckoutRequestID:</b> ' . htmlspecialchars($stkData['CheckoutRequestID']) . '</p>';
        echo '</div>';
    } else {
        // ❌ Safaricom returned an error
        echo '<div style="font-family:sans-serif;padding:20px;color:red">';
        echo '<h3>❌ STK Push Failed</h3>';
        echo '<pre>' . htmlspecialchars(json_encode($stkData, JSON_PRETTY_PRINT)) . '</pre>';
        echo '</div>';
    }
}
?>