<?php
// phonepe_verify.php (updated to reliably set phonepe_tokens.status = 'Active')

session_start();
define('ABSPATH', dirname(__FILE__) . '/');
require_once(ABSPATH . 'header.php');

include "../pages/dbInfo.php";
include "../phnpe/index.php";

// helper sanitize if not present
if (!function_exists('sanitizeInput')) {
    function sanitizeInput($data){
        return trim(htmlspecialchars($data, ENT_QUOTES));
    }
}
if (!function_exists('setXbyY')) {
    function setXbyY($sql){
        global $conn;
        if(isset($conn) && $conn){
            return $conn->query($sql);
        }
        return false;
    }
}

// helper: check if a column exists in a table
function columnExists($conn, $table, $column){
    if(!isset($conn) || !$conn) return false;
    $sql = "SHOW COLUMNS FROM `$table` LIKE '".$conn->real_escape_string($column)."'";
    $res = $conn->query($sql);
    return ($res && $res->num_rows > 0);
}

// helper: set status by sl (preferred)
function setTokenStatusBySl($conn, $sl, $status = 'Active'){
    if(!$conn || !$sl) return false;
    $stmt = $conn->prepare("UPDATE `phonepe_tokens` SET `status` = ? WHERE `sl` = ?");
    if($stmt){
        $stmt->bind_param("si", $status, $sl);
        $stmt->execute();
        $ok = $stmt->affected_rows >= 0;
        $stmt->close();
        return $ok;
    } else {
        $sql = "UPDATE phonepe_tokens SET status='".$conn->real_escape_string($status)."' WHERE sl=".intval($sl);
        return ($conn->query($sql) === TRUE);
    }
}

// helper: fallback set status using user_token + phoneNumber + merchant_upi (most-recent)
function setTokenStatusFallback($conn, $user_token, $phoneNumber, $merchant_upi, $status = 'Active'){
    if(!$conn) return false;
    // Find the most recent matching row
    $sql = "SELECT sl FROM phonepe_tokens WHERE user_token='".$conn->real_escape_string($user_token)."' AND phoneNumber='".$conn->real_escape_string($phoneNumber)."'";
    if(!empty($merchant_upi)){
        $sql .= " AND merchant_upi='".$conn->real_escape_string($merchant_upi)."'";
    }
    $sql .= " ORDER BY `date` DESC LIMIT 1";
    $res = $conn->query($sql);
    if($res && $res->num_rows > 0){
        $row = $res->fetch_assoc();
        $sl = intval($row['sl']);
        return setTokenStatusBySl($conn, $sl, $status);
    }
    // If nothing found with phoneNumber + merchant_upi, try user_token only
    $sql2 = "SELECT sl FROM phonepe_tokens WHERE user_token='".$conn->real_escape_string($user_token)."' ORDER BY `date` DESC LIMIT 1";
    $res2 = $conn->query($sql2);
    if($res2 && $res2->num_rows > 0){
        $row2 = $res2->fetch_assoc();
        $sl2 = intval($row2['sl']);
        return setTokenStatusBySl($conn, $sl2, $status);
    }
    return false;
}

