
<?php
    // Fallbacks
    $networks = $networks ?? ['Airtel', 'Tigo', 'Halopesa', 'Azampesa'];
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <title>Nunua Vocha ya WiFi - <?php echo e($router->name ?? 'BlueBando'); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">

    <style>
        :root {
          --primary-color: #007bff;
          --secondary-color: #6c757d;
          --success-color: #28a745;
          --danger-color: #dc3545;
        }
        * { box-sizing: border-box; }

        body {
          font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
          background-color: #f5f7fa;
          color: #333;
          margin: 0;
          padding: 0;
        }
        .payment-container {
          max-width: 420px;
          margin: 0 auto;
          padding: 16px 0 32px;
        }
        .page-title {
          font-size: 1.4rem;
          font-weight: bold;
          color: var(--primary-color);
          text-align: center;
          margin: 1.2rem 0 0.2rem 0;
        }
        .page-subtitle {
          text-align: center;
          font-size: .9rem;
          color: #777;
          margin-bottom: 1.4rem;
        }
        .payment-card {
          border-radius: 10px;
          box-shadow: 0 5px 18px rgba(0,0,0,0.13);
          background: #fff;
          border: 1px solid #eee;
          margin-bottom: 1.5rem;
          overflow: hidden;
        }
        .card-body {
          padding: 1.3rem;
        }
        .form-label {
          font-weight: 500;
          margin-bottom: 0.3rem;
          color: #444;
          font-size: 0.97rem;
          display: block;
        }
        .form-control, .form-select {
          width: 100%;
          height: 45px;
          border-radius: 8px;
          border: 1px solid #bbb;
          padding: 0.7rem 0.95rem;
          font-size: 1rem;
          margin-bottom: 10px;
          background: #fafbfc;
          transition: border-color 0.2s, background 0.2s;
        }
        .form-control:focus, .form-select:focus {
          outline: none;
          border-color: var(--primary-color);
          background: #fff;
        }
        .btn-pay {
          background: var(--primary-color);
          border: none;
          border-radius: 8px;
          color: #fff;
          font-size: 1.08rem;
          font-weight: 600;
          height: 45px;
          padding: 0.7rem;
          width: 100%;
          cursor: pointer;
          margin-top: 1rem;
          transition: background 0.18s, box-shadow 0.18s;
          box-shadow: 0 2px 8px rgba(0,123,255,0.07);
        }
        .btn-pay:hover {
          background: #0061c8;
          box-shadow: 0 5px 18px rgba(0,123,255,0.09);
        }
        .spinner-border {
          display: none;
          margin-left: 8px;
          width: 1.15em;
          height: 1.15em;
          border: 2px solid #fff;
          border-right-color: transparent;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          vertical-align: middle;
        }
        @keyframes spin {
          0% {transform: rotate(0);}
          100% {transform: rotate(360deg);}
        }
        .payment-gateways .form-check {
          margin-bottom: 0.3rem;
          margin-left: 2px;
          margin-top: 6px;
        }
        .form-check-label {
          margin-left: 7px;
          font-size: 1rem;
        }
        .gateway-desc {
          color: #777;
          font-size: 0.9em;
          margin-left: 2.1em;
          margin-top: -3px;
          margin-bottom: 4px;
          display: block;
        }
        #provider-row {
          display: block;
        }
        .alert {
          background: #ffd7d7;
          color: var(--danger-color);
          padding: 10px;
          border-radius: 8px;
          margin-bottom: 12px;
          font-size: 0.95rem;
        }
        .notice {
          font-size: 0.9rem;
          color: #777;
          margin-top: .2rem;
        }

        /* Modal */
        .modal {
          display:none;
          position:fixed;
          inset:0;
          background:rgba(0,0,0,0.3);
          z-index:20;
          align-items:center;
          justify-content:center;
        }
        .modal.show { display:flex; }
        .modal-content {
          background:#fff;
          border-radius:12px;
          padding:1.5rem 1.3rem;
          max-width:320px;
          width:90%;
          box-shadow:0 12px 32px rgba(0,0,0,0.15);
          text-align:center;
        }
        .modal-title {
          font-weight:600;
          margin-bottom:.4rem;
        }
        .modal-text {
          font-size:.95rem;
        }
    </style>
