<?php
require_once '../php/users-session.php';

// التحقق من أن Session يعمل
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// إعدادات الاتصال بقاعدة البيانات
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "vistadb";

// إنشاء الاتصال
$conn = new mysqli($servername, $username, $password, $dbname);

// التحقق من الاتصال
if ($conn->connect_error) {
    die("فشل الاتصال بقاعدة البيانات: " . $conn->connect_error);
}

// استرجاع الدول
$countries_query = "SELECT * FROM countries ORDER BY name";
$countries_result = $conn->query($countries_query);

// استرجاع التصنيفات الرئيسية
$main_categories_query = "SELECT * FROM main_categories ORDER BY name";
$main_categories_result = $conn->query($main_categories_query);
?>

<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إضافة إعلان جديد</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <!-- Tajawal Font -->
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Tajawal', sans-serif;
            background-color: #f4f7f6;
            direction: rtl;
        }
        .form-container {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 30px;
            margin-top: 30px;
        }
        .form-step {
            margin-bottom: 20px;
        }
        .image-preview {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        .image-preview img {
            max-width: 150px;
            max-height: 150px;
            object-fit: cover;
            border-radius: 5px;
        }
        #map {
            height: 400px;
            width: 100%;
            margin-top: 15px;
        }
    </style>
</head>
<body>

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 form-container">
                <h2 class="text-center mb-4">إضافة إعلان جديد</h2>
                
                <form id="newAdForm" method="POST" enctype="multipart/form-data">
                    <!-- موقع الإعلان -->
                    <div class="form-step">
                        <h4>موقع الإعلان</h4>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">الدولة</label>
                                <select id="country" name="country" class="form-select" required>
                                    <option value="">اختر الدولة</option>
                                    <?php while($country = $countries_result->fetch_assoc()): ?>
                                        <option value="<?= $country['country_id'] ?>"><?= $country['name'] ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">المحافظة</label>
                                <select id="governorate" name="governorate" class="form-select" required disabled>
                                    <option value="">اختر المحافظة</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">المركز</label>
                                <select id="city" name="city" class="form-select" required disabled>
                                    <option value="">اختر المركز</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">العنوان التفصيلي</label>
                            <input type="text" class="form-control" name="address" id="address" required>
                        </div>
                        
                        <div id="map"></div>
                    </div>

                    <!-- التصنيفات -->
                    <div class="form-step">
                        <h4>التصنيفات</h4>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">التصنيف الرئيسي</label>
                                <select id="mainCategory" name="main_category" class="form-select" required>
                                    <option value="">اختر التصنيف الرئيسي</option>
                                    <?php 
                                    mysqli_data_seek($main_categories_result, 0);
                                    while($category = $main_categories_result->fetch_assoc()): ?>
                                        <option value="<?= $category['main_category_id'] ?>"><?= $category['name'] ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">التصنيف الفرعي</label>
                                <select id="subCategory" name="sub_category" class="form-select" required disabled>
                                    <option value="">اختر التصنيف الفرعي</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- تفاصيل الإعلان -->
                    <div class="form-step">
                        <h4>تفاصيل الإعلان</h4>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">السعر</label>
                                <input type="number" class="form-control" name="price" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">وصف الإعلان</label>
                                <textarea class="form-control" name="description" rows="4" required></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- وسائل التواصل -->
                    <div class="form-step">
                        <h4>معلومات التواصل</h4>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">رقم الهاتف</label>
                                <input type="tel" class="form-control" name="phone" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">رقم الواتساب</label>
                                <input type="tel" class="form-control" name="whatsapp">
                            </div>
                        </div>
                    </div>

<?php if (isset($_SESSION['user_id'])): ?>
    <div class="alert alert-info">
        <strong>مرحباً، <?= htmlspecialchars($_SESSION['user_name']) ?></strong>
        <p>نوع المستخدم: 
            <?= isset($_SESSION['user_role']) && $_SESSION['user_role'] == 1 ? 'وكيل' : 'مستخدم عادي' ?>
        </p>
    </div>
<?php else: ?>
    <div class="alert alert-warning">
        سيتم نشر الإعلان بدون تسجيل دخول
    </div>
