<?php
// connect_merchant.php
// Replace your current file with this. Assumptions:
// - header.php sets session_start(), $conn (mysqli) and $userdata array (with user_token, bharatpe_connected etc.)

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

// Start session if not already
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// -------------- Helpers --------------
function safeTrim($v) {
    return is_string($v) ? trim($v) : $v;
}
function strContains(string $mainString, string $substring): bool {
    return strpos($mainString, $substring) !== false;
}

// -------------- BharatPe transactions fetcher --------------
function bharatpe_trans($merchantId, $token, $cookie) {
    $fromDate = date('Y-m-d', strtotime('-2 days'));
    $toDate = date('Y-m-d');

    $url = 'https://payments-tesseract.bharatpe.in/api/v1/merchant/transactions'
        . '?module=PAYMENT_QR&merchantId=' . urlencode($merchantId)
        . '&sDate=' . urlencode($fromDate) . '&eDate=' . urlencode($toDate);

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPHEADER => [
            'token: ' . $token,
            'user-agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36',
            'Cookie: ' . $cookie
        ],
    ]);

    $response = curl_exec($curl);
    $curlErr = curl_error($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    if ($curlErr) {
        return ['success' => false, 'error' => 'CURL_ERROR', 'message' => $curlErr, 'http_code' => $httpCode];
    }

    $decoded = json_decode($response, true);
    if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) {
        return ['success' => false, 'error' => 'INVALID_JSON', 'raw' => $response, 'http_code' => $httpCode];
    }

    return ['success' => true, 'http_code' => $httpCode, 'data' => $decoded];
}

// -------------- Proxy for OTP send/verify (verbose) --------------
if (isset($_GET['action']) && in_array($_GET['action'], ['send','verify'])) {
    header('Content-Type: application/json; charset=utf-8');

    $action = $_GET['action'];
    $mobile = isset($_GET['mobile']) ? rawurlencode($_GET['mobile']) : '';
    $uuid   = isset($_GET['uuid']) ? rawurlencode($_GET['uuid']) : '';
    $otp    = isset($_GET['otp']) ? rawurlencode($_GET['otp']) : '';
    $token  = isset($_GET['token']) ? rawurlencode($_GET['token']) : '';

    $externalBase = 'https://vrlpay.in/auth/connectHelp/bharatpe.php';
    $qs = "action={$action}&mobile={$mobile}";
    if ($action === 'verify') {
        $qs .= "&uuid={$uuid}&otp={$otp}&token={$token}";
    }
    $externalUrl = $externalBase . '?' . $qs;

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $externalUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_USERAGENT => 'PHP-curl-proxy/1.0'
    ]);
    $resp = curl_exec($ch);
    $curlErr = curl_error($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    curl_close($ch);

    if ($curlErr) {
        echo json_encode([
            'success' => false,
            'stage' => 'curl_error',
            'message' => 'CURL error while calling external service',
            'curl_error' => $curlErr,
            'http_code' => $http,
            'url' => $externalUrl
        ]);
        exit;
    }

    $parsed = json_decode($resp, true);
    if ($parsed === null) {
        echo json_encode([
            'success' => false,
            'stage' => 'invalid_json',
            'message' => 'External service returned non-JSON response',
            'http_code' => $http,
            'content_type' => $contentType,
            'raw' => substr($resp, 0, 2000),
            'url' => $externalUrl
        ]);
        exit;
    }

    // forward parsed response plus debug info
    $parsed['__proxy_http_code'] = $http;
    $parsed['__proxy_url'] = $externalUrl;
    echo json_encode($parsed);
    exit;
}