if(isset($_POST['verifyotp'])){ // Verify OTP submitted

    // collect inputs
    $otp = isset($_POST["otp"]) ? sanitizeInput($_POST["otp"]) : '';
    $numbero = isset($_POST["no"]) ? sanitizeInput($_POST["no"]) : '';
    $upi = isset($_POST["upi"]) ? sanitizeInput($_POST["upi"]) : '';
    $otp_toekn = isset($_POST["otp_toekn"]) ? sanitizeInput($_POST["otp_toekn"]) : '';
    $device_data = isset($_POST["device_data"]) ? sanitizeInput($_POST["device_data"]) : '';
    $user_token = isset($_POST['user_token']) ? sanitizeInput($_POST['user_token']) : '';
    $merchant_id = isset($_POST['merchant_id']) ? sanitizeInput($_POST['merchant_id']) : '';
    $merchant_click = isset($_POST['merchant_click']) ? sanitizeInput($_POST['merchant_click']) : '0';

    // Also accept user_name/user_role if passed from send-otp
    $post_user_name = isset($_POST['user_name']) ? sanitizeInput($_POST['user_name']) : '';
    $post_user_role = isset($_POST['user_role']) ? sanitizeInput($_POST['user_role']) : '';

    // Verify OTP using your sentotp verify call
    $otpferfyy = sentotp("2", $numbero, $otp, $otp_toekn, $device_data);
    $json0 = json_decode($otpferfyy, true);
    $b = json_decode($otpferfyy);

    $message = isset($json0["message"]) ? $json0["message"] : '';
    $phoneNumber = isset($json0["number"]) ? $json0["number"] : $numbero;
    $userId = isset($json0["userId"]) ? $json0["userId"] : null;
    $token = isset($json0["token"]) ? $json0["token"] : null;
    $refreshToken = isset($json0["refreshToken"]) ? $json0["refreshToken"] : null;
    $name = isset($json0["name"]) ? $json0["name"] : null;
    $device_datar = isset($json0["device_data"]) ? $json0["device_data"] : $device_data;

    if ($message == "success") {

        // 1) Update users.upi_id
        if(!empty($user_token)){
            if(isset($conn) && $conn){
                $stmt = $conn->prepare("UPDATE `users` SET `upi_id` = ? WHERE `user_token` = ?");
                if($stmt){
                    $stmt->bind_param("ss", $upi, $user_token);
                    $stmt->execute();
                    $stmt->close();
                } else {
                    $sql = "UPDATE users SET upi_id='".$conn->real_escape_string($upi)."' WHERE user_token='".$conn->real_escape_string($user_token)."'";
                    setXbyY($sql);
                }
            } else {
                setXbyY("UPDATE users SET upi_id='".$upi."' WHERE user_token='".$user_token."'");
            }
        }

        // 2) Delete old tokens for this user
        if(isset($conn) && $conn){
            $del_stmt = $conn->prepare("DELETE FROM `phonepe_tokens` WHERE `user_token` = ? AND `phoneNumber` = ?");
            if($del_stmt){
                $del_stmt->bind_param("ss", $user_token, $phoneNumber);
                $del_stmt->execute();
                $del_stmt->close();
            } else {
                $conn->query("DELETE FROM phonepe_tokens WHERE user_token='".$conn->real_escape_string($user_token)."' AND phoneNumber='".$conn->real_escape_string($phoneNumber)."'");
            }
        } else {
            setXbyY("DELETE FROM phonepe_tokens WHERE user_token='".$user_token."' AND phoneNumber='".$phoneNumber."'");
        }

        // 3) Insert new token record (merchant_upi set from $upi)
        $bbbyteuserid = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : (isset($userdata['user_id']) ? intval($userdata['user_id']) : 0);
        $last_insert_sl = 0;
        if(isset($conn) && $conn){
            $ins = $conn->prepare("INSERT INTO `phonepe_tokens` (`user_token`,`phoneNumber`,`userId`,`token`,`refreshToken`,`name`,`device_data`,`user_id`,`merchant_upi`) VALUES (?,?,?,?,?,?,?,?,?)");
            if($ins){
                $ins->bind_param("ssisssiss", $user_token, $phoneNumber, $userId, $token, $refreshToken, $name, $device_datar, $bbbyteuserid, $upi);
                $ins->execute();
                // capture insert id (sl)
                $last_insert_sl = $conn->insert_id;
                $ins->close();
            } else {
                // fallback raw query
                $sqlIns = "INSERT INTO phonepe_tokens (user_token, phoneNumber, userId, token, refreshToken, name, device_data, user_id, merchant_upi)
                        VALUES ('".$conn->real_escape_string($user_token)."', '".$conn->real_escape_string($phoneNumber)."', '".intval($userId)."', '".$conn->real_escape_string($token)."', '".$conn->real_escape_string($refreshToken)."', '".$conn->real_escape_string($name)."', '".$conn->real_escape_string($device_datar)."', ".intval($bbbyteuserid).", '".$conn->real_escape_string($upi)."')";
                $conn->query($sqlIns);
                $last_insert_sl = $conn->insert_id;
            }
        } else {
            // no $conn - try setXbyY, then attempt to select last inserted via other means (less reliable)
            setXbyY("INSERT INTO phonepe_tokens (user_token, phoneNumber, userId, token, refreshToken, name, device_data, user_id, merchant_upi) VALUES ('".$user_token."', '".$phoneNumber."', '".intval($userId)."', '".$token."', '".$refreshToken."', '".$name."', '".$device_datar."', ".intval($bbbyteuserid).", '".$upi."')");
            // can't reliably get insert id without $conn
            $last_insert_sl = 0;
        }

        // 3.a) Ensure merchant status in phonepe_tokens is set to Active
        $statusSet = false;
        if(isset($conn) && $conn && $last_insert_sl && intval($last_insert_sl) > 0){
            // Preferred: update by sl
            $statusSet = setTokenStatusBySl($conn, intval($last_insert_sl), 'Active');
        }

        if(!$statusSet && isset($conn) && $conn){
            // fallback: try by user_token + phoneNumber + merchant_upi (most recent)
            $statusSet = setTokenStatusFallback($conn, $user_token, $phoneNumber, $upi, 'Active');
        }

        // 4) Prepare values for store_id insertion/update:
        // unitId = users.name, roleName = users.role, groupValue = merchant_id
        $picked_unitId = '';
        $picked_roleName = '';
        $picked_groupValue = '';
        $picked_groupId = '';

        // First try to get user_name and user_role from POST (send-otp forwarded)
        $user_name = (isset($_POST['user_name']) ? sanitizeInput($_POST['user_name']) : '');
        $user_role = (isset($_POST['user_role']) ? sanitizeInput($_POST['user_role']) : '');

        // If not in POST, attempt to fetch from users table using user_token
        if ((empty($user_name) || empty($user_role)) && !empty($user_token) && isset($conn) && $conn) {
            $stmt = $conn->prepare("SELECT `name`, `role` FROM `users` WHERE `user_token` = ? LIMIT 1");
            if($stmt){
                $stmt->bind_param("s", $user_token);
                $stmt->execute();
                $stmt->bind_result($db_name, $db_role);
                if($stmt->fetch()){
                    if(empty($user_name)) $user_name = $db_name;
                    if(empty($user_role)) $user_role = $db_role;
                }
                $stmt->close();
            }
        }

        // Map merchant -> groupValue and user fields -> unitId/roleName
        if(!empty($merchant_id)){
            $picked_groupValue = $merchant_id;
            $picked_unitId = !empty($user_name) ? $user_name : $merchant_id; // fallback
            $picked_roleName = !empty($user_role) ? $user_role : '';
            $picked_groupId = '';
        } else {
            if (isset($b->{'userGroupNamespace'}->{'All'}) && is_array($b->{'userGroupNamespace'}->{'All'}) && count($b->{'userGroupNamespace'}->{'All'}) > 0) {
                $first = $b->{'userGroupNamespace'}->{'All'}[0];
                if(isset($first->{'userGroupNamespace'}->{'groupValue'})){
                    $picked_groupValue = (string)$first->{'userGroupNamespace'}->{'groupValue'};
                } elseif (isset($first->{'groupValue'})) {
                    $picked_groupValue = (string)$first->{'groupValue'};
                }
                if(isset($first->{'userGroupNamespace'}->{'groupId'})){
                    $picked_groupId = (string)$first->{'userGroupNamespace'}->{'groupId'};
                } elseif (isset($first->{'groupId'})) {
                    $picked_groupId = (string)$first->{'groupId'};
                }
                $apiUnit = isset($first->{'merchantName'}) ? (string)$first->{'merchantName'} : (isset($first->{'unitId'}) ? (string)$first->{'unitId'} : '');
                $picked_unitId = !empty($user_name) ? $user_name : $apiUnit;
                $apiRole = isset($first->{'roleName'}) ? (string)$first->{'roleName'} : '';
                $picked_roleName = !empty($user_role) ? $user_role : $apiRole;
            }
        }

        // 5) Insert/Update store_id table with mapping
        if(!empty($picked_groupValue) && !empty($user_token)){
            if(isset($conn) && $conn){
                $chk = $conn->prepare("SELECT sl FROM store_id WHERE user_token = ? LIMIT 1");
                if($chk){
                    $chk->bind_param("s", $user_token);
                    $chk->execute();
                    $chk->store_result();
                    $exists = ($chk->num_rows > 0);
                    $chk->bind_result($existing_sl);
                    $chk->fetch();
                    $chk->close();

                    if($exists){
                        $upd = $conn->prepare("UPDATE store_id SET unitId = ?, roleName = ?, groupValue = ?, groupId = ?, user_id = ? WHERE user_token = ?");
                        if($upd){
                            $uid_int = intval($bbbyteuserid);
                            $upd->bind_param("sssiis", $picked_unitId, $picked_roleName, $picked_groupValue, $picked_groupId, $uid_int, $user_token);
                            $upd->execute();
                            $upd->close();
                        } else {
                            $conn->query("UPDATE store_id SET unitId='".$conn->real_escape_string($picked_unitId)."', roleName='".$conn->real_escape_string($picked_roleName)."', groupValue='".$conn->real_escape_string($picked_groupValue)."', groupId='".$conn->real_escape_string($picked_groupId)."', user_id=".intval($bbbyteuserid)." WHERE user_token='".$conn->real_escape_string($user_token)."'");
                        }
                    } else {
                        $ins2 = $conn->prepare("INSERT INTO store_id (user_token, unitId, roleName, groupValue, groupId, user_id) VALUES (?,?,?,?,?,?)");
                        if($ins2){
                            $uid_int = intval($bbbyteuserid);
                            $ins2->bind_param("ssssii", $user_token, $picked_unitId, $picked_roleName, $picked_groupValue, $picked_groupId, $uid_int);
                            $ins2->execute();
                            $ins2->close();
                        } else {
                            $conn->query("INSERT INTO store_id (user_token, unitId, roleName, groupValue, groupId, user_id) VALUES ('".$conn->real_escape_string($user_token)."', '".$conn->real_escape_string($picked_unitId)."', '".$conn->real_escape_string($picked_roleName)."', '".$conn->real_escape_string($picked_groupValue)."', '".$conn->real_escape_string($picked_groupId)."', ".intval($bbbyteuserid).")");
                        }
                    }
                } else {
                    $conn->query("INSERT INTO store_id (user_token, unitId, roleName, groupValue, groupId, user_id) VALUES ('".$conn->real_escape_string($user_token)."', '".$conn->real_escape_string($picked_unitId)."', '".$conn->real_escape_string($picked_roleName)."', '".$conn->real_escape_string($picked_groupValue)."', '".$conn->real_escape_string($picked_groupId)."', ".intval($bbbyteuserid).")");
                }
            } else {
                setXbyY("INSERT INTO store_id (user_token, unitId, roleName, groupValue, groupId, user_id) VALUES ('".$user_token."', '".$picked_unitId."', '".$picked_roleName."', '".$picked_groupValue."', '".$picked_groupId."', ".intval($bbbyteuserid).")");
            }
        }

        // 6) Mark user connected and store merchant_id in users table
        if(!empty($user_token) && isset($conn) && $conn){
            $conn->query("UPDATE users SET phonepe_connected='Yes', merchant_id='".$conn->real_escape_string($merchant_id)."' WHERE user_token='".$conn->real_escape_string($user_token)."'");
        } else {
            setXbyY("UPDATE users SET phonepe_connected='Yes' WHERE user_token='".$user_token."'");
        }

        // 7) Final success
        echo '<script src="js/jquery-3.2.1.min.js"></script>';
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
        echo '<script>$("#loading_ajax").hide();
            Swal.fire({
                icon: "success",
                title: "Connected Successfully",
                text: "UPI and Merchant details updated.",
                showConfirmButton: true,
                confirmButtonText: "Ok",
                allowOutsideClick: false,
                allowEscapeKey: false
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "connect_merchant";
                }
            });
        </script>';
        exit();

    } else {
        // OTP failed
        echo '<script src="js/jquery-3.2.1.min.js"></script>';
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
        echo '<script>$("#loading_ajax").hide();
            Swal.fire({
                icon: "error",
                title: "Incorrect OTP, Please try again later",
                showConfirmButton: true,
                confirmButtonText: "Ok",
                allowOutsideClick: false,
                allowEscapeKey: false
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "connect_merchant";
                }
            });
        </script>';
        exit();
    }

} else {
    // direct access
    echo '<script src="js/jquery-3.2.1.min.js"></script>';
    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
    echo '<script>$("#loading_ajax").hide();
        Swal.fire({
            icon: "error",
            title: "Form Not Submitted!!",
            showConfirmButton: true,
            confirmButtonText: "Ok",
            allowOutsideClick: false,
            allowEscapeKey: false
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "connect_merchant";
            }
        });
    </script>';
    exit;
}
?>
