<?php
session_start();

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

header('Content-Type: application/json');

// Database connection
$host = 'localhost';
$db = 'interior_db';
$user = 'root';
$password = '';

$connection = new mysqli($host, $user, $password, $db);

if ($connection->connect_error) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

try {
    $user_id = $_SESSION['user_id'];
    
    // Get user email first
    $user_stmt = $connection->prepare("SELECT email FROM users WHERE id = ?");
    if (!$user_stmt) {
        throw new Exception('Prepare failed: ' . $connection->error);
    }
    
    $user_stmt->bind_param("i", $user_id);
    $user_stmt->execute();
    $user_result = $user_stmt->get_result();
    
    if ($user_result->num_rows === 0) {
        throw new Exception('User not found');
    }
    
    $user_data = $user_result->fetch_assoc();
    $user_email = $user_data['email'];
    
    // Get consultations with updated status - check both user_id and email
    $consultations_stmt = $connection->prepare("
        SELECT id, consultation_type, preferred_date, budget_range, status, created_at, updated_at
        FROM consultations 
        WHERE email = ? OR user_id = ?
        ORDER BY created_at DESC
        LIMIT 10
    ");
    
    if (!$consultations_stmt) {
        throw new Exception('Prepare failed: ' . $connection->error);
    }
    
    $consultations_stmt->bind_param("si", $user_email, $user_id);
    $consultations_stmt->execute();
    $consultations_result = $consultations_stmt->get_result();
    
    $consultations = [];
    while ($row = $consultations_result->fetch_assoc()) {
        $consultations[] = [
            'id' => (int)$row['id'],
            'consultation_type' => $row['consultation_type'],
            'preferred_date' => $row['preferred_date'],
            'budget_range' => $row['budget_range'],
            'status' => $row['status'],
            'created_at' => $row['created_at'],
            'updated_at' => $row['updated_at'] ?? $row['created_at']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'consultations' => $consultations,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    error_log('get-consultation-status.php error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching consultation status'
    ]);
} finally {
    if (isset($connection)) {
        $connection->close();
    }
}
?>
