<?php
// public/supplier_view.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin', 'staff']);

$pdo = db();
$title = "Supplier View - IMS";

$supplier_id = (int)($_GET['id'] ?? 0);
if ($supplier_id <= 0) {
    http_response_code(400);
    die("Invalid supplier ID.");
}

// Load supplier (including optional fields)
$ss = $pdo->prepare("
  SELECT
    id, supplier_code, name, city, country, is_active, created_at,
    contact_person, phone, email, address
  FROM suppliers
  WHERE id = :id
  LIMIT 1
");
$ss->execute([':id' => $supplier_id]);
$supplier = $ss->fetch();

if (!$supplier) {
    http_response_code(404);
    die("Supplier not found.");
}

// Products for this supplier + current stock
$ps = $pdo->prepare("
  SELECT
    p.id, p.sku, p.name, p.unit, p.sell_price, p.cost_price, p.reorder_level, p.is_active,
    c.name AS category_name,
    (
      COALESCE(SUM(CASE WHEN m.movement_type='IN' THEN m.quantity ELSE 0 END),0)
      - COALESCE(SUM(CASE WHEN m.movement_type='OUT' THEN m.quantity ELSE 0 END),0)
      + COALESCE(SUM(CASE WHEN m.movement_type='ADJUST' THEN m.quantity ELSE 0 END),0)
    ) AS current_stock
  FROM products p
  LEFT JOIN product_categories c ON c.id = p.category_id
  LEFT JOIN inventory_movements m ON m.product_id = p.id
  WHERE p.supplier_id = :sid
  GROUP BY p.id
  ORDER BY p.name ASC
");
$ps->execute([':sid' => $supplier_id]);
$products = $ps->fetchAll();

// Totals
$total_products = count($products);
$total_stock_units = 0;
$total_stock_cost = 0.0;
$total_stock_sell = 0.0;

foreach ($products as $p) {
    $stock = (int)($p['current_stock'] ?? 0);
    $total_stock_units += $stock;
    $total_stock_cost += $stock * (float)($p['cost_price'] ?? 0);
    $total_stock_sell += $stock * (float)($p['sell_price'] ?? 0);
}

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <div>
      <h4 class="mb-0">
        Supplier: <?= htmlspecialchars($supplier['name']) ?>
        <?php if (!empty($supplier['supplier_code'])): ?>
          <span class="text-muted">(<?= htmlspecialchars($supplier['supplier_code']) ?>)</span>
        <?php endif; ?>
      </h4>
      <div class="text-muted small">
        <?= htmlspecialchars(($supplier['city'] ?? '-') . ', ' . ($supplier['country'] ?? '-')) ?>
        · Status: <?= ((int)$supplier['is_active'] === 1) ? 'Active' : 'Inactive' ?>
      </div>
    </div>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-primary btn-sm" href="suppliers.php?edit=<?= (int)$supplier['id'] ?>">Edit</a>
      <a class="btn btn-outline-secondary btn-sm" href="suppliers.php">Back</a>
    </div>
  </div>

  <!-- Supplier details (including optional info) -->
  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <div class="row g-3">
        <div class="col-12 col-md-6">
          <div class="small text-muted">Code</div>
          <div class="fw-semibold"><?= htmlspecialchars($supplier['supplier_code'] ?? '-') ?></div>
        </div>

        <div class="col-12 col-md-6">
          <div class="small text-muted">Created</div>
          <div class="fw-semibold"><?= htmlspecialchars($supplier['created_at'] ?? '-') ?></div>
        </div>

        <div class="col-12 col-md-6">
          <div class="small text-muted">City</div>
          <div class="fw-semibold"><?= htmlspecialchars($supplier['city'] ?? '-') ?></div>
        </div>

        <div class="col-12 col-md-6">
          <div class="small text-muted">Country</div>
          <div class="fw-semibold"><?= htmlspecialchars($supplier['country'] ?? '-') ?></div>
        </div>
      </div>

      <!-- More details (optional) -->
      <div class="accordion mt-3" id="moreDetailsAcc">
        <div class="accordion-item">
          <h2 class="accordion-header" id="headingMore">
            <button class="accordion-button collapsed" type="button"
                    data-bs-toggle="collapse" data-bs-target="#collapseMore"
                    aria-expanded="false" aria-controls="collapseMore">
              More details (optional)
            </button>
          </h2>
          <div id="collapseMore" class="accordion-collapse collapse"
               aria-labelledby="headingMore" data-bs-parent="#moreDetailsAcc">
            <div class="accordion-body">
              <div class="row g-3">
                <div class="col-12 col-md-6">
                  <div class="small text-muted">Contact Person</div>
                  <div class="fw-semibold"><?= htmlspecialchars($supplier['contact_person'] ?? '-') ?></div>
                </div>

                <div class="col-12 col-md-6">
                  <div class="small text-muted">Phone</div>
                  <div class="fw-semibold"><?= htmlspecialchars($supplier['phone'] ?? '-') ?></div>
                </div>

                <div class="col-12 col-md-6">
                  <div class="small text-muted">Email</div>
                  <div class="fw-semibold"><?= htmlspecialchars($supplier['email'] ?? '-') ?></div>
                </div>

                <div class="col-12">
                  <div class="small text-muted">Address</div>
                  <div class="fw-semibold">
                    <?= !empty($supplier['address'])
                      ? nl2br(htmlspecialchars($supplier['address']))
                      : '-' ?>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>

  <!-- Summary cards -->
  <div class="row g-3 mb-3">
    <div class="col-12 col-md-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <div class="text-muted small">Products</div>
          <div class="fs-4 fw-semibold"><?= (int)$total_products ?></div>
        </div>
      </div>
    </div>
    <div class="col-12 col-md-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <div class="text-muted small">Total Stock Units</div>
          <div class="fs-4 fw-semibold"><?= (int)$total_stock_units ?></div>
        </div>
      </div>
    </div>
    <div class="col-12 col-md-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <div class="text-muted small">Estimated Stock Value</div>
          <div class="fw-semibold">Cost: <?= number_format($total_stock_cost, 2) ?></div>
          <div class="fw-semibold">Sell: <?= number_format($total_stock_sell, 2) ?></div>
        </div>
      </div>
    </div>
  </div>

  <!-- Products table -->
  <div class="card shadow-sm">
    <div class="card-body">
      <h6 class="mb-3">Products from this Supplier</h6>

      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <thead>
            <tr>
              <th>SKU</th>
              <th>Name</th>
              <th>Category</th>
              <th>Unit</th>
              <th class="text-end">Stock</th>
              <th class="text-end">Sell</th>
              <th class="text-center">Active</th>
              <th style="width:220px;"></th>
            </tr>
          </thead>
          <tbody>
            <?php if (!$products): ?>
              <tr><td colspan="8" class="text-muted">No products linked to this supplier yet.</td></tr>
            <?php else: ?>
              <?php foreach ($products as $p): ?>
                <?php
                  $stock = (int)($p['current_stock'] ?? 0);
                  $reorder = (int)($p['reorder_level'] ?? 0);
                  $low = ($reorder > 0 && $stock <= $reorder);
                ?>
                <tr class="<?= $low ? 'table-warning' : '' ?>">
                  <td><?= htmlspecialchars($p['sku']) ?></td>
                  <td><?= htmlspecialchars($p['name']) ?></td>
                  <td><?= htmlspecialchars($p['category_name'] ?? '-') ?></td>
                  <td><?= htmlspecialchars($p['unit'] ?? '-') ?></td>
                  <td class="text-end fw-semibold"><?= $stock ?></td>
                  <td class="text-end"><?= number_format((float)$p['sell_price'], 2) ?></td>
                  <td class="text-center"><?= ((int)$p['is_active'] === 1) ? '✅' : '❌' ?></td>
                  <td class="text-end">
                    <a class="btn btn-outline-dark btn-sm" href="product_stock_history.php?product_id=<?= (int)$p['id'] ?>">History</a>
                    <a class="btn btn-outline-primary btn-sm" href="products.php?edit=<?= (int)$p['id'] ?>">Edit</a>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <div class="text-muted small">
        Highlighted rows = stock at/under reorder level.
      </div>
    </div>
  </div>
</main>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
