<?php
// Initialize the session
session_start();
 
// Check if the user is logged in, if not then redirect to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}

// Include config file
require_once "includes/config.php";

// Initialize counts
$properties_count = $users_count = $gallery_count = $categories_count = $messages_count = $new_messages_count = 0;

// Get counts for dashboard
try {
    // Get properties count
    $sql = "SELECT COUNT(*) as count FROM properties";
    $result = $conn->query($sql);
    if ($result) {
        $row = $result->fetch_assoc();
        $properties_count = $row['count'];
        $result->free();
    }

    // Get users count
    $sql = "SELECT COUNT(*) as count FROM admins";
    $result = $conn->query($sql);
    if ($result) {
        $row = $result->fetch_assoc();
        $users_count = $row['count'];
        $result->free();
    }

    // Get gallery count
    $sql = "SELECT COUNT(*) as count FROM gallery_images";
    $result = $conn->query($sql);
    if ($result) {
        $row = $result->fetch_assoc();
        $gallery_count = $row['count'];
        $result->free();
    }

    // Get categories count
    $sql = "SELECT COUNT(*) as count FROM gallery_categories";
    $result = $conn->query($sql);
    if ($result) {
        $row = $result->fetch_assoc();
        $categories_count = $row['count'];
        $result->free();
    }

    // Get messages count
    $sql = "SELECT COUNT(*) as count FROM contact_submissions";
    $result = $conn->query($sql);
    if ($result) {
        $row = $result->fetch_assoc();
        $messages_count = $row['count'];
        $result->free();
    }
    
    // Get new messages count (status = 'new')
    $sql = "SELECT COUNT(*) as count FROM contact_submissions WHERE status = 'new'";
    $result = $conn->query($sql);
    if ($result) {
        $row = $result->fetch_assoc();
        $new_messages_count = $row['count'];
        $result->free();
    }

    // Get recent contact submissions
    $recent_contacts = [];
    $sql = "SELECT id, name, email, submission_date, status 
            FROM contact_submissions 
            ORDER BY submission_date DESC 
            LIMIT 5";
    $result = $conn->query($sql);
    if ($result) {
        while($row = $result->fetch_assoc()) {
            $recent_contacts[] = $row;
        }
        $result->free();
    }
} catch (Exception $e) {
    $error_message = "Error fetching dashboard data: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dashboard - Real Estate Admin</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom styles -->
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --success-color: #4cc9f0;
            --danger-color: #f72585;
            --warning-color: #f8961e;
            --dark-color: #1a1a2e;
            --light-color: #f8f9fa;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f5f7fb;
            color: #4a4a4a;
        }

        /* Sidebar Styles */
        .sidebar {
            background: linear-gradient(180deg, var(--dark-color) 0%, #16213e 100%);
            min-height: 100vh;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            position: fixed;
            width: 250px;
            z-index: 1000;
        }

        .sidebar .brand-link {
            padding: 1.5rem 1rem;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            margin-bottom: 1rem;
        }

        .sidebar .brand-text {
            font-size: 1.5rem;
            font-weight: 700;
            color: white;
        }

        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            margin: 4px 10px;
            border-radius: 8px;
            transition: all 0.3s;
        }

        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            transform: translateX(5px);
        }

        .sidebar .nav-link i {
            width: 24px;
            text-align: center;
            margin-right: 10px;
        }

        /* Main Content */
        .main-content {
            margin-left: 250px;
            padding: 2rem;
            min-height: 100vh;
        }

        /* Header */
        .page-header {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .page-title {
            font-weight: 700;
            color: var(--dark-color);
            margin: 0;
        }

        /* Stats Cards */
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
            margin-bottom: 1.5rem;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            border-left: 4px solid var(--primary-color);
        }

        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }

        .stats-card.primary {
            border-left-color: var(--primary-color);
        }

        .stats-card.success {
            border-left-color: var(--success-color);
        }

        .stats-card.warning {
            border-left-color: var(--warning-color);
        }

        .stats-card.danger {
            border-left-color: var(--danger-color);
        }

        .stats-card .stats-icon {
            font-size: 2.5rem;
            margin-bottom: 1rem;
            color: var(--primary-color);
        }

        .stats-card.success .stats-icon {
            color: var(--success-color);
        }

        .stats-card.warning .stats-icon {
            color: var(--warning-color);
        }

        .stats-card.danger .stats-icon {
            color: var(--danger-color);
        }

        .stats-card h3 {
            font-size: 1.75rem;
            font-weight: 700;
            margin: 0 0 0.5rem;
        }

        .stats-card p {
            color: #6c757d;
            margin: 0;
        }

        /* Recent Activity */
        .recent-activity {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
            padding: 1.5rem;
            margin-top: 1.5rem;
        }

        .recent-activity .card-title {
            font-weight: 600;
            color: var(--dark-color);
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 1px solid #eee;
        }

        .activity-item {
            display: flex;
            padding: 1rem 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .activity-item:last-child {
            border-bottom: none;
        }

        .activity-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: rgba(67, 97, 238, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;
            color: var(--primary-color);
            flex-shrink: 0;
        }

        .activity-content {
            flex: 1;
        }

        .activity-title {
            font-weight: 500;
            margin-bottom: 0.25rem;
        }

        .activity-time {
            font-size: 0.8rem;
            color: #6c757d;
        }

        /* Responsive */
        @media (max-width: 992px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s ease;
            }
            
            .sidebar.show {
                transform: translateX(0);
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .navbar-toggler {
                display: block;
            }
        }

        @media (min-width: 993px) {
            .navbar-toggler {
                display: none;
            }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="d-flex flex-column h-100">
            <!-- Brand Logo -->
            <a href="index.php" class="brand-link">
                <span class="brand-text">RealEstate Pro</span>
            </a>

            <!-- Sidebar Menu -->
            <nav class="mt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a href="index.php" class="nav-link active">
                            <i class="fas fa-tachometer-alt"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="properties.php" class="nav-link">
                            <i class="fas fa-home"></i> Properties
                        </a>
                    </li>
                    
                    <li class="nav-item">
                        <a href="gallery.php" class="nav-link">
                            <i class="fas fa-images"></i> Gallery
                        </a>
                    </li>
                     <li class="nav-item">
                        <a href="contacts.php" class="nav-link">
                            <i class="fas fa-envelope"></i> Messages
                            <?php if($new_messages_count > 0): ?>
                                <span class="badge bg-danger float-end"><?php echo $new_messages_count; ?></span>
                            <?php endif; ?>
                        </a>
                    </li>

                    <li class="nav-item">
                        <a href="categories.php" class="nav-link">
                            <i class="fas fa-tags"></i> Categories
                        </a>
                    </li>
                      <!-- Visit Requests Section -->
                <li class="nav-item">
                    <a href="visit_requests.php" class="nav-link text-white <?= basename($_SERVER['PHP_SELF']) == 'visit_requests.php' ? 'active' : '' ?>">
                        <i class="fas fa-calendar-check me-2"></i> Visit Requests
                    </a>
                </li>

                   
                   
                    <li class="nav-item">
                        <a href="settings.php" class="nav-link">
                            <i class="fas fa-cog"></i> Settings
                        </a>
                    </li>
                </ul>
            </nav>

            <!-- User Profile -->
            <div class="mt-auto p-3">
                <div class="d-flex align-items-center text-white">
                    <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($_SESSION['username'] ?? 'Admin'); ?>&background=4361ee&color=fff" 
                         alt="User" 
                         class="rounded-circle me-2" 
                         width="40" 
                         height="40">
                    <div>
                        <div class="fw-bold"><?php echo htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></div>
                        <small>Administrator</small>
                    </div>
                </div>
                <div class="mt-3">
                    <a href="logout.php" class="btn btn-outline-light btn-sm w-100">
                        <i class="fas fa-sign-out-alt me-1"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="page-title">Dashboard Overview</h1>
            <div class="d-flex align-items-center">
                <span class="me-3 text-muted">
                    <i class="far fa-calendar-alt me-1"></i> 
                    <?php echo date('l, F j, Y'); ?>
                </span>
                <button class="btn btn-primary d-md-none" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
            </div>
        </div>

        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="row">
            <div class="col-md-6 col-lg-3">
                <div class="stats-card primary">
                    <i class="fas fa-home stats-icon"></i>
                    <h3><?php echo $properties_count; ?></h3>
                    <p>Properties</p>
                </div>
            </div>
            <div class="col-md-6 col-lg-3">
                <div class="stats-card success">
                    <i class="fas fa-users stats-icon"></i>
                    <h3><?php echo $users_count; ?></h3>
                    <p>Users</p>
                </div>
            </div>
            <div class="col-md-6 col-lg-3">
                <div class="stats-card warning">
                    <i class="fas fa-envelope stats-icon"></i>
                    <h3><?php echo $messages_count; ?> 
                        <?php if($new_messages_count > 0): ?>
                            <span class="badge bg-danger"><?php echo $new_messages_count; ?> new</span>
                        <?php endif; ?>
                    </h3>
                    <p>Messages</p>
                    <a href="contacts.php" class="stretched-link"></a>
                </div>
            </div>
            <div class="col-md-6 col-lg-3">
                <div class="stats-card danger">
                    <i class="fas fa-tags stats-icon"></i>
                    <h3><?php echo $categories_count; ?></h3>
                    <p>Categories</p>
                </div>
            </div>
        </div>

       
        <!-- Recent Activity -->
        <div class="row">
            <div class="col-12">
                <div class="recent-activity">
                    <h5 class="card-title">Recent Contact Submissions</h5>
                    <?php if (!empty($recent_contacts)): ?>
                        <?php foreach ($recent_contacts as $contact): ?>
                            <div class="activity-item">
                                <div class="activity-icon">
                                    <i class="fas fa-envelope"></i>
                                </div>
                                <div class="activity-content">
                                    <h6 class="activity-title"><?php echo htmlspecialchars($contact['name'] ?? 'No Name'); ?></h6>
                                    <?php 
                                    $message = $contact['message'] ?? 'No message content';
                                    $preview = htmlspecialchars(substr($message, 0, 100));
                                    echo "<p class='activity-text mb-1'>{$preview}" . (strlen($message) > 100 ? '...' : '') . "</p>";
                                    ?>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span class="activity-time">
                                            <i class="far fa-clock me-1"></i> 
                                            <?php echo date('M j, Y g:i A', strtotime($contact['submission_date'])); ?>
                                        </span>
                                        <a href="mailto:<?php echo htmlspecialchars($contact['email']); ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-reply me-1"></i> Reply
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="text-center py-4">
                            <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No recent contact submissions</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle sidebar on mobile
        document.getElementById('sidebarToggle').addEventListener('click', function() {
            document.querySelector('.sidebar').classList.toggle('show');
        });

        // Auto-hide sidebar when clicking outside on mobile
        document.addEventListener('click', function(event) {
            const sidebar = document.querySelector('.sidebar');
            const sidebarToggle = document.getElementById('sidebarToggle');
            
            if (window.innerWidth <= 992 && 
                !sidebar.contains(event.target) && 
                event.target !== sidebarToggle && 
                !sidebarToggle.contains(event.target)) {
                sidebar.classList.remove('show');
            }
        });

        // Update time every minute
        function updateTime() {
            const now = new Date();
            const options = { 
                weekday: 'long', 
                year: 'numeric', 
                month: 'long', 
                day: 'numeric' 
            };
            document.querySelector('.current-date').textContent = now.toLocaleDateString('en-US', options);
        }

        // Update time on page load and then every minute
        updateTime();
        setInterval(updateTime, 60000);
    </script>
</body>
</html>