// -------------- POST verifyotp handler (final submission) --------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verifyotp'])) {

    $bbbyteuserid = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : 0;
    $bbytebharatpeuserid = isset($userdata['user_token']) ? safeTrim($userdata['user_token']) : '';

    $bharatpe_mobile        = safeTrim($_POST['bharatpe_mobile'] ?? '');
    $bbytebharatpeusermid   = safeTrim($_POST['MID'] ?? '');
    $bbytebharatpeusertoken = safeTrim($_POST['token'] ?? '');
    $bbytebharatpeusercookie= safeTrim($_POST['cookie'] ?? '');
    $bharatpeupiid          = safeTrim($_POST['upiid'] ?? '');

    $bbytebharatpestatus = false;

    if (empty($bbytebharatpeusermid) || empty($bbytebharatpeusertoken)) {
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
        echo '<script>Swal.fire("Error","Missing MID or token","error").then(()=>{window.location="connect_merchant";});</script>';
        exit;
    }

    $apiResp = bharatpe_trans($bbytebharatpeusermid, $bbytebharatpeusertoken, $bbytebharatpeusercookie);

    if (!isset($apiResp['success']) || $apiResp['success'] !== true) {
        $msg = 'Unable to verify with BharatPe API.';
        if (isset($apiResp['error'])) $msg .= ' (' . $apiResp['error'] . ')';
        if (isset($apiResp['message'])) $msg .= ' - ' . $apiResp['message'];

        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
        echo '<script>Swal.fire("Error","'.htmlspecialchars($msg, ENT_QUOTES).'","error").then(()=>{window.location="connect_merchant";});</script>';
        exit;
    }

    $responseData = $apiResp['data'] ?? [];

    if (isset($responseData['message']) && $responseData['message'] === 'SUCCESS'
        && isset($responseData['status']) && $responseData['status'] === true) {

        if (!empty($responseData['data']['transactions']) && is_array($responseData['data']['transactions'])) {
            $transactions = $responseData['data']['transactions'];
            foreach ($transactions as $transaction) {
                if (isset($transaction['type']) && $transaction['type'] === 'PAYMENT_RECV' && isset($transaction['payeeIdentifier'])) {
                    $bharatUpi = strtolower(trim($transaction['payeeIdentifier']));
                    $inputUpi  = strtolower(trim($bharatpeupiid));
                    if ($inputUpi !== '' && (strContains($inputUpi, $bharatUpi) || strContains($bharatUpi, $inputUpi))) {
                        $bbytebharatpestatus = true;
                        break;
                    }
                }
            }
        } else {
            // no transactions array present — previous logic treated as success
            $bbytebharatpestatus = true;
        }
    } else {
        $bbytebharatpestatus = false;
    }

    if ($bbytebharatpestatus === true) {
        // check existing record
        $stmt = $conn->prepare("SELECT id FROM bharatpe_tokens WHERE user_token = ? AND phoneNumber = ? LIMIT 1");
        $stmt->bind_param("ss", $bbytebharatpeuserid, $bharatpe_mobile);
        $stmt->execute();
        $stmt->store_result();
        $exists = $stmt->num_rows > 0;
        $stmt->close();

        if ($exists) {
            $up = $conn->prepare("UPDATE bharatpe_tokens SET merchantId=?, token=?, status='Active', Upiid=?, user_id=?, cookie=? WHERE user_token=? AND phoneNumber=?");
            $up->bind_param("sssssss", $bbytebharatpeusermid, $bbytebharatpeusertoken, $bharatpeupiid, $bbbyteuserid, $bbytebharatpeusercookie, $bbytebharatpeuserid, $bharatpe_mobile);
            $ok = $up->execute();
            $up->close();
        } else {
            $ins = $conn->prepare("INSERT INTO bharatpe_tokens (user_token, phoneNumber, merchantId, token, status, Upiid, user_id, cookie) VALUES (?, ?, ?, ?, 'Active', ?, ?, ?)");
            $ins->bind_param("sssssss", $bbytebharatpeuserid, $bharatpe_mobile, $bbytebharatpeusermid, $bbytebharatpeusertoken, $bharatpeupiid, $bbbyteuserid, $bbytebharatpeusercookie);
            $ok = $ins->execute();
            $ins->close();
        }

        if (isset($ok) && $ok) {
            $u = $conn->prepare("UPDATE users SET bharatpe_connected='Yes' WHERE user_token = ?");
            $u->bind_param("s", $bbytebharatpeuserid);
            $u->execute();
            $u->close();

            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
            echo '<script>$("#loading_ajax").hide(); Swal.fire({icon:"success", title:"Congratulations! Your Bharatpe Hasbeen Connected Successfully!", allowOutsideClick:false}).then(()=>{window.location="connect_merchant";});</script>';
            exit;
        } else {
            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
            echo '<script>$("#loading_ajax").hide(); Swal.fire({icon:"error", title:"Please Try Again Later!!"}).then(()=>{window.location="connect_merchant";});</script>';
            exit;
        }
    } else {
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
        echo '<script>$("#loading_ajax").hide(); Swal.fire({icon:"error", title:"Invalid BharatPe Details!!"}).then(()=>{window.location="connect_merchant";});</script>';
        exit;
    }
} // end verifyotp

