<?php
session_start();
if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in']) {
  header('Location: login.php');
  exit;
}

$data_file = 'data.json';
$upload_dir = 'drawings/';

$msg = '';

// Handle delete request
if (isset($_POST['delete']) && isset($_POST['item'])) {
  $item = $_POST['item'];
  // read existing data
  $dataArr = [];
  if (file_exists($data_file)) {
    $dataArr = json_decode(file_get_contents($data_file), true) ?: [];
  }
  // filter out the entry with matching item
  $newArr = [];
  foreach ($dataArr as $entry) {
    if ($entry['item'] !== $item) {
      $newArr[] = $entry;
    } else {
      // attempt to delete the file
      $filename = preg_replace('/[^a-zA-Z0-9\-_]/', '_', $entry['item']) . '.pdf';
      $filepath = $upload_dir . $filename;
      if (is_file($filepath)) {
        unlink($filepath);
      }
    }
  }
  // save back
  file_put_contents($data_file, json_encode($newArr, JSON_PRETTY_PRINT));
  $msg = "✅ Deleted item: " . htmlspecialchars($item);
}

// Load data for listing
$dataArr = [];
if (file_exists($data_file)) {
  $dataArr = json_decode(file_get_contents($data_file), true) ?: [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF‑8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Manage Drawings</title>
  <style>
    :root {
      --bg: #0b1020;
      --card: #121830;
      --muted: #a9b3c9;
      --text: #e9edf6;
      --accent: #6fb1ff;
    }
    html, body {
      margin: 0;
      background: linear-gradient(180deg, #0b1020, #0c1430);
    }
    body {
      font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, sans-serif;
      color: var(--text);
    }
    .wrap {
      max-width: 1000px;
      margin: 32px auto;
      padding: 0 16px;
    }
    h1 {
      margin: 0 0 8px;
      font-size: clamp(22px,3vw,30px);
    }
    .muted {
      color: var(--muted);
      font-size: 14px;
      margin-bottom: 16px;
    }
    .card {
      background: var(--card);
      border: 1px solid #223;
      border-radius: 16px;
      box-shadow: 0 10px 28px rgba(0,0,0,.25);
      overflow: auto;
    }
    table {
      width: 100%;
      border-collapse: separate;
      border-spacing: 0;
    }
    th {
      position: sticky;
      top: 0;
      background: #101734;
      text-align: left;
      padding: 12px;
      border-bottom: 1px solid #223;
    }
    td {
      padding: 12px;
      border-bottom: 1px solid #1a2444;
      color: var(--text);
    }
    tr:hover {
      background: #0f1a3a;
    }
    .btn-delete {
      background: #ff6b6b;
      color: #031225;
      border: 0;
      padding: 6px 10px;
      border-radius: 8px;
      font-weight: 600;
      cursor: pointer;
    }
    .btn-delete:hover {
      background: #ff8787;
    }
    .status-msg {
      margin: 12px 0;
      color: var(--accent);
      font-size: 14px;
    }
    .foot-links {
      margin-top: 16px;
      font-size: 14px;
      color: var(--muted);
    }
    .foot-links a {
      color: var(--accent);
      text-decoration: none;
    }
    .foot-links a:hover {
      text-decoration: underline;
    }
  </style>
</head>
<body>
  <div class="wrap">
    <h1>Manage Equipment Drawings</h1>
    <div class="muted">View and delete drawings (Item No. + metadata + file). <a href="index.html" style="color:var(--accent)">← Back to list</a> | <a href="logout.php" style="color:var(--accent)">Logout</a></div>

    <?php if (!empty($msg)): ?>
      <div class="status-msg"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>

    <div class="card" style="padding:12px 16px">
      <table>
        <thead>
          <tr>
            <th>Item No.</th>
            <th>Description</th>
            <th>Category</th>
            <th>Site</th>
            <th>File</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($dataArr)): ?>
            <tr><td colspan="6" style="text-align:center;color:var(--muted)">No entries found.</td></tr>
          <?php else: ?>
            <?php foreach ($dataArr as $entry): ?>
              <?php
                $filename = preg_replace('/[^a-zA-Z0-9\-_]/', '_', $entry['item']) . '.pdf';
              ?>
              <tr>
                <td><code><?= htmlspecialchars($entry['item']) ?></code></td>
                <td><?= htmlspecialchars($entry['desc']) ?></td>
                <td><span><?= htmlspecialchars($entry['cat']) ?></span></td>
                <td><span><?= htmlspecialchars($entry['site']) ?></span></td>
                <td><a href="drawings/<?= htmlspecialchars($filename) ?>" target="_blank" style="color:var(--accent);text-decoration:none"><?= htmlspecialchars($filename) ?></a></td>
                <td>
                  <form method="post" style="margin:0">
                    <input type="hidden" name="item" value="<?= htmlspecialchars($entry['item']) ?>">
                    <button type="submit" name="delete" class="btn-delete" onclick="return confirm('Delete item <?= addslashes(htmlspecialchars($entry['item'])) ?> and its file?')">Delete</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <div class="foot-links">
      <p>© <?= date('Y') ?> Your Company</p>
    </div>
  </div>
</body>
</html>