<?php endif; ?>


                    <!-- الصور -->
                    <div class="form-step">
                        <h4>صور الإعلان</h4>
                        <div class="mb-3">
                            <label class="form-label">تحميل الصور (حتى 6 صور)</label>
                            <input type="file" class="form-control" name="images[]" multiple accept="image/*" max="6">
                            <div class="image-preview" id="imagePreview"></div>
                        </div>
                    </div>

                    <div class="text-center">
                        <button type="submit" class="btn btn-primary btn-lg">نشر الإعلان</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Google Maps JavaScript API -->
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&libraries=places"></script>

    <script>
        // Google Maps Initialization
        function initMap() {
            const map = new google.maps.Map(document.getElementById('map'), {
                center: {lat: 30.0444, lng: 31.2357},
                zoom: 6
            });

            const addressInput = document.getElementById('address');
            const autocomplete = new google.maps.places.Autocomplete(addressInput);
            
            autocomplete.addListener('place_changed', function() {
                const place = autocomplete.getPlace();
                if (place.geometry) {
                    map.setCenter(place.geometry.location);
                    map.setZoom(15);
                    
                    new google.maps.Marker({
                        map: map,
                        position: place.geometry.location
                    });
                }
            });
        }

        // Dynamic Location Dropdowns
        document.getElementById('country').addEventListener('change', function() {
            const countryId = this.value;
            const governorateSelect = document.getElementById('governorate');
            const citySelect = document.getElementById('city');

            // Reset subsequent dropdowns
            governorateSelect.innerHTML = '<option value="">اختر المحافظة</option>';
            citySelect.innerHTML = '<option value="">اختر المركز</option>';
            governorateSelect.disabled = true;
            citySelect.disabled = true;

            if (countryId) {
                fetch(`ads-get-governorates.php?country_id=${countryId}`)
                    .then(response => response.json())
                    .then(data => {
                        data.forEach(governorate => {
                            const option = document.createElement('option');
                            option.value = governorate.id;
                            option.textContent = governorate.name_ar;
                            governorateSelect.appendChild(option);
                        });
                        governorateSelect.disabled = false;
                    });
            }
        });

        document.getElementById('governorate').addEventListener('change', function() {
            const governorateId = this.value;
            const citySelect = document.getElementById('city');

            // Reset city dropdown
            citySelect.innerHTML = '<option value="">اختر المركز</option>';
            citySelect.disabled = true;

            if (governorateId) {
                fetch(`ads-get-centers.php?governorate_id=${governorateId}`)
                    .then(response => response.json())
                    .then(data => {
                        data.forEach(city => {
                            const option = document.createElement('option');
                            option.value = city.id;
                            option.textContent = city.name_ar;
                            citySelect.appendChild(option);
                        });
                        citySelect.disabled = false;
                    });
            }
        });

        // Dynamic Categories Dropdowns
        document.getElementById('mainCategory').addEventListener('change', function() {
            const mainCategoryId = this.value;
            const subCategorySelect = document.getElementById('subCategory');

            // Reset sub category dropdown
            subCategorySelect.innerHTML = '<option value="">اختر التصنيف الفرعي</option>';
            subCategorySelect.disabled = true;

            if (mainCategoryId) {
                fetch(`ads-get-subcategories.php?main_category_id=${mainCategoryId}`)
                    .then(response => response.json())
                    .then(data => {
                        data.forEach(subCategory => {
                            const option = document.createElement('option');
                            option.value = subCategory.id;
                            option.textContent = subCategory.name;
                            subCategorySelect.appendChild(option);
                        });
                        subCategorySelect.disabled = false;
                    });
            }
        });

        // Image Preview
        document.querySelector('input[name="images[]"]').addEventListener('change', function(event) {
            const imagePreview = document.getElementById('imagePreview');
            imagePreview.innerHTML = ''; // Clear previous previews

            Array.from(this.files).slice(0, 6).forEach(file => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    imagePreview.appendChild(img);
                }
                reader.readAsDataURL(file);
            });
        });

        // Initialize Google Maps
        google.maps.event.addDomListener(window, 'load', initMap);
    </script>
</body>
</html>

<?php $conn->close(); ?>