<?php
/**
 * Staff Dashboard - Real-Time Implementation
 * Handles inquiries and appointments with real-time approve/decline functionality
 */

require_once '../config.php';

// Check if user is logged in and is staff
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'staff') {
    header('Location: ../staff-login.php');
    exit;
}

$staff_id = $_SESSION['user_id'];
$staff_name = $_SESSION['user_name'] ?? 'Staff Member';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Dashboard - Real-Time</title>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assets/css/fontawesome.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Poppins', sans-serif; background: #f5f7fa; color: #333; display: flex; }
        
        .sidebar {
            width: 250px;
            background: #2c3e50;
            color: white;
            height: 100vh;
            position: fixed;
            overflow-y: auto;
            padding: 20px 0;
        }
        
        .sidebar h3 {
            padding: 15px 20px;
            font-size: 14px;
            color: #bbb;
            text-transform: uppercase;
            margin: 10px 0 0 0;
        }
        
        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .sidebar-menu li {
            margin: 0;
        }
        
        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 20px;
            color: rgba(255,255,255,0.7);
            text-decoration: none;
            transition: all 0.3s;
            border-left: 4px solid transparent;
            cursor: pointer;
        }
        
        .sidebar-menu a:hover,
        .sidebar-menu a.active {
            background: rgba(102,126,234,0.2);
            color: white;
            border-left-color: #667eea;
        }
        
        .sidebar-badge {
            margin-left: auto;
            background: #e74c3c;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .main-wrapper {
            flex: 1;
            margin-left: 250px;
            display: flex;
            flex-direction: column;
        }
        
        .nav-header { 
            background: white; 
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08); 
            display: flex; 
            justify-content: space-between; 
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        .nav-header h1 { font-size: 22px; color: #667eea; margin: 0; font-weight: 700; }
        .user-menu { display: flex; align-items: center; gap: 20px; }
        .user-menu .avatar { width: 40px; height: 40px; border-radius: 50%; background: #667eea; color: white; display: flex; align-items: center; justify-content: center; font-weight: 600; }
        .logout-btn { background: #dc3545; color: white; border: none; padding: 8px 16px; border-radius: 5px; cursor: pointer; text-decoration: none; transition: background 0.3s; }
        .logout-btn:hover { background: #c82333; }
        
        .section {
            display: none;
        }
        
        .section.active {
            display: block;
        }
        
        .container { max-width: 1400px; margin: 0 auto; padding: 30px 20px; }
        h2 { font-size: 20px; color: #333; margin-bottom: 20px; margin-top: 30px; font-weight: 700; display: flex; align-items: center; gap: 10px; }
        
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px; }
        .stat-card { background: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.06); border-left: 4px solid #667eea; text-align: center; animation: slideIn 0.5s ease-out; }
        .stat-card h3 { font-size: 12px; color: #999; text-transform: uppercase; margin-bottom: 10px; }
        .stat-card .number { font-size: 32px; font-weight: 700; color: #667eea; }
        
        .panel { background: white; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.06); padding: 25px; margin-bottom: 30px; }
        
        .cards-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 20px; }
        .card { background: #f8f9fa; border-radius: 8px; padding: 20px; border-left: 4px solid #667eea; transition: all 0.3s ease; }
        .card:hover { box-shadow: 0 5px 15px rgba(0,0,0,0.1); transform: translateY(-2px); }
        
        .card-header { display: flex; justify-content: space-between; align-items: start; margin-bottom: 15px; }
        .card-title { font-weight: 600; color: #333; font-size: 16px; }
        .card-meta { color: #999; font-size: 12px; margin-top: 5px; }
        
        .badge { padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; text-transform: uppercase; }
        .badge-pending { background: #fff3cd; color: #856404; }
        .badge-responded { background: #d1ecf1; color: #0c5460; }
        .badge-approved { background: #d4edda; color: #155724; }
        .badge-declined { background: #f8d7da; color: #721c24; }
        .badge-scheduled { background: #d4edda; color: #155724; }
        
        .card-content { font-size: 14px; color: #666; line-height: 1.6; margin-bottom: 15px; }
        .card-content strong { color: #333; }
        
        .customer-info { margin: 15px 0; padding: 12px; background: white; border-radius: 6px; font-size: 13px; }
        .customer-info-row { margin: 5px 0; }
        
        .btn { padding: 10px 16px; background: #667eea; color: white; border: none; border-radius: 6px; cursor: pointer; text-decoration: none; display: inline-block; font-size: 13px; font-weight: 600; transition: all 0.3s; }
        .btn:hover { background: #764ba2; }
        .btn:active { transform: scale(0.98); }
        .btn-small { padding: 6px 12px; font-size: 12px; }
        .btn-secondary { background: #999; }
        .btn-secondary:hover { background: #777; }
        .btn-success { background: #28a745; }
        .btn-success:hover { background: #218838; }
        .btn-danger { background: #dc3545; }
        .btn-danger:hover { background: #c82333; }
        .btn:disabled { opacity: 0.6; cursor: not-allowed; }
        
        .card-actions { display: flex; gap: 10px; margin-top: 15px; flex-wrap: wrap; }
        
        .empty-state { text-align: center; padding: 40px 20px; color: #999; }
        .empty-state-icon { font-size: 48px; margin-bottom: 15px; }
        
        .loading { text-align: center; color: #999; padding: 40px 20px; }
        .spinner { border: 3px solid #f3f3f3; border-top: 3px solid #667eea; border-radius: 50%; width: 30px; height: 30px; animation: spin 1s linear infinite; margin: 0 auto 10px; }
        
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        @keyframes slideIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        
        .alert { padding: 12px 16px; border-radius: 6px; margin-bottom: 15px; font-size: 13px; position: relative; }
        .alert-success { background: #d4edda; color: #155724; }
        .alert-error { background: #f8d7da; color: #721c24; }
        
        .realtime-badge { display: inline-block; background: #667eea; color: white; padding: 4px 8px; border-radius: 4px; font-size: 11px; margin-left: 10px; animation: pulse 2s infinite; }
        @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.7; } }
        
        table { width: 100%; border-collapse: collapse; font-size: 14px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #e0e0e0; }
        th { background: #f8f9fa; font-weight: 600; color: #333; }
        tr:hover { background: #f8f9fa; }
        
        @media (max-width: 768px) {
            .nav-header { flex-direction: column; gap: 15px; text-align: center; }
            .cards-grid { grid-template-columns: 1fr; }
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
        }
    </style>
</head>
<body>

    <!-- Sidebar Navigation -->
    <div class="sidebar">
        <h3>Navigation</h3>
        <ul class="sidebar-menu">
            <li><a href="#" onclick="showSection('overview')" data-section="overview" class="section-link active">📊 Overview</a></li>
            <li><a href="#" onclick="showSection('inquiries')" data-section="inquiries" class="section-link">💬 Inquiries <span class="sidebar-badge" id="inquiries-badge">0</span></a></li>
            <li><a href="#" onclick="showSection('appointments')" data-section="appointments" class="section-link">📅 Appointments <span class="sidebar-badge" id="appointments-badge">0</span></a></li>
            <li><a href="#" onclick="showSection('properties')" data-section="properties" class="section-link">🏠 Properties</a></li>
        </ul>
    </div>

    <!-- Main Content -->
    <div class="main-wrapper">
        <!-- Header -->
        <div class="nav-header">
            <h1>⚙️ Staff Dashboard <span class="realtime-badge">🔴 LIVE</span></h1>
            <div class="user-menu">
                <span><?php echo htmlspecialchars($staff_name); ?></span>
                <div class="avatar"><?php echo strtoupper(substr($staff_name, 0, 1)); ?></div>
                <a href="../logout.php" class="logout-btn">Logout</a>
            </div>
        </div>

        <!-- Content Sections -->
        <div class="container">

        <h2>📊 Real-Time Statistics</h2>
        <div class="stats-grid">
            <div class="stat-card">
                <h3>💬 Pending Inquiries</h3>
                <div class="number" id="stat-inquiries">0</div>
            </div>
            <div class="stat-card">
                <h3>🏠 Properties</h3>
                <div class="number" id="stat-properties">0</div>
            </div>
            <div class="stat-card">
                <h3>📅 Upcoming Appointments</h3>
                <div class="number" id="stat-appointments">0</div>
            </div>
            <div class="stat-card">
                <h3>👥 Total Customers</h3>
                <div class="number" id="stat-customers">0</div>
            </div>
        </div>

        <!-- Overview Section -->
        <section class="section active" id="overview">
            <h2>📊 Real-Time Statistics</h2>
            <div class="stats-grid">
                <div class="stat-card">
                    <h3>💬 Pending Inquiries</h3>
                    <div class="number" id="stat-inquiries-overview">0</div>
                </div>
                <div class="stat-card">
                    <h3>🏠 Properties</h3>
                    <div class="number" id="stat-properties-overview">0</div>
                </div>
                <div class="stat-card">
                    <h3>📅 Upcoming Appointments</h3>
                    <div class="number" id="stat-appointments-overview">0</div>
                </div>
                <div class="stat-card">
                    <h3>👥 Total Customers</h3>
                    <div class="number" id="stat-customers-overview">0</div>
                </div>
            </div>
        </section>

        <!-- Inquiries Section -->
        <section class="section" id="inquiries">
            <h2>💬 Customer Inquiries - Real-Time</h2>
            <div class="panel">
                <div id="inquiries-container" class="cards-grid">
                    <div class="loading"><div class="spinner"></div><p>Loading inquiries...</p></div>
                </div>
            </div>
        </section>

        <!-- Appointments Section -->
        <section class="section" id="appointments">
            <h2>📅 Scheduled Appointments - Real-Time</h2>
            <div class="panel">
                <div id="appointments-container" class="cards-grid">
                    <div class="loading"><div class="spinner"></div><p>Loading appointments...</p></div>
                </div>
            </div>
        </section>

        <!-- Properties Section -->
        <section class="section" id="properties">
            <h2>🏠 Property Listings</h2>
            <div class="panel">
                <div class="table-responsive">
                    <table id="properties-table">
                        <thead>
                            <tr>
                                <th>Title</th>
                                <th>Location</th>
                                <th>Price</th>
                                <th>Type</th>
                                <th>Beds</th>
                                <th>Baths</th>
                                <th>Status</th>
                                <th>Created</th>
                            </tr>
                        </thead>
                        <tbody id="properties-body">
                            <tr>
                                <td colspan="8" class="loading">
                                    <div class="spinner"></div>
                                    Loading properties...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>


    </div>

    <script>
        const POLLING_INTERVAL = 5000; // 5 seconds for real-time
        let pollTimers = {};
        let lastUpdateTime = 0;

        document.addEventListener('DOMContentLoaded', function() {
            console.log('🔴 Real-Time Staff Dashboard Started');
            loadAllData();
            startRealTimePolling();
        });

        function startRealTimePolling() {
            // Poll every 5 seconds for real-time updates
            pollTimers.all = setInterval(loadAllData, POLLING_INTERVAL);
        }

        function loadAllData() {
            loadStats();
            loadInquiries();
            loadAppointments();
        }

        function loadStats() {
            fetch('api/staff/get-stats.php')
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('stat-inquiries').textContent = data.stats.pending_inquiries || 0;
                        document.getElementById('stat-properties').textContent = data.stats.total_properties || 0;
                        document.getElementById('stat-appointments').textContent = data.stats.upcoming_visits || 0;
                        document.getElementById('stat-customers').textContent = data.stats.total_customers || 0;
                    }
                })
                .catch(e => console.error('Stats error:', e));
        }

        function loadInquiries() {
            fetch('api/staff/get-pending-inquiries.php')
                .then(r => r.json())
                .then(data => {
                    if (data.success && data.inquiries) {
                        displayInquiries(data.inquiries);
                    }
                })
                .catch(e => console.error('Inquiries error:', e));
        }

        function displayInquiries(inquiries) {
            const container = document.getElementById('inquiries-container');
            
            if (!inquiries || inquiries.length === 0) {
                container.innerHTML = '<div class="empty-state"><div class="empty-state-icon">✅</div><p>No pending inquiries</p></div>';
                return;
            }

            let pending = inquiries.filter(i => i.status === 'pending');
            let responded = inquiries.filter(i => i.status === 'responded');
            let approved = inquiries.filter(i => i.status === 'approved');
            let declined = inquiries.filter(i => i.status === 'declined');

            let html = '';

            pending.forEach(i => {
                html += `
                    <div class="card" style="border-left-color: #ffc107;">
                        <div class="card-header">
                            <div><div class="card-title">${i.property_title || 'Property'}</div>
                            <div class="card-meta">From: ${i.customer_name}</div></div>
                            <span class="badge badge-pending">⏳ PENDING</span>
                        </div>
                        <div class="card-content">📝 ${i.message}</div>
                        <div class="customer-info">
                            <strong>📧 ${i.email}</strong> | <strong>☎️ ${i.phone}</strong><br>
                            <span class="card-meta">Submitted: ${new Date(i.created_at).toLocaleDateString()}</span>
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-success btn-small" onclick="approveInquiry(${i.id}, this)">✓ Approve</button>
                            <button class="btn btn-danger btn-small" onclick="declineInquiry(${i.id}, this)">✕ Decline</button>
                            <a href="mailto:${i.email}" class="btn btn-secondary btn-small">📧 Email</a>
                        </div>
                    </div>
                `;
            });

            responded.forEach(i => {
                html += `
                    <div class="card" style="border-left-color: #17a2b8;">
                        <div class="card-header">
                            <div class="card-title">${i.property_title || 'Property'}</div>
                            <span class="badge badge-responded">💬 RESPONDED</span>
                        </div>
                        <div class="card-content"><strong>Message:</strong> ${i.message}</div>
                        <div class="customer-info" style="background: #d1ecf1;"><strong>Your Response:</strong><br>${i.response || 'No response yet'}</div>
                        <div class="card-actions">
                            <button class="btn btn-success btn-small" onclick="approveInquiry(${i.id}, this)">✓ Approve</button>
                            <button class="btn btn-danger btn-small" onclick="declineInquiry(${i.id}, this)">✕ Decline</button>
                        </div>
                    </div>
                `;
            });

            approved.forEach(i => {
                html += `
                    <div class="card" style="border-left-color: #28a745; opacity: 0.85;">
                        <div class="card-header">
                            <div class="card-title">${i.property_title || 'Property'}</div>
                            <span class="badge badge-approved">✓ APPROVED</span>
                        </div>
                        <div class="card-content">📝 ${i.message}</div>
                        <div class="customer-info"><strong>From: ${i.customer_name}</strong></div>
                    </div>
                `;
            });

            declined.forEach(i => {
                html += `
                    <div class="card" style="border-left-color: #dc3545; opacity: 0.85;">
                        <div class="card-header">
                            <div class="card-title">${i.property_title || 'Property'}</div>
                            <span class="badge badge-declined">✕ DECLINED</span>
                        </div>
                        <div class="card-content">📝 ${i.message}</div>
                        <div class="customer-info"><strong>From: ${i.customer_name}</strong></div>
                    </div>
                `;
            });

            container.innerHTML = html;
        }

        function loadAppointments() {
            fetch('api/staff/get-scheduled-visits.php')
                .then(r => r.json())
                .then(data => {
                    if (data.success && data.appointments) {
                        displayAppointments(data.appointments);
                    }
                })
                .catch(e => console.error('Appointments error:', e));
        }

        function displayAppointments(appointments) {
            const container = document.getElementById('appointments-container');
            
            if (!appointments || appointments.length === 0) {
                container.innerHTML = '<div class="empty-state"><div class="empty-state-icon">📭</div><p>No scheduled appointments</p></div>';
                return;
            }

            let pending = appointments.filter(a => a.status === 'pending');
            let approved = appointments.filter(a => a.status === 'approved');
            let declined = appointments.filter(a => a.status === 'declined');

            let html = '';

            pending.forEach(a => {
                html += `
                    <div class="card" style="border-left-color: #ffc107;">
                        <div class="card-header">
                            <div><div class="card-title">${a.property_title || 'Property'}</div>
                            <div class="card-meta">Customer: ${a.customer_name}</div></div>
                            <span class="badge badge-pending">⏳ PENDING</span>
                        </div>
                        <div class="card-content">
                            📍 <strong>${a.city}</strong><br>
                            🗓️ <strong>${new Date(a.appointment_date).toLocaleDateString()}</strong> at <strong>${a.appointment_time}</strong>
                        </div>
                        <div class="customer-info">
                            📧 ${a.email} | ☎️ ${a.phone}<br>
                            ${a.message ? '<strong>Notes:</strong> ' + a.message : ''}
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-success btn-small" onclick="approveAppointment(${a.id}, this)">✓ Approve</button>
                            <button class="btn btn-danger btn-small" onclick="declineAppointment(${a.id}, this)">✕ Decline</button>
                            <a href="mailto:${a.email}" class="btn btn-secondary btn-small">📧 Email</a>
                        </div>
                    </div>
                `;
            });

            approved.forEach(a => {
                html += `
                    <div class="card" style="border-left-color: #28a745; opacity: 0.85;">
                        <div class="card-header">
                            <div class="card-title">${a.property_title || 'Property'}</div>
                            <span class="badge badge-approved">✓ APPROVED</span>
                        </div>
                        <div class="card-content">
                            📍 ${a.city} | 🗓️ ${new Date(a.appointment_date).toLocaleDateString()} at ${a.appointment_time}
                        </div>
                        <div class="customer-info"><strong>${a.customer_name}</strong></div>
                    </div>
                `;
            });

            declined.forEach(a => {
                html += `
                    <div class="card" style="border-left-color: #dc3545; opacity: 0.85;">
                        <div class="card-header">
                            <div class="card-title">${a.property_title || 'Property'}</div>
                            <span class="badge badge-declined">✕ DECLINED</span>
                        </div>
                        <div class="card-content">
                            📍 ${a.city} | 🗓️ ${new Date(a.appointment_date).toLocaleDateString()} at ${a.appointment_time}
                        </div>
                        <div class="customer-info"><strong>${a.customer_name}</strong></div>
                    </div>
                `;
            });

            container.innerHTML = html;
        }

        function approveInquiry(inquiryId, btn) {
            if (!confirm('✓ Approve this inquiry?')) return;
            btn.disabled = true;
            btn.textContent = '⏳ Approving...';

            fetch('api/staff/realtime-approve-inquiry.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({inquiry_id: inquiryId, action: 'approve'})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showAlert('✓ Inquiry approved!', 'success');
                    setTimeout(() => {
                        loadInquiries();
                        loadStats();
                    }, 500);
                } else {
                    showAlert('❌ ' + (data.message || 'Error'), 'error');
                    btn.disabled = false;
                    btn.textContent = '✓ Approve';
                }
            })
            .catch(e => {
                console.error(e);
                showAlert('❌ Error', 'error');
                btn.disabled = false;
                btn.textContent = '✓ Approve';
            });
        }

        function declineInquiry(inquiryId, btn) {
            if (!confirm('✕ Decline this inquiry?')) return;
            btn.disabled = true;
            btn.textContent = '⏳ Declining...';

            fetch('api/staff/realtime-approve-inquiry.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({inquiry_id: inquiryId, action: 'decline'})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showAlert('✕ Inquiry declined!', 'success');
                    setTimeout(() => {
                        loadInquiries();
                        loadStats();
                    }, 500);
                } else {
                    showAlert('❌ ' + (data.message || 'Error'), 'error');
                    btn.disabled = false;
                    btn.textContent = '✕ Decline';
                }
            })
            .catch(e => {
                console.error(e);
                showAlert('❌ Error', 'error');
                btn.disabled = false;
                btn.textContent = '✕ Decline';
            });
        }

        function approveAppointment(appointmentId, btn) {
            if (!confirm('✓ Approve this appointment?')) return;
            btn.disabled = true;
            btn.textContent = '⏳ Approving...';

            fetch('api/staff/realtime-approve-appointment.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({appointment_id: appointmentId, action: 'approve'})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showAlert('✓ Appointment approved!', 'success');
                    setTimeout(() => {
                        loadAppointments();
                        loadStats();
                    }, 500);
                } else {
                    showAlert('❌ ' + (data.message || 'Error'), 'error');
                    btn.disabled = false;
                    btn.textContent = '✓ Approve';
                }
            })
            .catch(e => {
                console.error(e);
                showAlert('❌ Error', 'error');
                btn.disabled = false;
                btn.textContent = '✓ Approve';
            });
        }

        function declineAppointment(appointmentId, btn) {
            if (!confirm('✕ Decline this appointment?')) return;
            btn.disabled = true;
            btn.textContent = '⏳ Declining...';

            fetch('api/staff/realtime-approve-appointment.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({appointment_id: appointmentId, action: 'decline'})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showAlert('✕ Appointment declined!', 'success');
                    setTimeout(() => {
                        loadAppointments();
                        loadStats();
                    }, 500);
                } else {
                    showAlert('❌ ' + (data.message || 'Error'), 'error');
                    btn.disabled = false;
                    btn.textContent = '✕ Decline';
                }
            })
            .catch(e => {
                console.error(e);
                showAlert('❌ Error', 'error');
                btn.disabled = false;
                btn.textContent = '✕ Decline';
            });
        }

        function showAlert(message, type) {
            const alert = document.createElement('div');
            alert.className = `alert alert-${type}`;
            alert.textContent = message;
            alert.style.position = 'fixed';
            alert.style.top = '20px';
            alert.style.right = '20px';
            alert.style.zIndex = '9999';
            alert.style.minWidth = '300px';
            document.body.appendChild(alert);
            setTimeout(() => alert.remove(), 3000);
        }

        window.addEventListener('beforeunload', () => {
            Object.values(pollTimers).forEach(t => clearInterval(t));
        });
    </script>

</body>
</html>
