<!DOCTYPE html>
<html dir="rtl" lang="he">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>פאנל מתווכים - נדלני</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            direction: rtl;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            min-height: 100vh;
        }

        /* עמוד כניסה */
        .login-container {
            max-width: 500px;
            margin: 50px auto;
            padding: 30px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            text-align: center;
        }

        .login-header h1 {
            color: #007bff;
            margin-bottom: 10px;
            font-size: 28px;
        }

        .login-header h2 {
            color: #333;
            margin-bottom: 5px;
            font-size: 22px;
        }

        .login-header p {
            color: #666;
            font-size: 14px;
        }

        .special-banner {
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
            color: #333;
            padding: 10px;
            border-radius: 6px;
            margin: 15px 0;
            font-size: 12px;
            font-weight: bold;
        }

        .form-group {
            margin-bottom: 25px;
            text-align: right;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }

        .form-group input {
            width: 100%;
            padding: 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            text-align: center;
            font-weight: bold;
            transition: border-color 0.3s;
        }

        .form-group input:focus {
            outline: none;
            border-color: #007bff;
        }

        .btn-primary {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            border: none;
            padding: 15px 40px;
            border-radius: 8px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            width: 100%;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
        }

        .btn-primary:disabled {
            opacity: 0.7;
            transform: none;
            box-shadow: none;
        }

        /* דשבורד */
        .dashboard-header {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 25px;
            position: relative;
            overflow: hidden;
        }

        .dashboard-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -10%;
            width: 200px;
            height: 200px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            z-index: 1;
        }

        .dashboard-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            z-index: 2;
            flex-wrap: wrap;
        }

        .broker-details h1 {
            margin: 0 0 10px 0;
            font-size: 28px;
        }

        .broker-details h3 {
            margin: 0;
            color: rgba(255,255,255,0.9);
        }

        .broker-details p {
            margin: 5px 0;
            font-size: 14px;
            opacity: 0.8;
        }

        .stats-container {
            display: flex;
            gap: 15px;
        }

        .stat-card {
            text-align: center;
            background: rgba(255,255,255,0.2);
            padding: 15px 20px;
            border-radius: 10px;
        }

        .stat-card.credits {
            background: rgba(255,215,0,0.3);
            border: 2px solid rgba(255,215,0,0.5);
        }

        .stat-number {
            font-size: 24px;
            font-weight: bold;
            display: block;
        }

        .stat-number.credits {
            color: #ffd700;
        }

        .stat-label {
            font-size: 12px;
            opacity: 0.9;
        }

        .logout-btn {
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: white;
            padding: 8px 15px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
        }

        /* כלי בקרה */
        .controls {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .action-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .btn {
            border: none;
            padding: 10px 15px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: transform 0.2s;
        }

        .btn:hover {
            transform: translateY(-1px);
        }

        .btn-info { background: #17a2b8; color: white; }
        .btn-success { background: #28a745; color: white; }
        .btn-warning { background: #ffc107; color: #333; }
        .btn-purple { background: #6f42c1; color: white; }
        .btn-secondary { background: #6c757d; color: white; }

        .search-filters {
            display: grid;
            grid-template-columns: 1fr auto auto auto;
            gap: 15px;
            align-items: center;
        }

        .search-input, .filter-select {
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
        }

        .search-input {
            width: 100%;
        }

        /* נכסים */
        .properties-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
        }

        .property-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s, box-shadow 0.3s;
            border-right: 4px solid #007bff;
        }

        .property-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }

        .property-card.inactive {
            border-right-color: #dc3545;
            opacity: 0.8;
            background: #f8f9fa;
        }

        .property-image {
            width: 100%;
            height: 180px;
            object-fit: cover;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        .property-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .property-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin: 15px 0;
            font-size: 14px;
            color: #666;
        }

        .property-meta span {
            background: #f8f9fa;
            padding: 4px 8px;
            border-radius: 4px;
            white-space: nowrap;
        }

        .property-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-top: 15px;
        }

        .btn-action {
            padding: 8px 12px;
            font-size: 12px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            transition: all 0.2s;
            flex: 1;
            min-width: 80px;
            justify-content: center;
        }

        .btn-action:hover {
            transform: translateY(-1px);
        }

        /* הודעות סטטוס */
        .status-message {
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            font-weight: bold;
            margin-bottom: 20px;
        }

        .status-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .status-warning {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }

        /* טעינה */
        .loading {
            text-align: center;
            padding: 40px;
            background: white;
            border-radius: 12px;
            margin-bottom: 20px;
        }

        .spinner {
            display: inline-block;
            width: 30px;
            height: 30px;
            border: 4px solid #007bff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* מודאל */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            direction: rtl;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }

        .modal-header {
            text-align: center;
            margin-bottom: 20px;
        }

        .credits-display {
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            color: #333;
            text-align: center;
        }

        .platform-option {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12px;
            cursor: pointer;
            padding: 10px;
            border: 2px solid transparent;
            border-radius: 6px;
            transition: all 0.2s;
        }

        .platform-option:hover {
            border-color: #007bff;
            background: rgba(0,123,255,0.05);
        }

        .platform-info {
            display: flex;
            align-items: center;
        }

        .platform-info input {
            margin-left: 10px;
        }

        .credit-cost {
            background: #007bff;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: bold;
        }

        .modal-buttons {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 25px;
        }

        .btn-modal {
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
        }

        /* עמוד ריק */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .empty-icon {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.3;
        }

        /* רספונסיבי */
        @media (max-width: 768px) {
            .dashboard-info {
                flex-direction: column;
                gap: 20px;
                text-align: center;
            }

            .stats-container {
                justify-content: center;
            }

            .search-filters {
                grid-template-columns: 1fr;
                gap: 10px;
            }

            .properties-grid {
                grid-template-columns: 1fr;
            }

            .property-actions {
                flex-direction: column;
            }

            .btn-action {
                min-width: auto;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        
        <!-- שלב 1: עמוד כניסה -->
        <div id="loginSection">
            <div class="login-container">
                <!-- כותרת -->
                <div class="login-header">
                    <h1>🏠 נָדְלָנִי</h1>
                    <h2>כניסה למתווכים</h2>
                    <p>הזן את קוד המתווך שקיבלת מהמשרד</p>
                    <div class="special-banner">
                        ⭐ גישה למערכת הפרסום האוטומטית של נדלני ⭐
                    </div>
                </div>

                <!-- טופס כניסה -->
                <form id="loginForm" onsubmit="handleLogin(event)">
                    <div class="form-group">
                        <label for="brokerCode">🔑 קוד מתווך</label>
                        <input 
                            type="text" 
                            id="brokerCode" 
                            placeholder="הזן את קוד המתווך שלך (למשל: 11, 12, 18)"
                            required
                        >
                    </div>

                    <button type="submit" id="loginBtn" class="btn-primary">
                        🚀 כניסה למערכת
                    </button>
                </form>

                <!-- הודעות סטטוס -->
                <div id="loginStatus" style="display: none; margin-top: 20px;"></div>

                <!-- מידע נוסף -->
                <div style="margin-top: 30px; padding: 20px; background: #f8f9fa; border-radius: 8px; text-align: center;">
                    <h4 style="color: #333; margin-bottom: 15px;">💡 איך זה עובד?</h4>
                    <div style="font-size: 14px; color: #666; line-height: 1.6;">
                        <p>1️⃣ הזן את קוד המתווך שקיבלת</p>
                        <p>2️⃣ לחץ כניסה למערכת הפרסום</p>
                        <p>3️⃣ נוביל אותך לפאנל הניהול שלך</p>
                    </div>
                    
                    <div style="margin-top: 20px; padding: 15px; background: linear-gradient(135deg, #28a745 0%, #20c997 100%); color: white; border-radius: 8px; font-size: 13px;">
                        <strong>🚀 מערכת פרסום אוטומטית מתקדמת</strong><br>
                        <span style="font-size: 12px; opacity: 0.9;">פרסם בפייסבוק, לינקדאין ווואטסאפ בלחיצה אחת!</span>
                    </div>
                </div>

                <!-- תמיכה -->
                <div style="text-align: center; margin-top: 20px; font-size: 12px; color: #999;">
                    <p>זקוק לעזרה? צור קשר בוואטסאפ: <a href="https://wa.me/972525349977" target="_blank" style="color: #25D366; text-decoration: none; font-weight: bold;">💬 לחץ כאן</a></p>
                </div>
            </div>
        </div>

        <!-- שלב 2: דשבורד מתווך -->
        <div id="dashboardSection" style="display: none;">
            
            <!-- כותרת דשבורד -->
            <div class="dashboard-header">
                <div class="dashboard-info">
                    <div class="broker-details">
                        <h1>🏠 פאנל ניהול נכסים - נָדְלָנִי</h1>
                        <div id="brokerInfo">
                            <h3 id="brokerName">טוען...</h3>
                            <p>מתווך נדל"ן | מערכת פרסום אוטומטית</p>
                        </div>
                    </div>
                    
                    <div class="stats-container">
                        <div class="stat-card">
                            <span class="stat-number" id="propertiesCount">0</span>
                            <div class="stat-label">נכסים פעילים</div>
                        </div>
                        
                        <div class="stat-card credits">
                            <span class="stat-number credits" id="nadelaniCredits">0</span>
                            <div class="stat-label">⭐ ניקוד נדלני</div>
                        </div>
                    </div>
                    
                    <div>
                        <button onclick="logout()" class="logout-btn">
                            🚪 יציאה
                        </button>
                    </div>
                </div>
            </div>

            <!-- כלי בקרה -->
            <div class="controls">
                
                <!-- כפתורי פעולה -->
                <div class="action-buttons">
                    <button onclick="refreshData()" id="refreshBtn" class="btn btn-info">
                        <span id="refreshIcon">🔄</span> רענן נתונים
                    </button>
                    
                    <button onclick="toggleAllProperties()" id="toggleAllBtn" class="btn btn-success">
                        ⚡ הפעל הכל
                    </button>
                    
                    <button onclick="showBulkActions()" class="btn btn-warning">
                        🤖 פרסום אוטומטי
                    </button>
                    
                    <button onclick="showAutoPublishSettings()" class="btn btn-purple">
                        ⚙️ הגדרות אוטומציה
                    </button>
                </div>

                <!-- חיפוש וסינון -->
                <div class="search-filters">
                    <input 
                        type="text" 
                        id="searchInput" 
                        placeholder="🔍 חיפוש נכסים לפי שם, מיקום או תיאור..."
                        class="search-input"
                        oninput="searchProperties()"
                    >
                    
                    <select id="statusFilter" onchange="filterProperties()" class="filter-select">
                        <option value="all">כל הסטטוסים</option>
                        <option value="on">פעיל בלבד</option>
                        <option value="off">לא פעיל בלבד</option>
                    </select>
                    
                    <select id="categoryFilter" onchange="filterProperties()" class="filter-select">
                        <option value="all">כל הקטגוריות</option>
                        <option value="1">דירה</option>
                        <option value="15">טריפלקס</option>
                        <option value="16">יחידת דיור</option>
                    </select>
                    
                    <button onclick="toggleView()" id="viewToggle" class="btn btn-secondary">
                        📋 טבלה
                    </button>
                </div>
            </div>

            <!-- סטטוס טעינה -->
            <div id="loadingStatus" class="loading" style="display: none;">
                <div class="spinner"></div>
                <p style="margin-top: 15px; color: #666;">טוען נתונים...</p>
            </div>

            <!-- הודעות סטטוס -->
            <div id="dashboardStatus" style="display: none;"></div>

            <!-- רשימת נכסים -->
            <div id="propertiesList" class="properties-grid"></div>

        </div>

    </div>

    <!-- מודאל פרסום -->
    <div id="publishModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>📢 פרסום נכס אוטומטי</h3>
            </div>
            <div id="publishContent"></div>
            <div class="credits-display">
                <div style="font-size: 16px; font-weight: bold; margin-bottom: 5px;">⭐ ניקוד נדלני זמין</div>
                <div style="font-size: 24px; font-weight: bold;" id="modalCredits">0</div>
                <div style="font-size: 12px; margin-top: 5px;">נקודות לפרסום אוטומטי</div>
            </div>
            <div class="modal-buttons">
                <button onclick="closeModal()" class="btn-modal" style="background: #6c757d; color: white;">
                    ❌ ביטול
                </button>
                <button onclick="confirmPublish()" class="btn-modal" style="background: #28a745; color: white;">
                    🚀 פרסם עכשיו
                </button>
            </div>
        </div>
    </div>

    <script>
        // ===== הגדרות גלובליות =====
        const WEBHOOK_URL = 'https://hook.eu2.make.com/96rcexlj83qn94w3kavbl45alhozx2rx';
        
        let currentBroker = null;
        let allProperties = [];
        let filteredProperties = [];
        let currentView = 'cards';
        let publishingProperty = null;

        // ===== טעינה ראשונית =====
        document.addEventListener('DOMContentLoaded', function() {
            // בדיקה אם כבר מחובר
            const savedBrokerId = localStorage.getItem('broker_id');
            const loginTime = localStorage.getItem('login_time');
            
            if (savedBrokerId && loginTime) {
                const isLoginValid = (Date.now() - parseInt(loginTime)) < 24 * 60 * 60 * 1000;
                if (isLoginValid) {
                    document.getElementById('brokerCode').value = savedBrokerId;
                    showLoginStatus('נמצא קוד שמור. לחץ כניסה או הזן קוד חדש', 'warning');
                }
            }
        });

        // ===== פונקציות כניסה =====
        async function handleLogin(event) {
            event.preventDefault();
            
            const brokerCode = document.getElementById('brokerCode').value.trim();
            const loginBtn = document.getElementById('loginBtn');
            
            if (!brokerCode) {
                showLoginStatus('אנא הזן קוד מתווך', 'error');
                return;
            }

            // שינוי מצב הכפתור
            loginBtn.innerHTML = '⏳ בודק קוד...';
            loginBtn.disabled = true;

            try {
                // שליחה ל-Make לבדיקת הקוד
                const response = await fetch(WEBHOOK_URL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'verify_broker',
                        broker_code: brokerCode
                    })
                });

                const data = await response.json();

                if (data.success && data.broker) {
                    // שמירה ב-localStorage  
                    localStorage.setItem('broker_id', brokerCode);
                    localStorage.setItem('broker_data', JSON.stringify(data.broker));
                    localStorage.setItem('login_time', Date.now().toString());
                    
                    showLoginStatus('✅ קוד תקין! עובר לפאנל...', 'success');
                    
                    // מעבר לדשבורד
                    setTimeout(() => {
                        currentBroker = data.broker;
                        showDashboard();
                        loadBrokerData(brokerCode);
                    }, 1500);

                } else {
                    showLoginStatus(data.message || 'קוד מתווך שגוי או לא קיים', 'error');
                }

            } catch (error) {
                console.error('Error:', error);
                showLoginStatus('שגיאה בחיבור למערכת. אנא נסה שנית', 'error');
            } finally {
                // החזרת הכפתור למצב רגיל
                loginBtn.innerHTML = '🚀 כניסה למערכת';
                loginBtn.disabled = false;
            }
        }

        function showLoginStatus(message, type) {
            const statusDiv = document.getElementById('loginStatus');
            statusDiv.textContent = message;
            statusDiv.className = `status-message status-${type}`;
            statusDiv.style.display = 'block';
            
            if (type !== 'success') {
                setTimeout(() => {
                    statusDiv.style.display = 'none';
                }, 5000);
            }
        }

        // ===== פונקציות דשבורד =====
        function showDashboard() {
            document.getElementById('loginSection').style.display = 'none';
            document.getElementById('dashboardSection').style.display = 'block';
        }

        function showLogin() {
            document.getElementById('dashboardSection').style.display = 'none';
            document.getElementById('loginSection').style.display = 'block';
        }

        async function loadBrokerData(brokerId) {
            setLoading(true);
            
            try {
                const response = await fetch(WEBHOOK_URL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'get_broker_properties',
                        broker_id: brokerId
                    })
                });

                const data = await response.json();

                if (data.success) {
                    currentBroker = data.broker;
                    allProperties = data.properties || [];
                    filteredProperties = [...allProperties];

                    updateBrokerInfo();
                    displayProperties();
                    showDashboardStatus('נתונים נטענו בהצלחה', 'success');
                } else {
                    showDashboardStatus(data.message || 'שגיאה בטעינת הנתונים', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showDashboardStatus('שגיאה בחיבור למערכת', 'error');
            } finally {
                setLoading(false);
            }
        }

        function updateBrokerInfo() {
            if (!currentBroker) return;
            
            document.getElementById('brokerName').textContent = 
                `${currentBroker.first_name} ${currentBroker.last_name}`;
            
            const activeCount = allProperties.filter(p => p.status === 'on').length;
            document.getElementById('propertiesCount').textContent = activeCount;
            document.getElementById('nadelaniCredits').textContent = currentBroker.credits || 0;
        }

        function displayProperties() {
            const propertiesList = document.getElementById('propertiesList');
            
            if (filteredProperties.length === 0) {
                propertiesList.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-icon">🏠</div>
                        <h3>אין נכסים להצגה</h3>
                        <p>נכסים יופיעו כאן לאחר שיתווספו למערכת</p>
                    </div>
                `;
                return;
            }

            const propertiesHTML = filteredProperties.map(property => createPropertyCard(property)).join('');
            propertiesList.innerHTML = propertiesHTML;
        }

        function createPropertyCard(property) {
            const isActive = property.status === 'on';
            const statusClass = isActive ? '' : 'inactive';
            const statusText = isActive ? 'פעיל' : 'לא פעיל';
            
            return `
                <div class="property-card ${statusClass}">
                    <img src="${property.image || 'https://via.placeholder.com/350x180?text=אין+תמונה'}" 
                         alt="${property.title}" 
                         class="property-image"
                         onerror="this.src='https://via.placeholder.com/350x180?text=אין+תמונה'">
                    
                    <h3 class="property-title">${property.title}</h3>
                    
                    <div class="property-meta">
                        <span>📊 ${statusText}</span>
                        <span>📅 ${formatDate(property.created_at)}</span>
                        <span>🔢 נכס #${property.porp_id}</span>
                    </div>
                    
                    <div class="property-actions">
                        <button onclick="publishProperty('${property.porp_id}')" 
                                class="btn-action" 
                                style="background: #28a745; color: white;">
                            🚀 פרסם
                        </button>
                        
                        <button onclick="togglePropertyStatus('${property.porp_id}')" 
                                class="btn-action" 
                                style="background: ${isActive ? '#dc3545' : '#17a2b8'}; color: white;">
                            ${isActive ? '⏸️ עצור' : '▶️ הפעל'}
                        </button>
                        
                        <a href="${property.link}" 
                           target="_blank" 
                           class="btn-action" 
                           style="background: #6c757d; color: white; text-decoration: none;">
                            👁️ צפה
                        </a>
                    </div>
                </div>
            `;
        }

        // ===== פונקציות פרסום =====
        function publishProperty(propertyId) {
            publishingProperty = allProperties.find(p => p.porp_id === propertyId);
            
            if (!publishingProperty) {
                showDashboardStatus('נכס לא נמצא', 'error');
                return;
            }

            // הצגת מודאל פרסום
            document.getElementById('publishContent').innerHTML = `
                <h4>${publishingProperty.title}</h4>
                <p style="color: #666; margin: 10px 0;">בחר פלטפורמות לפרסום:</p>
                
                <div class="platform-option" onclick="togglePlatform('facebook')">
                    <div class="platform-info">
                        <input type="checkbox" id="platform_facebook" value="facebook">
                        <label for="platform_facebook">📘 פייסבוק</label>
                    </div>
                    <span class="credit-cost">2 נק'</span>
                </div>
                
                <div class="platform-option" onclick="togglePlatform('linkedin')">
                    <div class="platform-info">
                        <input type="checkbox" id="platform_linkedin" value="linkedin">
                        <label for="platform_linkedin">💼 לינקדאין</label>
                    </div>
                    <span class="credit-cost">3 נק'</span>
                </div>
                
                <div class="platform-option" onclick="togglePlatform('whatsapp')">
                    <div class="platform-info">
                        <input type="checkbox" id="platform_whatsapp" value="whatsapp">
                        <label for="platform_whatsapp">💬 וואטסאפ</label>
                    </div>
                    <span class="credit-cost">1 נק'</span>
                </div>
                
                <div style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 6px; font-size: 12px;">
                    <strong>💡 הערה:</strong> הפרסום יתבצע באופן אוטומטי לפי ההגדרות שלך
                </div>
            `;
            
            document.getElementById('modalCredits').textContent = currentBroker.credits || 0;
            document.getElementById('publishModal').style.display = 'flex';
        }

        function togglePlatform(platform) {
            const checkbox = document.getElementById(`platform_${platform}`);
            checkbox.checked = !checkbox.checked;
        }

        async function confirmPublish() {
            const selectedPlatforms = [];
            let totalCredits = 0;

            // בדיקת פלטפורמות נבחרות
            const platforms = ['facebook', 'linkedin', 'whatsapp'];
            const creditCosts = { facebook: 2, linkedin: 3, whatsapp: 1 };

            platforms.forEach(platform => {
                const checkbox = document.getElementById(`platform_${platform}`);
                if (checkbox && checkbox.checked) {
                    selectedPlatforms.push(platform);
                    totalCredits += creditCosts[platform];
                }
            });

            if (selectedPlatforms.length === 0) {
                alert('אנא בחר לפחות פלטפורמה אחת');
                return;
            }

            if (totalCredits > (currentBroker.credits || 0)) {
                alert(`אין מספיק נקודות זכות. נדרש: ${totalCredits}, זמין: ${currentBroker.credits || 0}`);
                return;
            }

            try {
                const response = await fetch(WEBHOOK_URL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'publish_property',
                        property_id: publishingProperty.porp_id,
                        broker_id: currentBroker.id,
                        platforms: selectedPlatforms,
                        credits_to_deduct: totalCredits
                    })
                });

                const data = await response.json();

                if (data.success) {
                    showDashboardStatus(`הנכס נשלח לפרסום ב-${selectedPlatforms.length} פלטפורמות! ניכוי: ${totalCredits} נקודות`, 'success');
                    
                    // עדכון נקודות זכות
                    currentBroker.credits -= totalCredits;
                    document.getElementById('nadelaniCredits').textContent = currentBroker.credits;
                    
                    closeModal();
                } else {
                    alert(data.message || 'שגיאה בפרסום הנכס');
                }

            } catch (error) {
                console.error('Error:', error);
                alert('שגיאה בחיבור למערכת');
            }
        }

        function closeModal() {
            document.getElementById('publishModal').style.display = 'none';
            publishingProperty = null;
        }

        // ===== פונקציות כלליות =====
        async function togglePropertyStatus(propertyId) {
            const property = allProperties.find(p => p.porp_id === propertyId);
            if (!property) return;

            const newStatus = property.status === 'on' ? 'off' : 'on';

            try {
                const response = await fetch(WEBHOOK_URL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'toggle_property_status',
                        property_id: propertyId,
                        new_status: newStatus,
                        broker_id: currentBroker.id
                    })
                });

                const data = await response.json();

                if (data.success) {
                    property.status = newStatus;
                    displayProperties();
                    updateBrokerInfo();
                    showDashboardStatus(`סטטוס הנכס שונה ל-${newStatus === 'on' ? 'פעיל' : 'לא פעיל'}`, 'success');
                } else {
                    showDashboardStatus(data.message || 'שגיאה בשינוי סטטוס', 'error');
                }

            } catch (error) {
                console.error('Error:', error);
                showDashboardStatus('שגיאה בחיבור למערכת', 'error');
            }
        }

        async function refreshData() {
            const refreshBtn = document.getElementById('refreshBtn');
            const refreshIcon = document.getElementById('refreshIcon');
            
            refreshIcon.textContent = '⏳';
            refreshBtn.disabled = true;
            
            const brokerId = localStorage.getItem('broker_id');
            await loadBrokerData(brokerId);
            
            refreshIcon.textContent = '🔄';
            refreshBtn.disabled = false;
        }

        function searchProperties() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            
            filteredProperties = allProperties.filter(property => {
                return property.title.toLowerCase().includes(searchTerm) ||
                       (property.description && property.description.toLowerCase().includes(searchTerm));
            });
            
            displayProperties();
        }

        function filterProperties() {
            const statusFilter = document.getElementById('statusFilter').value;
            const categoryFilter = document.getElementById('categoryFilter').value;
            
            filteredProperties = allProperties.filter(property => {
                const statusMatch = statusFilter === 'all' || property.status === statusFilter;
                const categoryMatch = categoryFilter === 'all' || property.category_id == categoryFilter;
                
                return statusMatch && categoryMatch;
            });
            
            displayProperties();
        }

        function toggleAllProperties() {
            // פונקציונליות להפעלה/עצירה של כל הנכסים
            alert('פונקציה זו תהיה זמינה בקרוב');
        }

        function showBulkActions() {
            alert('פרסום אוטומטי מרוכז - פונקציה זו תהיה זמינה בקרוב');
        }

        function showAutoPublishSettings() {
            alert('הגדרות אוטומציה - פונקציה זו תהיה זמינה בקרוב');
        }

        function toggleView() {
            // החלפה בין תצוגת כרטיסים לטבלה
            alert('תצוגת טבלה - פונקציה זו תהיה זמינה בקרוב');
        }

        function logout() {
            localStorage.removeItem('broker_id');
            localStorage.removeItem('broker_data');
            localStorage.removeItem('login_time');
            
            currentBroker = null;
            allProperties = [];
            filteredProperties = [];
            
            showLogin();
            showLoginStatus('התנתקת בהצלחה', 'success');
        }

        function setLoading(isLoading) {
            const loadingStatus = document.getElementById('loadingStatus');
            const propertiesList = document.getElementById('propertiesList');
            
            if (isLoading) {
                loadingStatus.style.display = 'block';
                propertiesList.style.display = 'none';
            } else {
                loadingStatus.style.display = 'none';
                propertiesList.style.display = 'grid';
            }
        }

        function showDashboardStatus(message, type) {
            const statusDiv = document.getElementById('dashboardStatus');
            statusDiv.textContent = message;
            statusDiv.className = `status-message status-${type}`;
            statusDiv.style.display = 'block';
            
            setTimeout(() => {
                statusDiv.style.display = 'none';
            }, 5000);
        }

        function formatDate(dateString) {
            if (!dateString) return 'לא זמין';
            
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('he-IL');
            } catch (error) {
                return 'תאריך לא תקין';
            }
        }

        // ===== אירועי מקלדת =====
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeModal();
            }
        });

        // ===== סגירת מודאל בלחיצה על הרקע =====
        document.getElementById('publishModal').addEventListener('click', function(event) {
            if (event.target === this) {
                closeModal();
            }
        });
    </script>
</body>
</html>