<?php

require "../config/db.php";

$raw = file_get_contents("php://input");

/* LOG CALLBACK FOR DEBUG */

file_put_contents("mpesa_callback_log.txt",$raw."\n",FILE_APPEND);

$data = json_decode($raw, true);

$result = $data["Result"];

$resultCode = $result["ResultCode"];
$conversation = $result["ConversationID"];
$originator = $result["OriginatorConversationID"];

/* FIND WITHDRAW USING ORIGINATOR ID */

$stmt = $conn->prepare("
SELECT id,user_id,amount,fee,status
FROM mpesa_withdrawals
WHERE mpesa_originator_id=?
");

$stmt->bind_param("s",$originator);
$stmt->execute();

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

if(!$row){
    http_response_code(200);
    exit;
}

$withdraw_id = $row["id"];

if($resultCode == 0){

/* UPDATE STATUS */

$stmt = $conn->prepare("
UPDATE mpesa_withdrawals
SET status='success',
mpesa_conversation_id=?
WHERE id=? AND status='pending'
");

$stmt->bind_param(
"si",
$conversation,
$withdraw_id
);

$stmt->execute();

/* ONLY DEDUCT IF UPDATED */

if($stmt->affected_rows > 0){

    $total = $row["amount"] + $row["fee"];

    $stmt = $conn->prepare("
    UPDATE users
    SET balance = balance - ?
    WHERE id=?");

    $stmt->bind_param(
    "di",
    $total,
    $row["user_id"]
    );

    $stmt->execute();
}

}else{

$stmt = $conn->prepare("
UPDATE mpesa_withdrawals
SET status='failed'
WHERE id=?");

$stmt->bind_param("i",$withdraw_id);
$stmt->execute();

}

http_response_code(200);