</head>
<body>
<div class="payment-container">

    <div class="page-title">Nunua Vocha ya WiFi</div>
    <?php if($router): ?>
        <div class="page-subtitle">
            Router: <strong><?php echo e($router->name); ?></strong>
        </div>
    <?php endif; ?>

    <div class="payment-card">
        <div class="card-body">
            <?php if(! $plans->count()): ?>
                <div class="alert">
                    Hakuna vifurushi vilivyowezeshwa kwa router hii kwa sasa.
                    Tafadhali wasiliana na mtoa huduma.
                </div>
            <?php else: ?>
            <form id="payment-form">
                
                <input type="hidden" name="router_id" id="router_id" value="<?php echo e($router->id ?? ''); ?>">

                
                <div class="mb-3" id="provider-row">
                    <label class="form-label" for="provider">Chagua Mtandao</label>
                    <select name="provider" id="provider" class="form-select">
                        <?php $__currentLoopData = $networks; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $net): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($net); ?>"><?php echo e($net); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                
                <div class="mb-3">
                    <label class="form-label" for="phone">Weka Namba ya Simu</label>
                    <input type="tel" class="form-control" name="phone" id="phone" placeholder="weka namba hapa" required>
                    <div class="notice">Mfano: 0745XXXXXXX au 745XXXXXXX (itabadilishwa kuwa 255... moja kwa moja).</div>
                </div>

                
                <div class="mb-3">
                    <label class="form-label" for="plan_id">Chagua Kifurushi</label>
                    <select name="plan_id" id="plan_id" class="form-select" required>
                        <?php $__currentLoopData = $plans; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $plan): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($plan->id); ?>">
                                <?php echo e($plan->name); ?> – <?php echo e(number_format($plan->price)); ?> <?php echo e($plan->currency ?? 'TZS'); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                
                <div class="mb-3 payment-gateways">
                    <div class="form-label">Bonyeza 'Lipa sasa' Kufanya malipo</div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" checked disabled>
                        <label class="form-check-label">AzamPay</label>
                        <span class="gateway-desc">Airtel, Tigo, Halopesa, Azampesa</span>
                    </div>
                </div>

                <button type="submit" class="btn-pay" id="submit-btn" <?php echo e($plans->count() ? '' : 'disabled'); ?>>
                    Lipa Sasa
                    <span class="spinner-border" id="btn-spinner"></span>
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>


<div class="modal" id="statusModal">
    <div class="modal-content">
        <div class="modal-title" id="modal-title">Inachakata malipo...</div>
        <div class="modal-text" id="modal-text">
            Tafadhali weka PIN yako kwenye simu kuthibitisha malipo.
        </div>
    </div>
</div>

<script>
(function () {
    const form       = document.getElementById('payment-form');
    if (!form) return;
    const submitBtn  = document.getElementById('submit-btn');
    const spinner    = document.getElementById('btn-spinner');
    const modal      = document.getElementById('statusModal');
    const modalTitle = document.getElementById('modal-title');
    const modalText  = document.getElementById('modal-text');
    const token      = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    function showModal(title, text) {
        modalTitle.textContent = title;
        modalText.textContent  = text;
        modal.classList.add('show');
    }
    function hideModal() {
        modal.classList.remove('show');
    }

    function normalisePhone(raw) {
        let phone = raw.replace(/[^\d]/g, '');
        if (phone.length === 10 && phone.startsWith('0')) {
            return '255' + phone.substring(1);
        } else if (phone.length === 12 && phone.startsWith('255')) {
            return phone;
        } else if (phone.length === 13 && phone.startsWith('+255')) {
            return '255' + phone.substring(4);
        } else if (phone.length === 9 && phone.startsWith('7')) {
            return '255' + phone;
        }
        return null;
    }

    form.addEventListener('submit', function (e) {
        e.preventDefault();

        const routerId = document.getElementById('router_id').value;
        const planId   = document.getElementById('plan_id').value;
        const provider = document.getElementById('provider').value;
        const rawPhone = document.getElementById('phone').value.trim();

        const msisdn = normalisePhone(rawPhone);
        if (!msisdn) {
            alert('Namba ya simu si sahihi. Tafadhali andika namba kamili mfano 0745XXXXXXX au 745XXXXXXX.');
            return;
        }

        submitBtn.disabled = true;
        spinner.style.display = 'inline-block';

        const payload = new URLSearchParams();
        payload.append('router_id', routerId);
        payload.append('plan_id', planId);
        payload.append('phone', msisdn);
        payload.append('network', provider);
        payload.append('gateway', 'azampay');
        payload.append('provider', provider);
        payload.append('_token', token);

        fetch("<?php echo e(url('/payment.php')); ?>", {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: payload
        })
        .then(res => res.json())
        .then(data => {
            submitBtn.disabled = false;
            spinner.style.display = 'none';

            if (!data || !data.success) {
                const msg = (data && data.message) || (data && data.error) || 'Malipo hayajakamilika.';
                alert(msg);
                return;
            }

            showModal(
                'Malipo yameanzishwa',
                'Tafadhali weka PIN yako kwenye simu kuthibitisha malipo. Ukimaliza, utapokea vocha kwenye SMS.'
            );

            // NEXT STEP (baadaye):
            // hapa tunaweza kuanza polling kwa order_id ili kuonyesha vocha live.
            console.log('Order created:', data);
        })
        .catch(err => {
            submitBtn.disabled = false;
            spinner.style.display = 'none';
            console.error(err);
            alert('Hitilafu ya seva au mtandao. Jaribu tena.');
        });
    });
})();
</script>
</body>
</html>
<?php /**PATH /var/www/blue/resources/views/payments/form.blade.php ENDPATH**/ ?>