<?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 "../config/db.php";

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

$user_id = $data["user_id"];
$phone = $data["phone"];
$amount_usd = floatval($data["amount"]);

/* CONFIG */

$consumer_key = "yrSfRYeKGqGXNlIu8W2OAdunskod36frZfKGoiKCSXVOJ5o2";
$consumer_secret = "pE4Blivbaflxp3r9xdBPoQYNllNO57JwhEKXq6vdGk89iOoaBKyieVCCVmywBowT";

$shortcode = "4168553";

$initiator = "Enerlith003api";

$security_credential = "jd3RuEIXj2yDeDNpC4cgKh32O22fD74D3ZV2a555K00EbECYh2mP+SYARsdy7VTR32zEOEZI1IpzhCoLJ3zUuaTHNUNH8+8M98SSdrofxgr1xmTnoT20OjB+EEyD5B5f/2MYLvsTpqRXK0sQq1qGMWQ8LJXNIeN9cr1lse3qjCWTN5ygazOyPXe+piYAZAqROLR8dA6PsEZ2CSCtttSdq0zpjS2aR67ch7a2AlB/qLz5pdO6Nz8f39ubrw5nAuv/jAx1uKWbx0Q4ayArPkThLfknH8Q04s9J960cY7wiKQ0QrZF8cVDY8hyUiSfreKgF8mrjNe1rW1mI/dfSx5a39A==";
$result_url = "https://binary.enerliths.com/trading-backend/payments/mpesa_withdraw_result.php";

$timeout_url = "https://binary.enerliths.com/trading-backend/payments/mpesa_withdraw_timeout.php";


/* CALCULATIONS */

$rate = 129.1;

$fee = $amount_usd < 50 ? 1 : 2;

$total_usd = $amount_usd + $fee;

$kes = round($amount_usd * $rate);

if ($total_usd < 5) {
    echo json_encode(["success" => false, "error" => "Minimum withdrawal is $5"]);
    exit;
}

/* CHECK BALANCE */

$stmt = $conn->prepare("SELECT balance FROM users WHERE id=?");
$stmt->bind_param("i",$user_id);
$stmt->execute();

$row = $stmt->get_result()->fetch_assoc();

if(!$row){
    echo json_encode(["success"=>false,"error"=>"User not found"]);
    exit;
}

if($total_usd > $row["balance"]){
    echo json_encode([
        "success"=>false,
        "error"=>"Insufficient balance"
    ]);
    exit;
}

/* SAVE REQUEST */

$stmt = $conn->prepare("
INSERT INTO mpesa_withdrawals
(user_id,phone,amount,fee,amount_sent,status)
VALUES (?,?,?,?,?,'pending')
");

$stmt->bind_param(
"isddd",
$user_id,
$phone,
$amount_usd,
$fee,
$kes
);

$stmt->execute();

$withdraw_id = $conn->insert_id;

/* GET TOKEN */

$credentials = base64_encode($consumer_key.":".$consumer_secret);

$token_url = "https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials";

$ch = curl_init($token_url);

curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Basic ".$credentials
]);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$token_response = curl_exec($ch);

$token_data = json_decode($token_response);

$access_token = $token_data->access_token;

/* B2C REQUEST */

$url = "https://api.safaricom.co.ke/mpesa/b2c/v1/paymentrequest";

$payload = [

"InitiatorName"=>$initiator,

"SecurityCredential"=>$security_credential,

"CommandID"=>"BusinessPayment",

"Amount"=>$kes,

"PartyA"=>$shortcode,

"PartyB"=>$phone,

"Remarks"=>"Withdrawal",

"QueueTimeOutURL"=>$timeout_url,

"ResultURL"=>$result_url,

"Occasion"=>$withdraw_id

];

$ch = curl_init($url);

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

curl_setopt($ch,CURLOPT_POST,true);

curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($payload));

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$response = curl_exec($ch);

$result = json_decode($response,true);

/* SAVE MPESA IDS */

if(isset($result["ConversationID"])){

$stmt = $conn->prepare("
UPDATE mpesa_withdrawals
SET mpesa_conversation_id=?, mpesa_originator_id=?
WHERE id=?
");

$stmt->bind_param(
"ssi",
$result["ConversationID"],
$result["OriginatorConversationID"],
$withdraw_id
);

$stmt->execute();

}

echo json_encode([
"success"=>true
]);
