<?php
// Error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Files ko include karna
require_once '../config/cors.php';
require_once '../config/database.php';
// require_once '../models/Product.php'; // Profile ke liye iski zaroorat nahi hai
// require_once '../middleware/auth.php'; // Auth istemal nahi kar rahe

// --- YAHAN SE FIX SHURU ---

// Database connection Class se banaya gaya hai
$database = new Database();
$db = $database->getConnection(); // Is connection ($db) ka istemal karenge

// URL se User ID lena
$userId = $_GET['userId'] ?? null;

if (!$userId) {
    http_response_code(400);
    echo json_encode(['error' => 'User ID is missing in the URL']);
    exit;
}

try {
    // getDBConnection() ko hata diya gaya hai.
    
    // User profile data ke liye query
    // $pdo ko $db se badal diya gaya hai
    $stmt = $db->prepare("
        SELECT id, first_name, last_name, name, email, phone, date_of_birth, 
               gender, profile_image, bio, role, email_verified, is_active, 
               created_at, updated_at, last_login
        FROM users 
        WHERE id = :user_id
    ");
    $stmt->execute(['user_id' => $userId]);
    $userProfile = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$userProfile) {
        http_response_code(404);
        echo json_encode(['error' => 'User not found']);
        exit;
    }
    
    // User addresses ke liye query
    // $pdo ko $db se badal diya gaya hai
    $stmt = $db->prepare("
        SELECT id, label, address_line1, address_line2, city, state, 
               postal_code, country, is_default, created_at
        FROM addresses 
        WHERE user_id = :user_id 
        ORDER BY is_default DESC, created_at DESC
    ");
    $stmt->execute(['user_id' => $userId]);
    $addresses = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Response bhejna
    echo json_encode([
        'success' => true,
        'user' => $userProfile,
        'addresses' => $addresses
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error occurred: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'An error occurred: ' . $e->getMessage()]);
}
?>