<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('supplier_management');

$pdo = getDB();
$id = (int)($_GET['id'] ?? 0);
if (!$id) { $_SESSION['error'] = 'Invalid supplier ID.'; header('Location: suppliers.php'); exit; }

$stmt = $pdo->prepare("SELECT * FROM suppliers WHERE id = ?");
$stmt->execute([$id]);
$supplier = $stmt->fetch();
if (!$supplier) { $_SESSION['error'] = 'Supplier not found.'; header('Location: suppliers.php'); exit; }

$products = $pdo->prepare("SELECT * FROM products WHERE supplier_id = ? AND status = 1 ORDER BY product_name");
$products->execute([$id]);
$products_list = $products->fetchAll();

$purchases = $pdo->prepare("SELECT * FROM purchases WHERE supplier_id = ? ORDER BY purchase_date DESC");
$purchases->execute([$id]);
$purchases_list = $purchases->fetchAll();

$payments = $pdo->prepare("SELECT * FROM payments WHERE supplier_id = ? AND payment_type = 'supplier' ORDER BY payment_date DESC");
$payments->execute([$id]);
$payments_list = $payments->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-truck me-2"></i>Supplier Profile</h4>
            <a href="suppliers.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back to Suppliers</a>
        </div>
        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="card mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-8">
                        <h5 class="fw-bold mb-3"><?= htmlspecialchars($supplier['supplier_name']) ?> <code class="ms-2"><?= htmlspecialchars($supplier['supplier_code']) ?></code></h5>
                        <div class="row">
                            <div class="col-md-6 mb-2"><strong>Company:</strong> <?= htmlspecialchars($supplier['company_name'] ?? '-') ?></div>
                            <div class="col-md-6 mb-2"><strong>Contact Person:</strong> <?= htmlspecialchars($supplier['contact_person'] ?? '-') ?></div>
                            <div class="col-md-6 mb-2"><strong>Phone:</strong> <?= htmlspecialchars($supplier['phone']) ?></div>
                            <div class="col-md-6 mb-2"><strong>Email:</strong> <?= htmlspecialchars($supplier['email'] ?? '-') ?></div>
                            <div class="col-md-6 mb-2"><strong>Address:</strong> <?= htmlspecialchars($supplier['address'] ?? '-') ?></div>
                            <div class="col-md-6 mb-2"><strong>Opening Balance:</strong> <?= formatCurrency($supplier['opening_balance']) ?></div>
                        </div>
                    </div>
                    <div class="col-md-4 text-end">
                        <div class="mb-2">
                            <span class="badge" style="font-size:1rem;padding:8px 16px;background:<?= $supplier['status'] ? '#e8f5e9' : '#ffebee' ?>;color:<?= $supplier['status'] ? '#2e7d32' : '#c62828' ?>;">
                                <?= $supplier['status'] ? 'Active' : 'Inactive' ?>
                            </span>
                        </div>
                        <div class="mt-3">
                            <h2 class="fw-bold text-primary"><?= formatCurrency($supplier['current_balance']) ?></h2>
                            <small class="text-muted">Current Balance</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <ul class="nav nav-tabs mb-3" id="supplierTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="products-tab" data-bs-toggle="tab" data-bs-target="#products" type="button" role="tab"><i class="fas fa-boxes me-1"></i>Products (<?= count($products_list) ?>)</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="purchases-tab" data-bs-toggle="tab" data-bs-target="#purchases" type="button" role="tab"><i class="fas fa-shopping-bag me-1"></i>Purchases (<?= count($purchases_list) ?>)</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="payments-tab" data-bs-toggle="tab" data-bs-target="#payments" type="button" role="tab"><i class="fas fa-hand-holding-usd me-1"></i>Payments (<?= count($payments_list) ?>)</button>
            </li>
        </ul>

        <div class="tab-content" id="supplierTabsContent">
            <div class="tab-pane fade show active" id="products" role="tabpanel">
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="supplierProductsTable" class="table table-hover datatable">
                                <thead><tr><th>Code</th><th>Product Name</th><th>Type</th><th>Selling Price</th><th>Stock</th><th>Status</th></tr></thead>
                                <tbody>
                                    <?php if (!empty($products_list)): ?>
                                    <?php foreach ($products_list as $p): ?>
                                    <tr>
                                        <td><code><?= htmlspecialchars($p['product_code']) ?></code></td>
                                        <td><a href="<?= BASE_URL ?>products/products.php?view=<?= $p['id'] ?>"><?= htmlspecialchars($p['product_name']) ?></a></td>
                                        <td><span class="badge bg-secondary"><?= htmlspecialchars(ucfirst($p['product_type'] ?? 'N/A')) ?></span></td>
                                        <td><?= formatCurrency($p['selling_price']) ?></td>
                                        <td><?= (int)$p['current_stock'] ?></td>
                                        <td><?= getStockBadge($p['current_stock'], $p['low_stock_qty'] ?? 5) ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="purchases" role="tabpanel">
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="supplierPurchasesTable" class="table table-hover datatable">
                                <thead><tr><th>Purchase No</th><th>Date</th><th>Total</th><th>Paid</th><th>Due</th><th>Status</th><th>Actions</th></tr></thead>
                                <tbody>
                                    <?php if (!empty($purchases_list)): ?>
                                    <?php foreach ($purchases_list as $pr): ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($pr['purchase_no']) ?></strong></td>
                                        <td><?= formatDate($pr['purchase_date']) ?></td>
                                        <td><?= formatCurrency($pr['total_amount']) ?></td>
                                        <td><?= formatCurrency($pr['paid_amount']) ?></td>
                                        <td><span class="badge <?= $pr['due_amount'] > 0 ? 'badge-pending' : 'badge-completed' ?>"><?= formatCurrency($pr['due_amount']) ?></span></td>
                                        <td><?= getStatusBadge($pr['purchase_status']) ?></td>
                                        <td>
                                            <a href="view_purchase.php?id=<?= $pr['id'] ?>" class="btn btn-sm btn-outline-info"><i class="fas fa-eye"></i></a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="payments" role="tabpanel">
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="supplierPaymentsTable" class="table table-hover datatable">
                                <thead><tr><th>Payment No</th><th>Amount</th><th>Method</th><th>Date</th><th>Note</th></tr></thead>
                                <tbody>
                                    <?php if (!empty($payments_list)): ?>
                                    <?php foreach ($payments_list as $pmt): ?>
                                    <tr>
                                        <td><code><?= htmlspecialchars($pmt['payment_no'] ?? '-') ?></code></td>
                                        <td><strong><?= formatCurrency($pmt['amount']) ?></strong></td>
                                        <td><?= htmlspecialchars($pmt['payment_method']) ?></td>
                                        <td><?= formatDateTime($pmt['payment_date']) ?></td>
                                        <td><?= htmlspecialchars($pmt['note'] ?? '-') ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
