<?php
require_once '../../config.php';
header('Content-Type: application/json');

// Check if user is logged in and is staff
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'staff') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $stats = [];
    
    // Count pending inquiries
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM inquiries WHERE status = 'pending'");
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['pending_inquiries'] = intval($result->fetch_assoc()['count']);
    $stmt->close();
    
    // Count total properties
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM properties");
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['total_properties'] = intval($result->fetch_assoc()['count']);
    $stmt->close();
    
    // Count upcoming appointments
    $stmt = $conn->prepare("
        SELECT COUNT(*) as count FROM appointments 
        WHERE status IN ('pending', 'scheduled') 
        AND appointment_date >= CURDATE()
    ");
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['upcoming_visits'] = intval($result->fetch_assoc()['count']);
    $stmt->close();
    
    // Count total customers
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM users WHERE role = 'customer'");
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['total_customers'] = intval($result->fetch_assoc()['count']);
    $stmt->close();
    
    echo json_encode(['success' => true, 'stats' => $stats]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
