<?php
require 'auth_check.php';
require '../config/db.php';

if (!isset($_GET['id'])) {
    header("Location: users.php"); exit();
}

$user_id = $_GET['id'];

// 1. Fetch User Profile
$uStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$uStmt->execute([$user_id]);
$user = $uStmt->fetch();

if (!$user) { echo "User not found."; exit(); }

// 2. Fetch All Orders & Items for this User
$orders = $pdo->prepare("
    SELECT o.*, 
           GROUP_CONCAT(p.name SEPARATOR ', ') as product_names 
    FROM orders o
    LEFT JOIN order_items oi ON o.id = oi.order_id
    LEFT JOIN products p ON oi.product_id = p.id
    WHERE o.user_id = ?
    GROUP BY o.id
    ORDER BY o.created_at DESC
");
$orders->execute([$user_id]);
$order_history = $orders->fetchAll();

// 3. Calculate Stats
$total_spent = 0;
$completed_orders = 0;
foreach($order_history as $o) {
    if($o['status'] == 'completed') {
        $total_spent += $o['total_amount'];
        $completed_orders++;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>User History - <?php echo htmlspecialchars($user['name']); ?></title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .profile-header { background: white; padding: 20px; border-radius: 8px; display: flex; gap: 30px; align-items: center; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        .avatar { width: 80px; height: 80px; background: #3498db; color: white; font-size: 32px; display: flex; align-items: center; justify-content: center; border-radius: 50%; font-weight: bold; }
        .info h2 { margin: 0 0 5px; }
        .info p { margin: 2px 0; color: #666; }
        
        .stat-box { background: #f8f9fa; border: 1px solid #ddd; padding: 15px; border-radius: 8px; text-align: center; min-width: 150px; }
        .stat-val { font-size: 24px; font-weight: bold; color: #2c3e50; }
        
        .order-table { width: 100%; border-collapse: collapse; margin-top: 20px; background: white; }
        .order-table th { background: #f1f1f1; padding: 10px; text-align: left; }
        .order-table td { padding: 10px; border-bottom: 1px solid #eee; }
    </style>
</head>
<body>

   <?php include 'sidebar.php'; ?>

    <div class="content">
        <a href="users.php" style="display:inline-block; margin-bottom:15px; text-decoration:none;">&larr; Back to Users List</a>

        <div class="profile-header">
            <div class="avatar">
                <?php echo strtoupper(substr($user['name'], 0, 1)); ?>
            </div>
            <div class="info" style="flex: 1;">
                <h2><?php echo htmlspecialchars($user['name']); ?></h2>
                <p><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($user['email']); ?></p>
                <p><i class="fab fa-whatsapp"></i> <?php echo htmlspecialchars($user['phone']); ?></p>
                <p><i class="fas fa-calendar"></i> Joined: <?php echo date('d M Y', strtotime($user['created_at'])); ?></p>
                
                <?php if($user['phone']): ?>
                    <a href="https://wa.me/<?php echo $user['phone']; ?>" target="_blank" style="display:inline-block; margin-top:5px; color:#27ae60; font-weight:bold; text-decoration:none;">
                        <i class="fab fa-whatsapp"></i> Chat with Customer
                    </a>
                <?php endif; ?>
            </div>
            
            <div class="stat-box">
                <div class="stat-val">₹<?php echo number_format($total_spent); ?></div>
                <small>Lifetime Spent</small>
            </div>
            <div class="stat-box">
                <div class="stat-val"><?php echo $completed_orders; ?></div>
                <small>Paid Orders</small>
            </div>
        </div>

        <h3 style="margin-top: 40px;">Order History</h3>
        
        <?php if(empty($order_history)): ?>
            <p style="color: #777;">This user has not placed any orders yet.</p>
        <?php else: ?>
            <table class="order-table">
                <thead>
                    <tr>
                        <th>Order ID</th>
                        <th>Products Bought</th>
                        <th>Amount</th>
                        <th>Payment</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($order_history as $o): ?>
                    <tr>
                        <td>#<?php echo $o['id']; ?></td>
                        <td>
                            <?php echo $o['product_names'] ? htmlspecialchars($o['product_names']) : '<em>Item deleted</em>'; ?>
                        </td>
                        <td><strong>₹<?php echo number_format($o['total_amount']); ?></strong></td>
                        <td><?php echo $o['payment_method']; ?></td>
                        <td>
                            <?php 
                                $color = 'gray';
                                if($o['status'] == 'completed') $color = 'green';
                                if($o['status'] == 'pending') $color = 'orange';
                                if($o['status'] == 'cancelled') $color = 'red';
                            ?>
                            <span style="color:<?php echo $color; ?>; font-weight:bold; text-transform:capitalize;">
                                <?php echo $o['status']; ?>
                            </span>
                        </td>
                        <td><?php echo date('d M Y', strtotime($o['created_at'])); ?></td>
                        <td>
                            <a href="orders.php?id=<?php echo $o['id']; ?>" style="color: blue; text-decoration: none;">View Order</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>

    </div>

</body>
</html>