<?php
session_start();
@include('./includes/config.php');
$encodedPhone = $_GET['phone'] ?? '';

if (!$encodedPhone) {
    echo "<script>
        alert('❌ Mobile number missing!');
        window.location.href = 'login.php';
    </script>";
    exit;
}

$phone = base64_decode($encodedPhone, true);

if (!$phone || !preg_match('/^[0-9]{10}$/', $phone)) {
    echo "<script>
        alert('❌ Invalid or malformed phone number!');
        window.location.href = 'login.php';
    </script>";
    exit;
}

$userQuery = mysqli_query($tng_conn, "SELECT name, type FROM users WHERE phone='$phone'");
if (!$userQuery || mysqli_num_rows($userQuery) == 0) {
   echo "<script>
        alert('❌ No user found with this number!');
        window.location.href = 'login.php';
    </script>";
    exit;
}

$user = mysqli_fetch_assoc($userQuery);
$userName = $user['name'] ?? 'User';
$userType = $user['type'] ?? '';

$regFee = 0;
if ($userType == "retailer") {
    $regFee = XyZ_val('ret_reg_fee');
} elseif ($userType == "distributor") {
    $regFee = XyZ_val('dist_reg_fee');
} else {
    $regFee = 999;
}


if (isset($_GET['check_paytm']) && $_GET['check_paytm'] == '1') {
    $encodedAppNo = $_GET['app_no'] ?? '';
    
    if ($encodedAppNo) {
        $application_no = base64_decode($encodedAppNo, true);
        
        $url = "https://" . JkL_get('paymentapi', 'gateway_Url') . "/bharatpaygateway_verification?type=paytm&application_no=" . urlencode($application_no) . "&apikey=" . urlencode(JkL_get('paymentapi', 'gateway_apikey'));
        $res = curl_get($url, 20);
        $data = json_decode($res['response'], true);
        
        if (is_array($data) && isset($data['Message']) && $data['Message'] === 'Success' && isset($data['status']) && $data['status'] === 'SUCCESS') {
           
            $payerName = $data['payerName'] ?? 'QR Payment';
            $payerHandle = $data['payerHandle'] ?? 'QR';
            $txnAmount = $data['amount'];
            $utr = $data['utr'];
            $datetime = date("Y-m-d H:i:s");

            
            $checkTxn = mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM wallet WHERE BANKTXNID = '$utr' AND phone = '$phone'");
            $txnExists = mysqli_fetch_assoc($checkTxn)['cnt'] > 0;

            if (!$txnExists) {
               
                mysqli_query($tng_conn, "INSERT INTO wallet (phone, BANKTXNID, amount, RESPMSG, PAYMENTMODE, status, txn_date) 
                    VALUES('$phone', '$utr', '$txnAmount', '$payerName', 'UPI', 'success', '$datetime')");
                
                
                mysqli_query($tng_conn, "UPDATE users SET status='1' WHERE phone='$phone'");
            }

            
            echo "<!DOCTYPE html>
            <html>
            <head>
                <title>Payment Success</title>
                <meta http-equiv='refresh' content='2;url=login.php'>
                <style>
                    body { font-family: Arial; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
                    .success-box { background: white; padding: 30px; border-radius: 15px; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
                </style>
            </head>
            <body>
                <div class='success-box'>
                    <h1 style='color: green;'>✅ Payment Successful!</h1>
                    <p>Your account has been activated successfully.</p>
                    <p>Redirecting to login page...</p>
                </div>
                <script>
                    setTimeout(() => {
                        alert('✅ Payment Successful!\\\\nYour account is now activated.');
                        window.location.href = 'login.php';
                    }, 100);
                </script>
            </body>
            </html>";
            exit;
        } else {
            
            $encodedPhoneParam = base64_encode($phone);
            $encodedAppNoParam = base64_encode($application_no);
            header("Refresh: 5; url=payment.php?phone=$encodedPhoneParam&check_paytm=1&app_no=$encodedAppNoParam");
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_payment'])) {
    $type = $_POST['type'] ?? '';
    $application_no = $_POST['application_no'] ?? '';
    $utr = $_POST['utr'] ?? '';

    if (!$type || !$application_no || !$utr) {
        echo "<script>alert('Please enter UTR number'); window.history.back();</script>";
        exit();
    }

    $url = "https://" . JkL_get('paymentapi', 'gateway_Url') . "/bharatpaygateway_verification?type=" . urlencode($type) . "&application_no=" . urlencode($application_no) . "&utr=" . urlencode($utr) . "&apikey=" . urlencode(JkL_get('paymentapi', 'gateway_apikey'));

    $res = curl_get($url, 20);
    $data = json_decode($res['response'], true);

    if (isset($data['error'])) {
        echo "<script>
            alert('Payment Failed: " . addslashes($data['error']) . "');
            window.history.back();
        </script>";
        exit();
    } elseif (is_array($data) && isset($data['Message']) && $data['Message'] === 'Success' && isset($data['status']) && $data['status'] === 'SUCCESS') {
        $payerName = $data['payerName'] ?? 'QR Payment';
        $payerHandle = $data['payerHandle'] ?? 'QR';
        $txnAmount = $data['amount'];
        $utr = $data['utr'];
        $datetime = date("Y-m-d H:i:s");

        
        $checkTxn = mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM wallet WHERE BANKTXNID = '$utr' AND phone = '$phone'");
        $txnExists = mysqli_fetch_assoc($checkTxn)['cnt'] > 0;

        if (!$txnExists) {
           
            mysqli_query($tng_conn, "INSERT INTO wallet (phone, BANKTXNID, amount, RESPMSG, PAYMENTMODE, status, txn_date) 
                VALUES('$phone', '$utr', '$txnAmount', '$payerName', 'UPI', 'success', '$datetime')");
            
            
            mysqli_query($tng_conn, "UPDATE users SET status='1' WHERE phone='$phone'");
        }

        echo "<script>
            alert('✅ Payment Successful!\\\\nYour account is now activated.\\\\nUTR: $utr\\\\nPayer: $payerName');
            window.location.href = 'login.php';
        </script>";
        exit();
    } else {
        echo "<script>
            alert('Transaction failed. Please check your UTR number or try again later.');
            window.history.back();
        </script>";
        exit();
    }
}

if (!isset($_GET['check_paytm']) || $_GET['check_paytm'] != '1') {
    $url = "https://" . JkL_get('paymentapi', 'gateway_Url') . "/qr_verification?amount=" . urlencode($regFee) . "&apikey=" . urlencode(JkL_get('paymentapi', 'gateway_apikey'));
    $res = curl_get($url, 20);
    $qrData = json_decode($res['response'], true);
} else {
    $qrData = $_SESSION['qr_data'] ?? [];
}

if (isset($qrData['error']) && !isset($_GET['check_paytm'])) {
    $errorMsg = $qrData['error'] ?? 'Unknown error during QR generation.';
    die("<div style='color:red;font-weight:bold;text-align:center;margin-top:20px;'>❌ QR Generation Failed: $errorMsg</div>");
}

if (!is_array($qrData) || !isset($qrData['Message']) || $qrData['Message'] !== 'Success') {
    die("<div style='color:red;font-weight:bold;text-align:center;margin-top:20px;'>❌ Invalid response from payment gateway</div>");
}

if (!isset($_GET['check_paytm'])) {
    $_SESSION['qr_data'] = $qrData;
    $_SESSION['qr_amount'] = $regFee;
    $_SESSION['activation_phone'] = $phone;
}

if ($qrData['type'] === "paytm" && !isset($_GET['check_paytm'])) {
    $encodedPhoneParam = base64_encode($phone);
    $encodedAppNoParam = base64_encode($qrData['application_no']);
    header("Refresh: 3; url=payment.php?phone=$encodedPhoneParam&check_paytm=1&app_no=$encodedAppNoParam");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment - Account Activation</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="./template/tngweb/assets/css/payment-extended.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-credit-card"></i> Complete Payment</h1>
            <p>Activate Your Account</p>
        </div>
        
        <div class="content">
            <div class="user-info">
                <h2>Hi, <?php echo $userName; ?>! 👋</h2>
                <p>Mobile: <strong><?php echo $phone; ?></strong></p>
                <p>Account Type: <strong><?php echo ucfirst($userType); ?></strong></p>
            </div>
            
            <div class="amount">
                ₹<?php echo $regFee; ?>
            </div>
            
            <div class="qr-container">
                <img src="<?php echo $qrData['qr']; ?>" class="qr-image" alt="QR Code">
            </div>
            
            <div class="payment-method">
                <i class="fas fa-info-circle"></i> 
                Payment Method: <strong><?php echo strtoupper($qrData['type']); ?></strong>
            </div>
            
            <?php if ($qrData['type'] === "paytm"): ?>
                <?php if (isset($_GET['check_paytm'])): ?>
                    <div class="status checking">
                        <i class="fas fa-sync-alt fa-spin"></i> 
                        Checking Payment Status...
                        <br>
                        
                    </div>
                <?php else: ?>
                    <div class="status pending">
                        <i class="fas fa-hourglass-half"></i> 
                        Starting payment verification...
                    </div>
                <?php endif; ?>
            <?php else: ?>
                <div class="status pending">
                    <i class="fas fa-mobile-alt"></i> 
                    Scan QR code to complete payment
                </div>
            <?php endif; ?>
            
            <?php if ($qrData['type'] === "bharatpay"): ?>
                <div class="utr-section">
                    <h3>
                        <i class="fas fa-exclamation-triangle"></i> 
                        UTR Number Required
                    </h3>
                    <p style="color: #856404; margin-bottom: 15px; font-size: 14px; line-height: 1.5;">
                        After completing the payment, please enter the <strong>UTR number</strong> 
                        from your bank transaction to verify your payment.
                    </p>
                    <form method="POST" action="">
                        <div class="input-group">
                            <i class="fas fa-receipt"></i>
                            <input type="text" name="utr" placeholder="Enter UTR Number" required 
                                   minlength="8" maxlength="30">
                        </div>
                        <input type="hidden" name="type" value="bharatpay">
                        <input type="hidden" name="application_no" value="<?php echo $qrData['application_no']; ?>">
                        <input type="hidden" name="verify_payment" value="1">
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-check-circle"></i> Verify Payment
                        </button>
                    </form>
                </div>
            <?php endif; ?>
            
            <a href="login.php" class="btn btn-secondary">
                <i class="fas fa-key"></i> Back to Login
            </a>
            
            <div class="login-link">
                <a href="login.php"><i class="fas fa-arrow-left"></i> Return to Login Page</a>
            </div>
        </div>
    </div>
</body>
</html>