// -------------- POST Verify flow (start OTP process) --------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['Verify'])) {
    $bharatpe_mobile = safeTrim($_POST['bharatpe_mobile'] ?? '');

    // check existing active token for this phone
    $ixcheck = false;
    if (!empty($bharatpe_mobile)) {
        $check = $conn->prepare("SELECT id FROM bharatpe_tokens WHERE phoneNumber = ? AND status = 'Active' LIMIT 1");
        $check->bind_param("s", $bharatpe_mobile);
        $check->execute();
        $check->store_result();
        $ixcheck = $check->num_rows > 0;
        $check->close();
    }

    if (isset($userdata['bharatpe_connected']) && $userdata['bharatpe_connected'] === "Yes" && $ixcheck) {
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
        echo '<script>$("#loading_ajax").hide(); Swal.fire({icon:"error", title:"Merchant Already Connected !!"}).then(()=>{window.location="connect_merchant";});</script>';
        exit;
    }

    // Render JS that triggers server-side proxy to send OTP, then prompts for OTP
    ?>
    <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Connect BharatPe</title>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    </head>
    <body>
    <script>
    const mobile = "<?php echo htmlspecialchars($bharatpe_mobile, ENT_QUOTES); ?>";

    function sendOtp() {
        fetch("<?php echo basename(__FILE__); ?>?action=send&mobile=" + encodeURIComponent(mobile))
            .then(res => res.json())
            .then(data => {
                if (data.success === false) {
                    let errMsg = data.message || 'Failed to send OTP';
                    if (data.curl_error) errMsg += '\nCURL Error: ' + data.curl_error;
                    if (data.http_code) errMsg += '\nHTTP Code: ' + data.http_code;
                    if (data.raw) errMsg += '\nResponse snippet: ' + data.raw.substring(0,500);
                    Swal.fire("Failed", errMsg, "error");
                    return;
                }

                // Detect uuid/token in response
                const uuid = data.uuid || (data.data && data.data.uuid) || '';
                const token = data.token || (data.data && data.data.token) || '';
                // If success but no uuid/token, still pass empty values (external may return other structure)
                promptOtp(uuid, token);
            })
            .catch(err => {
                console.error(err);
                Swal.fire("Error", "Network error while sending OTP: " + err.message, "error");
            });
    }

    function promptOtp(uuid, token) {
        Swal.fire({
            title: 'Enter OTP',
            input: 'text',
            inputLabel: 'OTP sent to your BharatPe number',
            inputPlaceholder: 'Enter 4-6 digit OTP',
            inputAttributes: { maxlength: 6, autocapitalize: 'off', autocorrect: 'off' },
            showCancelButton: false,
            confirmButtonText: 'Verify OTP',
            preConfirm: (otp) => {
                if (!otp) {
                    Swal.showValidationMessage('Please enter the OTP');
                    return false;
                }
                return fetch("<?php echo basename(__FILE__); ?>?action=verify&uuid=" + encodeURIComponent(uuid) + "&otp=" + encodeURIComponent(otp) + "&mobile=" + encodeURIComponent(mobile) + "&token=" + encodeURIComponent(token))
                    .then(res => res.json())
                    .then(response => {
                        if (!response.success) {
                            throw new Error(response.message || 'OTP verification failed');
                        }
                        return response;
                    })
                    .catch(err => {
                        Swal.showValidationMessage(err.message || 'Verification failed');
                    });
            }
        }).then(result => {
            if (result.isConfirmed && result.value) {
                const data = result.value;
                const cookie = data.cookie_text || (data.data && data.data.cookie_text) || '';
                const merchant_id = data.merchant_id || (data.data && data.data.merchant_id) || '';
                const token = data.token || (data.data && data.data.token) || '';

                Swal.fire({
                    title: 'Bharatpe UPI Settings',
                    html: `
                        <form id="bharatpeForm" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" class="mb-2">
                            <div class="row" id="merchant">
                                <div class="col-md-12 mb-2">
                                    <label>Merchant Mobile</label>
                                    <input type="text" name="bharatpe_mobile" class="form-control" value="${mobile}" readonly required>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label>Enter Merchant ID</label>
                                    <input type="text" name="MID" class="form-control" value="${merchant_id}" readonly required>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label>Enter BharatPe Cookie</label>
                                    <textarea name="cookie" class="form-control" readonly required>${cookie}</textarea>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label>Enter BharatPe Token</label>
                                    <input type="text" name="token" class="form-control" value="${token}" readonly required>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label>BharatPe UPI Id</label>
                                    <input type="text" name="upiid" class="form-control" placeholder="Enter BharatPe UPI Id" required>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <button type="submit" name="verifyotp" class="btn btn-primary btn-block mt-2">Verify BharatPe</button>
                                </div>
                            </div>
                        </form>
                    `,
                    showCancelButton: false,
                    showConfirmButton: false,
                    allowOutsideClick: false,
                    allowEscapeKey: false
                });
            }
        });
    }

    window.onload = function() {
        sendOtp();
    };
    </script>
    <style>
        .swal2-content textarea { min-height: 80px; }
    </style>
    </body>
    </html>
    <?php
    exit;
} // end Verify flow

// Default: ask user to start flow
echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
echo '<script>$("#loading_ajax").hide(); Swal.fire({icon:"info", title:"Please start merchant connect flow.", text:"Redirecting..." }).then(()=>{ window.location="connect_merchant"; });</script>';
exit;
