<?php
session_start();
require_once __DIR__ . '/../includes/db.php';

$docs = $pdo->query("
SELECT
  d.id,
  d.created_at,
  d.status,
  MAX(CASE WHEN f.code='po' THEN v.value END) AS po,
  MAX(CASE WHEN f.code='shipt_to' THEN v.value END) AS ship_to,
  MAX(CASE WHEN f.code='consignee' THEN v.value END) AS consignee
FROM bol_documents d
LEFT JOIN bol_values v ON v.bol_id = d.id
LEFT JOIN bol_fields f ON f.id = v.field_id
GROUP BY d.id
ORDER BY d.created_at DESC
")->fetchAll(PDO::FETCH_ASSOC);

include '../includes/header.php';
include '../includes/sidebar.php';
?>

<div class="container-fluid">
  <h3>Documents – Bill of Lading</h3>

 <a href="document_new.php" class="btn btn-success mb-3">+ New BOL</a>


  <button class="btn btn-outline-secondary mb-3"
          data-bs-toggle="collapse"
          data-bs-target="#documentsWrapper">
    Show / Hide Documents
  </button>

  <div class="collapse show" id="documentsWrapper">
    <table class="table table-bordered table-hover">
      <thead class="table-light">
        <tr>
          <th>ID</th>
          <th>PO</th>
          <th>Ship To</th>
          <th>Consignee</th>
          <th>Created</th>
          <th>Status</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($docs as $d): ?>
        <tr>
          <td><?= htmlspecialchars($d['id']) ?></td>
          <td><?= htmlspecialchars($d['po'] ?? '') ?></td>
          <td><?= htmlspecialchars($d['ship_to'] ?? '') ?></td>
          <td><?= htmlspecialchars($d['consignee'] ?? '') ?></td>
          <td><?= htmlspecialchars($d['created_at']) ?></td>
          <td><?= htmlspecialchars($d['status']) ?></td>
          <td>
            <a class="btn btn-sm btn-primary"
               href="documents.php?edit=<?= urlencode($d['id']) ?>">Edit</a>
            <a class="btn btn-sm btn-danger"
               href="document_delete.php?id=<?= urlencode($d['id']) ?>"
               onclick="return confirm('Delete this document?')">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <?php if (isset($_GET['edit'])): ?>
    <hr>
    <?php $_GET['id'] = $_GET['edit']; include __DIR__ . '/bol_editor_partial.php'; ?>
  <?php endif; ?>
</div>

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