<?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', 'user_id' => null]);
    exit;
}

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

// Database connection
$host = 'localhost';
$db = 'zemaraim_interior';
$user = 'zemaraim';
$password = '8wwxk]-X3Kx]CJ]5';

$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'];
    
    // DEBUG: Log what we're searching for
    error_log("DEBUG: Looking for consultations with email: " . $user_email);
    
    // Get consultations with updated status - try both user_id and email
    $consultations_stmt = $connection->prepare("
        SELECT id, consultation_type, preferred_date, budget_range, status, created_at, updated_at, email, user_id
        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']
        ];
    }
    
    // DEBUG: Log results
    error_log("DEBUG: Found " . count($consultations) . " consultations");
    
    echo json_encode([
        'success' => true,
        'user_id' => $user_id,
        'user_email' => $user_email,
        'consultations' => $consultations,
        'count' => count($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: ' . $e->getMessage()
    ]);
} finally {
    if (isset($connection)) {
        $connection->close();
    }
}
?>
