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

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

try {
    $hasResponseColumn = false;
    $responseColumnCheck = $conn->query("SHOW COLUMNS FROM inquiries LIKE 'response'");
    if ($responseColumnCheck && $responseColumnCheck->num_rows > 0) {
        $hasResponseColumn = true;
    }
    if ($responseColumnCheck instanceof mysqli_result) {
        $responseColumnCheck->close();
    }

    $responseSelect = $hasResponseColumn ? "i.response AS response," : "NULL AS response,";

    // Get all inquiries from all customers
    $stmt = $conn->prepare("
        SELECT 
            i.id,
            i.customer_id,
            CONCAT(c.firstname, ' ', c.lastname) as customer_name,
            c.phone,
            c.email,
            p.title as property_title,
            i.property_id,
            i.message,
            {$responseSelect}
            i.status,
            i.created_at,
            i.updated_at
        FROM inquiries i
        LEFT JOIN customers c ON i.customer_id = c.id
        LEFT JOIN properties p ON i.property_id = p.id
        WHERE i.status IN ('pending', 'responded', 'approved', 'declined')
        ORDER BY CASE WHEN i.status = 'pending' THEN 0 ELSE 1 END, i.created_at DESC
        LIMIT 100
    ");
    if (!$stmt) {
        throw new Exception('Failed to prepare inquiries query');
    }
    
    $stmt->execute();
    $result = $stmt->get_result();

    $inquiries = [];
    while ($row = $result->fetch_assoc()) {
        $inquiries[] = [
            'id' => intval($row['id']),
            'customer_id' => intval($row['customer_id']),
            'customer_name' => $row['customer_name'],
            'phone' => $row['phone'],
            'email' => $row['email'],
            'property_id' => $row['property_id'] ? intval($row['property_id']) : null,
            'property_title' => $row['property_title'],
            'message' => $row['message'],
            'response' => $row['response'],
            'status' => $row['status'],
            'created_at' => $row['created_at'],
            'updated_at' => $row['updated_at']
        ];
    }
    $stmt->close();

    echo json_encode(['success' => true, 'inquiries' => $inquiries, 'count' => count($inquiries)]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
