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

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

// fallback sanitize if not exist
if (!function_exists('sanitizeInput')) {
    function sanitizeInput($data){
        return trim(htmlspecialchars($data, ENT_QUOTES));
    }
}

if(!isset($userdata) && isset($_SESSION['userdata'])){
    $userdata = $_SESSION['userdata'];
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Connect PhonePe - Send OTP</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>.container { max-width: 600px; margin-top: 40px; }</style>
</head>
<body>
<div class="container">
    <h3>Connect PhonePe</h3>
    <form method="POST" class="mt-4">
        <div class="form-group">
            <label for="phonepe_mobile">Phone Number</label>
            <input type="text" class="form-control" id="phonepe_mobile" name="phonepe_mobile" placeholder="Enter phone number" required>
        </div>

        <div class="form-group">
            <label for="merchant_id">Merchant ID</label>
            <input type="text" class="form-control" id="merchant_id" name="merchant_id" placeholder="Enter Merchant ID" required>
        </div>

        <div class="form-group">
            <label for="upi">UPI ID</label>
            <input type="text" class="form-control" id="upi" name="upi" placeholder="merchant@upi" required>
        </div>

        <button type="submit" name="Verify" class="btn btn-primary btn-block">Send OTP & Continue</button>
    </form>
</div>

<script src="js/jquery-3.2.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</body>
</html>

<?php
if(isset($_POST['Verify'])){

    if (isset($userdata['phonepe_connected']) && $userdata['phonepe_connected'] == "Yes"){
        echo '<script>
            Swal.fire({icon:"error", title:"Merchant Already Connected !!", confirmButtonText:"Ok"})
            .then(()=>{ window.location.href="connect_merchant"; });
        </script>';
        exit;
    }

    $no = sanitizeInput($_POST['phonepe_mobile']);
    $merchant_id = sanitizeInput($_POST['merchant_id']);
    $upi = sanitizeInput($_POST['upi']);

    // send OTP as before
    $sendotpresult = sentotp(1, $no, 0, 0, 0);
    echo $sendotpresult;

    $json0 = json_decode($sendotpresult, true);
    $otpSended = isset($json0["otpSended"]) ? $json0["otpSended"] : 'false';
    $phoneNumber = isset($json0["phoneNumber"]) ? $json0["phoneNumber"] : $no;
    $token = isset($json0["token"]) ? $json0["token"] : '';
    $device = isset($json0["device"]) ? $json0["device"] : '';

    if($otpSended == 'true'){
        // safe variables for SweetAlert
        $safe_no = htmlspecialchars($no, ENT_QUOTES);
        $safe_phoneNumber = htmlspecialchars($phoneNumber, ENT_QUOTES);
        $safe_token = htmlspecialchars($token, ENT_QUOTES);
        $safe_device = htmlspecialchars($device, ENT_QUOTES);
        $safe_user_token = isset($userdata['user_token']) ? htmlspecialchars($userdata['user_token'], ENT_QUOTES) : '';
        $safe_merchant = htmlspecialchars($merchant_id, ENT_QUOTES);
        $safe_upi = htmlspecialchars($upi, ENT_QUOTES);

        echo '<script>
            $("#loading_ajax").hide();
            Swal.fire({
                title: "OTP Sent!",
                text: "Please enter OTP, Merchant ID & UPI ID to verify.",
                icon: "success",
                confirmButtonText: "Ok",
                allowOutsideClick: false,
                allowEscapeKey: false
            }).then(()=>{ showOtpForm(); });

            function showOtpForm(){
                Swal.fire({
                    title: "Verify PhonePe Details",
                    html: `
                        <form id="phonepeForm" method="POST" action="phonepe_verify.php" class="mb-2">
                            <div class="row">
                                <div class="col-md-12 mb-2">
                                    <label>Enter OTP</label>
                                    <input type="number" name="otp" id="otp_field" placeholder="Enter OTP" class="form-control" required>
                                </div>

                                <div class="col-md-12 mb-2">
                                    <label>Merchant ID</label>
                                    <input type="text" name="merchant_id" id="merchant_id_field" value="'.$safe_merchant.'" placeholder="Enter Merchant ID" class="form-control" required>
                                </div>

                                <div class="col-md-12 mb-2">
                                    <label>UPI ID</label>
                                    <input type="text" name="upi" id="upi_field" value="'.$safe_upi.'" placeholder="merchant@upi" class="form-control" required>
                                </div>

                                <input type="hidden" name="number" value="'.$safe_no.'">
                                <input type="hidden" name="user_token" value="'.$safe_user_token.'">
                                <input type="hidden" name="no" value="'.$safe_phoneNumber.'">
                                <input type="hidden" name="otp_toekn" value="'.$safe_token.'">
                                <input type="hidden" name="device_data" value="'.$safe_device.'">

                                <div class="col-md-12 mb-2">
                                    <button type="submit" name="verifyotp" class="btn btn-primary btn-block mt-2">Verify & Connect</button>
                                </div>
                            </div>
                        </form>
                    `,
                    showCancelButton:false,
                    showConfirmButton:false,
                    allowOutsideClick:false,
                    allowEscapeKey:false
                });
            }
        </script>';
        exit;

    } else {
        echo '<script>
            Swal.fire({icon:"error", title:"OTP Error!", confirmButtonText:"Ok"})
            .then(()=>{ window.location.href="connect_merchant"; });
        </script>';
        exit;
    }
}
?>
