<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Database.php';

$auth = new Auth();
$auth->requireRole('admin');

$user_id = $_GET['id'] ?? null;

if (!$user_id) {
    jsonResponse(['success' => false, 'message' => 'User ID is required'], 400);
}

try {
    $db = new Database();

    // Get basic user info
    $user_stmt = $db->query("SELECT id, name, email, phone, role, created_at FROM users WHERE id = ?", [$user_id]);
    $user = $user_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        jsonResponse(['success' => false, 'message' => 'User not found'], 404);
    }

    $details = [];

    // Get role-specific details
    if ($user['role'] === 'customer') {
        $deliveries_stmt = $db->query("SELECT id, tracking_id, status, created_at FROM deliveries WHERE customer_id = ? ORDER BY created_at DESC LIMIT 5", [$user_id]);
        $details['recent_deliveries'] = $deliveries_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $orders_stmt = $db->query("SELECT id, total_amount, status, created_at FROM orders WHERE user_id = ? ORDER BY created_at DESC LIMIT 5", [$user_id]);
        $details['recent_orders'] = $orders_stmt->fetchAll(PDO::FETCH_ASSOC);

    } elseif ($user['role'] === 'shop_owner') {
        $shops_stmt = $db->query("SELECT id, name, location, is_approved FROM shops WHERE owner_id = ? ORDER BY created_at DESC", [$user_id]);
        $details['shops'] = $shops_stmt->fetchAll(PDO::FETCH_ASSOC);

    } elseif ($user['role'] === 'rider') {
        $stats_stmt = $db->query("SELECT status, COUNT(*) as count FROM deliveries WHERE rider_id = ? GROUP BY status", [$user_id]);
        $stats = $stats_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        $details['delivery_stats'] = $stats;
    }

    $user['details'] = $details;

    jsonResponse(['success' => true, 'user' => $user]);

} catch (Exception $e) {
    jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
}
?>