<?php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

if (!isset($_SESSION['user']['id'])) {
    header("Location: ../auth/login.php");
    exit();
}

if (!isset($_GET['supplier_id']) || !is_numeric($_GET['supplier_id'])) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-danger'>Invalid supplier ID.</div>
            <a href='../suppliers/supplier_list.php' class='btn btn-secondary'>Back to Suppliers</a>
          </div>";
    require_once '../includes/footer.php';
    exit();
}

$supplier_id = (int)$_GET['supplier_id'];

// Get supplier details
$supplierStmt = $pdo->prepare("SELECT * FROM suppliers WHERE id = ?");
$supplierStmt->execute([$supplier_id]);
$supplier = $supplierStmt->fetch(PDO::FETCH_ASSOC);

if (!$supplier) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-danger'>Supplier not found.</div>
            <a href='../suppliers/supplier_list.php' class='btn btn-secondary'>Back to Suppliers</a>
          </div>";
    require_once '../includes/footer.php';
    exit();
}

// Get purchases for this supplier
$purchaseStmt = $pdo->prepare("
    SELECT p.*, 
           u.fullname as created_by_name,
           COUNT(pl.id) as item_count,
           COALESCE(SUM(pl.qty * pl.cost_price), 0) as total_value
    FROM purchases p
    LEFT JOIN users u ON p.created_by = u.id
    LEFT JOIN purchase_lines pl ON p.id = pl.purchase_id
    WHERE p.supplier_id = ?
    GROUP BY p.id
    ORDER BY p.purchase_date DESC, p.id DESC
");
$purchaseStmt->execute([$supplier_id]);
$purchases = $purchaseStmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate totals
$totalPurchases = count($purchases);
$totalAmount = 0;
foreach ($purchases as $purchase) {
    $totalAmount += $purchase['total'] ?: $purchase['total_value'];
}
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="text-primary">
                <i class="fas fa-shopping-cart"></i> Purchase History
            </h3>
            <p class="mb-0">
                Supplier: <strong><?= htmlspecialchars($supplier['name']) ?></strong>
                <?php if ($supplier['contact']): ?> | Contact: <?= htmlspecialchars($supplier['contact']) ?><?php endif; ?>
            </p>
        </div>
        <div>
            <a href="../suppliers/supplier_list.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Suppliers
            </a>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card bg-info text-white">
                <div class="card-body text-center">
                    <h5><i class="fas fa-list"></i> Total Purchases</h5>
                    <h2><?= $totalPurchases ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card bg-success text-white">
                <div class="card-body text-center">
                    <h5><i class="fas fa-money-bill-wave"></i> Total Amount</h5>
                    <h2>TSh <?= number_format($totalAmount, 2) ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card bg-warning text-dark">
                <div class="card-body text-center">
                    <h5><i class="fas fa-calendar"></i> Supplier Since</h5>
                    <h4><?= date('d/m/Y', strtotime($supplier['created_at'])) ?></h4>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header bg-light">
            <h5 class="mb-0">Purchase Records</h5>
        </div>
        <div class="card-body">
            <?php if (empty($purchases)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                    <h5>No purchases found for this supplier</h5>
                    <p class="text-muted">This supplier has no purchase records yet.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead class="thead-dark">
                            <tr>
                                <th>Invoice #</th>
                                <th>Date</th>
                                <th>Items</th>
                                <th>Amount</th>
                                <th>Created By</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($purchases as $purchase): ?>
                                <tr>
                                    <td>
                                        <strong><?= htmlspecialchars($purchase['invoice_no']) ?></strong>
                                    </td>
                                    <td><?= date('d/m/Y', strtotime($purchase['purchase_date'])) ?></td>
                                    <td><?= $purchase['item_count'] ?> items</td>
                                    <td class="font-weight-bold">
                                        TSh <?= number_format($purchase['total'] ?: $purchase['total_value'], 2) ?>
                                    </td>
                                    <td><?= htmlspecialchars($purchase['created_by_name'] ?? 'Unknown') ?></td>
                                    <td>
                                        <a href="view_purchase.php?id=<?= $purchase['id'] ?>" 
                                           class="btn btn-sm btn-info" 
                                           title="View Details">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>