<?php
// Define the base directory constant
define('ROOT_DIR', realpath(dirname(__FILE__)) . '/../');

// Securely include files using the ROOT_DIR constant
include ROOT_DIR . 'pages/dbFunctions.php';
include ROOT_DIR . 'auth/config.php';
include ROOT_DIR . 'pages/dbInfo.php';
include ROOT_DIR . 'auth/fampay_mail_check.php';
include ROOT_DIR . 'includes/google_oauth.php';
include ROOT_DIR . 'includes/fampay_gmail_api.php';
include_once ROOT_DIR . 'includes/subscription_lib.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $byteTransactionId = ($_POST['byte_order_status']);
} else {
    header('HTTP/1.1 403 Forbidden');
    exit('Forbidden');
}

$sqlSelectOrderscxr = "SELECT * FROM orders WHERE byteTransactionId=?";
$stmtSelectOrderscxr = $conn->prepare($sqlSelectOrderscxr);
$stmtSelectOrderscxr->bind_param("s", $byteTransactionId);
$stmtSelectOrderscxr->execute();
$resultSelectOrders = $stmtSelectOrderscxr->get_result();
$cxrrrowOrders = $resultSelectOrders->fetch_assoc();
$stmtSelectOrderscxr->close();

if (!$cxrrrowOrders) {
    die("Byter error");
}

$order_id      = $cxrrrowOrders['order_id'];
$db_amount     = $cxrrrowOrders['amount'];
$order_created = strtotime($cxrrrowOrders['create_date']);

// If already marked SUCCESS earlier, just report it (no need to hit Gmail again)
$sqlCheckStatus = "SELECT status FROM orders WHERE order_id=?";
$stmtCheckStatus = $conn->prepare($sqlCheckStatus);
$stmtCheckStatus->bind_param("s", $order_id);
$stmtCheckStatus->execute();
$resultCheckStatus = $stmtCheckStatus->get_result();
if ($resultCheckStatus->num_rows > 0) {
    $rowCheckStatus = $resultCheckStatus->fetch_assoc();
    if ($rowCheckStatus['status'] === 'SUCCESS') {
        echo 'success';
        $stmtCheckStatus->close();
        $conn->close();
        exit;
    }
    if ($rowCheckStatus['status'] === 'FAILURE') {
        echo 'FAILURE';
        $stmtCheckStatus->close();
        $conn->close();
        exit;
    }
}
$stmtCheckStatus->close();

$user_token   = $cxrrrowOrders['user_token'];
$cxrremark1   = $cxrrrowOrders['remark1'];

$sqlSelectUser = "SELECT * FROM users WHERE user_token=?";
$stmtSelectUser = $conn->prepare($sqlSelectUser);
$stmtSelectUser->bind_param("s", $user_token);
$stmtSelectUser->execute();
$resultSelectUser = $stmtSelectUser->get_result();
$rowUser = $resultSelectUser->fetch_assoc();
$stmtSelectUser->close();

$callback_url  = $rowUser['callback_url'];
$megabyteuserid = $rowUser['id'];

// Fetch this merchant's FamPay Gmail credentials
$sqlSelectFam = "SELECT * FROM fampay_tokens WHERE user_token=?";
$stmtSelectFam = $conn->prepare($sqlSelectFam);
$stmtSelectFam->bind_param("s", $user_token);
$stmtSelectFam->execute();
$resultSelectFam = $stmtSelectFam->get_result();
$rowFam = $resultSelectFam->fetch_assoc();
$stmtSelectFam->close();

if (!$rowFam || $rowFam['status'] !== 'Active') {
    echo 'PENDING';
    $conn->close();
    exit;
}

$gmail        = $rowFam['gmail'];
$app_password = $rowFam['app_password'];

// Merchants who connected via "Sign in with Google" have a refresh_token
// and are checked through the Gmail API. Older merchants who connected
// with a manual Gmail App Password still go through the original IMAP
// check - nothing changes for them.
if (!empty($rowFam['refresh_token'])) {
    $accessToken = google_oauth_get_valid_access_token($conn, $rowFam, $site_settings);
    $check = $accessToken
        ? fampay_check_payment_oauth($accessToken, $db_amount, $order_id, null, null, $order_created, $conn)
        : ['matched' => false, 'utr' => null, 'error' => 'Google access token could not be refreshed'];
} else {
    $check = fampay_check_payment($gmail, $app_password, $db_amount, $order_id, null, null, $order_created, $conn);
}

if ($check['matched']) {

    $UTR = $check['utr'];

    include_once ROOT_DIR . 'includes/fampay_order_resolver.php';
    resolve_fampay_order_success($conn, $order_id, $UTR, $db_amount, $user_token, $cxrremark1, $megabyteuserid, $callback_url, $gmail);

    echo 'success';

} else {
    if (!empty($check['error'])) {
        // Log quietly, don't leak error to the browser/customer
        error_log('FamPay verify error for order ' . $order_id . ': ' . $check['error']);
    }
    echo 'PENDING';
}

$conn->close();
?>
