<?php
include '../config.php';

$customer_id = $_GET['id'] ?? 0;

// Get customer details
$stmt = $conn->prepare("SELECT * FROM customers WHERE id = ?");
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$customer = $stmt->get_result()->fetch_assoc();

if (!$customer) {
    header('Location: ./');
    exit;
}

// Get customer's purchase history
$stmt = $conn->prepare("
    SELECT s.*, 
           COUNT(si.id) as item_count,
           GROUP_CONCAT(p.name SEPARATOR ', ') as products
    FROM sales s 
    LEFT JOIN sale_items si ON s.id = si.sale_id
    LEFT JOIN products p ON si.product_id = p.id
    WHERE s.customer_id = ?
    GROUP BY s.id
    ORDER BY s.sale_date DESC
");
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$purchases = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get summary stats
$stmt = $conn->prepare("
    SELECT 
        COUNT(*) as total_orders,
        SUM(total_amount) as total_spent,
        AVG(total_amount) as avg_order,
        MAX(sale_date) as last_purchase
    FROM sales 
    WHERE customer_id = ?
");
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$stats = $stmt->get_result()->fetch_assoc();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Customer History - <?= htmlspecialchars($customer['name']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; }
        .container { margin-top: 40px; }
        .customer-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; }
        .stat-card { border: none; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
    </style>
</head>
<body>
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="fw-bold"><i class="fas fa-user"></i> Customer History</h1>
            <div>
                <a href="../pos/" class="btn btn-success me-2"><i class="fas fa-cash-register"></i> New Sale</a>
                <a href="./" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
            </div>
        </div>

        <!-- Customer Info Header -->
        <div class="customer-header p-4 mb-4">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h2><?= htmlspecialchars($customer['name']) ?></h2>
                    <div class="mt-2">
                        <?php if ($customer['phone']): ?>
                        <span class="me-3"><i class="fas fa-phone"></i> <?= htmlspecialchars($customer['phone']) ?></span>
                        <?php endif; ?>
                        <?php if ($customer['email']): ?>
                        <span><i class="fas fa-envelope"></i> <?= htmlspecialchars($customer['email']) ?></span>
                        <?php endif; ?>
                    </div>
                    <?php if ($customer['address']): ?>
                    <div class="mt-2">
                        <i class="fas fa-map-marker-alt"></i> <?= htmlspecialchars($customer['address']) ?>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="col-md-6 text-end">
                    <div class="h4 mb-1">Customer Since</div>
                    <div><?= date('M d, Y', strtotime($customer['created_at'])) ?></div>
                </div>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card stat-card text-center p-3">
                    <i class="fas fa-shopping-bag fa-2x text-primary mb-2"></i>
                    <h4><?= $stats['total_orders'] ?? 0 ?></h4>
                    <small class="text-muted">Total Orders</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card text-center p-3">
                    <i class="fas fa-dollar-sign fa-2x text-success mb-2"></i>
                    <h4>$<?= number_format($stats['total_spent'] ?? 0, 2) ?></h4>
                    <small class="text-muted">Total Spent</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card text-center p-3">
                    <i class="fas fa-chart-line fa-2x text-info mb-2"></i>
                    <h4>$<?= number_format($stats['avg_order'] ?? 0, 2) ?></h4>
                    <small class="text-muted">Avg Order</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card text-center p-3">
                    <i class="fas fa-calendar fa-2x text-warning mb-2"></i>
                    <h4><?= $stats['last_purchase'] ? date('M d', strtotime($stats['last_purchase'])) : 'Never' ?></h4>
                    <small class="text-muted">Last Purchase</small>
                </div>
            </div>
        </div>

        <!-- Purchase History -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5><i class="fas fa-history"></i> Purchase History</h5>
                <span class="badge bg-primary"><?= count($purchases) ?> transactions</span>
            </div>
            <div class="card-body p-0">
                <?php if (empty($purchases)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">No purchases yet</h5>
                    <a href="../pos/" class="btn btn-primary">Start First Sale</a>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped mb-0">
                        <thead class="table-dark">
                            <tr>
                                <th>Order #</th>
                                <th>Date</th>
                                <th>Items</th>
                                <th>Products</th>
                                <th>Payment</th>
                                <th>Total</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($purchases as $purchase): ?>
                            <tr>
                                <td><strong>#<?= $purchase['id'] ?></strong></td>
                                <td><?= date('M d, Y H:i', strtotime($purchase['sale_date'])) ?></td>
                                <td>
                                    <span class="badge bg-secondary"><?= $purchase['item_count'] ?> items</span>
                                </td>
                                <td>
                                    <small class="text-muted"><?= htmlspecialchars(substr($purchase['products'], 0, 50)) ?><?= strlen($purchase['products']) > 50 ? '...' : '' ?></small>
                                </td>
                                <td>
                                    <span class="badge bg-<?= $purchase['payment_method'] === 'cash' ? 'success' : 'primary' ?>">
                                        <?= strtoupper($purchase['payment_method']) ?>
                                    </span>
                                </td>
                                <td class="fw-bold text-success">$<?= number_format($purchase['total_amount'], 2) ?></td>
                                <td>
                                    <a href="../pos/receipt.php?id=<?= $purchase['id'] ?>" class="btn btn-sm btn-outline-primary" target="_blank">
                                        <i class="fas fa-receipt"></i> Receipt
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
