<?php
session_start();

header("Access-Control-Allow-Origin: https://enerliths.com");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once "../config/db.php";

$data = json_decode(file_get_contents("php://input"), true);
$checkout = $data["checkout"];

/* GET DEPOSIT */

$stmt=$conn->prepare("SELECT * FROM deposits WHERE checkout_request_id=?");
$stmt->bind_param("s",$checkout);
$stmt->execute();
$deposit=$stmt->get_result()->fetch_assoc();

if(!$deposit){
    echo json_encode(["status"=>"not_found"]);
    exit();
}

if($deposit["status"]!="pending"){
    echo json_encode(["status"=>$deposit["status"]]);
    exit();
}

/* timeout protection (90 seconds) */

$created=strtotime($deposit["created_at"]);
if(time()-$created>90){

    $stmt=$conn->prepare("UPDATE deposits SET status='failed' WHERE checkout_request_id=?");
    $stmt->bind_param("s",$checkout);
    $stmt->execute();

    echo json_encode(["status"=>"timeout"]);
    exit();
}

/* DARJA CREDENTIALS */

$shortcode="4168553";
$passkey = "b53d140509cb2b0f51a5939375e857da6afa5071bfc5f1239e38c57d0a5f2bc5";
$consumerKey = "yrSfRYeKGqGXNlIu8W2OAdunskod36frZfKGoiKCSXVOJ5o2";
$consumerSecret = "pE4Blivbaflxp3r9xdBPoQYNllNO57JwhEKXq6vdGk89iOoaBKyieVCCVmywBowT";

$timestamp=date("YmdHis");
$password=base64_encode($shortcode.$passkey.$timestamp);

/* ACCESS TOKEN */

$cred=base64_encode($consumerKey.":".$consumerSecret);

$curl=curl_init();
curl_setopt($curl,CURLOPT_URL,"https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials");
curl_setopt($curl,CURLOPT_HTTPHEADER,["Authorization: Basic ".$cred]);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);

$res=json_decode(curl_exec($curl));
$token=$res->access_token;

/* STK QUERY */

$url="https://api.safaricom.co.ke/mpesa/stkpushquery/v1/query";

$payload=[
"BusinessShortCode"=>$shortcode,
"Password"=>$password,
"Timestamp"=>$timestamp,
"CheckoutRequestID"=>$checkout
];

$curl=curl_init($url);

curl_setopt($curl,CURLOPT_HTTPHEADER,[
"Authorization: Bearer ".$token,
"Content-Type: application/json"
]);

curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($payload));

$result=json_decode(curl_exec($curl),true);

/* INCREMENT CHECK COUNTER */

$conn->query("UPDATE deposits SET stk_checks=stk_checks+1,last_check=NOW() WHERE checkout_request_id='$checkout'");

/* SUCCESS */

if(isset($result["ResultCode"]) && $result["ResultCode"]==0){

    $user=$deposit["user_id"];
    $usd=$deposit["amount_usd"];

    $conn->begin_transaction();

    $stmt=$conn->prepare("UPDATE deposits SET status='success' WHERE checkout_request_id=?");
    $stmt->bind_param("s",$checkout);
    $stmt->execute();

    $stmt=$conn->prepare("UPDATE users SET balance=balance+? WHERE id=?");
    $stmt->bind_param("di",$usd,$user);
    $stmt->execute();

    $conn->commit();

    echo json_encode(["status"=>"success"]);
    exit();
}

/* REAL FAILURE CODES */

$failCodes=[1032,1037,1];

if(isset($result["ResultCode"]) && in_array($result["ResultCode"],$failCodes)){

    $stmt=$conn->prepare("UPDATE deposits SET status='failed' WHERE checkout_request_id=?");
    $stmt->bind_param("s",$checkout);
    $stmt->execute();

    echo json_encode(["status"=>"failed"]);
    exit();
}

/* OTHERWISE STILL PENDING */

echo json_encode(["status"=>"pending"]);