<?php

session_start();

require_once __DIR__ . "/config/database.php";
require_once __DIR__ . "/classes/MTNMoMo.php";

date_default_timezone_set("Africa/Kigali");

/*
|--------------------------------------------------------------------------
| DATABASE
|--------------------------------------------------------------------------
*/

$db = new Database();
$pdo = $db->connect();

/*
|--------------------------------------------------------------------------
| CHECK SESSION
|--------------------------------------------------------------------------
*/

if(
    !isset($_SESSION["print_job"]) ||
    !isset($_SESSION["print_job"]["order_id"])
){

    header("Location:index.php");
    exit;

}

$order_id = (int)$_SESSION["print_job"]["order_id"];

/*
|--------------------------------------------------------------------------
| LOAD ORDER
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("

SELECT *

FROM print_orders

WHERE id=?

LIMIT 1

");

$stmt->execute([$order_id]);

$order = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$order){

    die("Order not found.");

}

/*
|--------------------------------------------------------------------------
| LOAD PAYMENT
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("

SELECT *

FROM payments

WHERE order_id=?

ORDER BY id DESC

LIMIT 1

");

$stmt->execute([$order_id]);

$payment = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$payment){

    die("Payment record not found.");

}

$referenceId = $payment["reference_id"];

/*
|--------------------------------------------------------------------------
| CHECK PAYMENT STATUS (AJAX)
|--------------------------------------------------------------------------
*/

if (
    isset($_GET["action"]) &&
    $_GET["action"] === "check"
) {

    header("Content-Type: application/json");

    $momo = new MTNMoMo();

$result = $momo->checkPaymentStatus($referenceId);


if (!$result["success"]) {

    echo json_encode([
        "success" => false,
        "message" => "Unable to check payment status.",
        "result"  => $result
    ]);

    exit;
}

/*
|--------------------------------------------------------------------------
| EXTRACT RESPONSE
|--------------------------------------------------------------------------
*/

$response = $result["response"] ?? [];

$status = strtoupper(
    $response["status"] ?? "PENDING"
);
    /*
    |--------------------------------------------------------------------------
    | UPDATE PAYMENTS TABLE
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        UPDATE payments
        SET
            status = ?,
            raw_response = ?
        WHERE id = ?
    ");

    $stmt->execute([

        $status,

        json_encode($response),

        $payment["id"]

    ]);

    /*
    |--------------------------------------------------------------------------
    | SAVE FINANCIAL TRANSACTION ID
    |--------------------------------------------------------------------------
    */

    if (!empty($response["financialTransactionId"])) {

        $stmt = $pdo->prepare("
    UPDATE payments
    SET transaction_id = ?
    WHERE id = ?
");

$stmt->execute([

    $response["financialTransactionId"],

    $payment["id"]

]);

    }

    /*
    |--------------------------------------------------------------------------
    | UPDATE PRINT ORDER
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
    UPDATE print_orders
    SET payment_status = ?
    WHERE id = ?
");

$orderStatus = "waiting_payment";

if ($status === "SUCCESSFUL") {

    $orderStatus = "paid";

} elseif (

    $status === "FAILED" ||
    $status === "REJECTED" ||
    $status === "TIMEOUT"

) {

    $orderStatus = "cancelled";

}

$stmt->execute([

    $orderStatus,

    $order_id

]);

/*
|--------------------------------------------------------------------------
| ADD JOB TO PRINT QUEUE
|--------------------------------------------------------------------------
*/

if ($status === "SUCCESSFUL") {

    // Reba niba order itarajya muri queue
    $stmt = $pdo->prepare("
        SELECT id
        FROM print_queue
        WHERE order_id = ?
        LIMIT 1
    ");

    $stmt->execute([$order["id"]]);

    if (!$stmt->fetch()) {

        $stmt = $pdo->prepare("
            INSERT INTO print_queue
            (
                order_id,
                printer_id,
                file_name,
                pdf_path,
                copies,
                status
            )
            VALUES
            (
                ?, ?, ?, ?, ?, 'WAITING'
            )
        ");

        $stmt->execute([

            $order["id"],
            $order["printer_id"],
            $order["file_name"],
            $order["pdf_path"],
            $order["copies"]

        ]);

    }

}

    /*
    |--------------------------------------------------------------------------
    | RETURN JSON
    |--------------------------------------------------------------------------
    */

    echo json_encode([

        "success" => true,

        "status" => $status,

        "response" => $response

    ]);

    exit;

}

?>
<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>

Waiting Payment

</title>

<style>

body{

background:#0f1115;

font-family:Arial;

color:white;

display:flex;

justify-content:center;

align-items:center;

height:100vh;

margin:0;

}

.card{

width:450px;

background:#1d1f25;

padding:30px;

border-radius:12px;

text-align:center;

}

.loader{

width:70px;

height:70px;

border:8px solid #444;

border-top:8px solid #00c853;

border-radius:50%;

margin:auto;

animation:spin 1s linear infinite;

}

@keyframes spin{

100%{

transform:rotate(360deg);

}

}

.status{

margin-top:25px;

font-size:22px;

}

.info{

margin-top:15px;

color:#bbb;

}

</style>

</head>

<body>

<div class="card">

<div class="loader"></div>

<div
class="status"
id="paymentStatus"
>

Waiting for payment...

</div>

<div
class="info"
id="paymentMessage"
>

Please confirm the Mobile Money request on your phone.

</div>

<div class="info">

Amount:

<strong>

<?=number_format($order["price"],2)?>

<?=CURRENCY?>

</strong>

</div>

</div>

<script>

let paymentCompleted = false;

function checkPaymentStatus(){

    if(paymentCompleted){
        return;
    }

    fetch("payment_status.php?order=<?= $order_id ?>&action=check")

    .then(response => response.json())

    .then(data => {
        console.log(data);

        if(!data.success){

            console.log(data);

            return;

        }

        const status = data.status.toUpperCase();

        const statusBox =
            document.getElementById("paymentStatus");

        const messageBox =
            document.getElementById("paymentMessage");

        switch(status){

            case "PENDING":

                statusBox.innerHTML =
                    "Waiting for payment...";

                messageBox.innerHTML =
                    "Please approve the payment request on your phone.";

                break;


            case "SUCCESSFUL":

                paymentCompleted = true;

                statusBox.innerHTML =
                    "Payment Successful";

                messageBox.innerHTML =
                    "Your payment has been received. Preparing your print job...";

                setTimeout(function(){

                    window.location =
                        "success.php";

                },1500);

                break;


            case "FAILED":

                paymentCompleted = true;

                statusBox.innerHTML =
                    "Payment Failed";

                messageBox.innerHTML =
                    "The payment failed. Please try again.";

                break;


            case "REJECTED":

                paymentCompleted = true;

                statusBox.innerHTML =
                    "Payment Rejected";

                messageBox.innerHTML =
                    "The payment request was rejected.";

                break;


            case "TIMEOUT":

                paymentCompleted = true;

                statusBox.innerHTML =
                    "Payment Timed Out";

                messageBox.innerHTML =
                    "The payment request expired.";

                break;


            default:

                statusBox.innerHTML =
                    status;

                messageBox.innerHTML =
                    "Checking payment status...";

        }

    })

    .catch(error=>{

        console.log(error);

    });

}

checkPaymentStatus();

setInterval(checkPaymentStatus,3000);

</script>

</body>
</html>