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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $item = trim($_POST['item']);
  $desc = trim($_POST['desc']);
  $cat = trim($_POST['cat']);
  $site = trim($_POST['site']);

  if (!empty($item) && !empty($cat) && isset($_FILES['pdf'])) {
    $filename = preg_replace('/[^a-zA-Z0-9\-_]/', '_', $item) . '.pdf';
    $target = $upload_dir . $filename;

    if (move_uploaded_file($_FILES['pdf']['tmp_name'], $target)) {
      $entry = ['item' => $item, 'desc' => $desc, 'cat' => $cat, 'site' => $site];
      $existing = file_exists($data_file) ? json_decode(file_get_contents($data_file), true) : [];
      $existing[] = $entry;
      file_put_contents($data_file, json_encode($existing, JSON_PRETTY_PRINT));
      echo 'success';
    } else {
      echo '❌ Failed to upload file.';
    }
  } else {
    echo '⚠️ Please fill all required fields.';
  }
  exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Upload Drawing</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);
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
    }

    .wrap {
      width: 100%;
      max-width: 600px;
      padding: 16px;
    }

    h1 {
      margin: 0 0 12px;
      font-size: clamp(24px, 4vw, 32px);
      text-align: center;
    }

    .muted {
      color: var(--muted);
      font-size: 14px;
      margin-bottom: 16px;
      text-align: center;
    }

    .card {
      background: var(--card);
      border: 1px solid #223;
      border-radius: 16px;
      padding: 24px;
      box-shadow: 0 10px 28px rgba(0, 0, 0, .25);
    }

    label {
      display: block;
      margin-bottom: 6px;
      font-weight: 500;
    }

    input, select {
      background: #666666;
      border: 1px solid #223;
      color: var(--text);
      padding: 10px 12px;
      border-radius: 12px;
      outline: none;
      width: 100%;
      margin-bottom: 14px;
      transition: box-shadow 0.2s ease, border-color 0.2s ease;
    }

    input:focus, select:focus {
      border-color: var(--accent);
      box-shadow: 0 0 0 2px rgba(111, 177, 255, 0.4);
    }

    .btn {
      background: var(--accent);
      color: #031225;
      border: 0;
      padding: 10px 14px;
      border-radius: 12px;
      font-weight: 700;
      cursor: pointer;
      width: 100%;
      transition: background 0.2s ease;
    }

    .btn:hover {
      background: #87c1ff;
    }

    #progressBar {
      width: 100%;
      height: 18px;
      margin-top: 16px;
      border-radius: 8px;
      overflow: hidden;
      background: #1a233b;
      border: 1px solid #223;
    }

    #progressFill {
      height: 100%;
      width: 0;
      background: var(--accent);
      transition: width .2s ease;
    }

    #statusMsg {
      margin-top: 12px;
      font-size: 14px;
      color: var(--muted);
      text-align: center;
    }

    .footer {
      text-align: center;
      margin-top: 18px;
      font-size: 13px;
      color: var(--muted);
    }

    .footer a {
      color: var(--accent);
      text-decoration: none;
    }

    .footer a:hover {
      text-decoration: underline;
    }
  </style>
</head>
<body>
  <div class="wrap">
    <h1>Upload Drawing</h1>
    <div class="muted">Upload a PDF and fill in all required fields</div>

    <div class="card">
      <form id="uploadForm">
        <label for="item">Item No.</label>
        <input type="text" id="item" name="item" required>

        <label for="desc">Description</label>
        <input type="text" id="desc" name="desc" required>

        <label for="cat">Category</label>
        <select name="cat" id="cat" required>
          <option value="">--Select--</option>
          <option value="T">T – Towers/Columns/Chimneys</option>
          <option value="R">R – Reactors</option>
          <option value="E">E – Exchangers/Heaters/Coolers</option>
          <option value="V">V – Vessels/Drums/Tanks</option>
          <option value="X">X – Filters/Arresters/Distributors</option>
          <option value="C">C – Compressors</option>
          <option value="TO">TO – Incinerators</option>
          <option value="TK">TK – Storage Tanks</option>
          <option value="NOZ">NOZ – Piping / Nozzle Orientation</option>
          <option value="Other">Other</option>
        </select>

        <label for="site">Site</label>
        <select name="site" id="site">
          <option value="">All sites</option>
          <option value="Tank Farm">Tank Farm</option>
          <option value="NPG">NPG</option>
          <option value="Incineration">Incineration</option>
          <option value="Flaking">Flaking</option>
        </select>

        <label for="pdf">PDF File</label>
        <input type="file" name="pdf" id="pdf" accept=".pdf" required>

        <button type="submit" class="btn">Upload</button>
      </form>

      <div id="progressBar"><div id="progressFill"></div></div>
      <div id="statusMsg"></div>
    </div>

    <div class="footer">
      <p><a href="index.html">← Back to list</a> | <a href="logout.php">Logout</a></p>
    </div>
  </div>

  <script>
  document.getElementById('uploadForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const form = e.target;
    const formData = new FormData(form);
    const xhr = new XMLHttpRequest();

    const fill = document.getElementById('progressFill');
    const msg = document.getElementById('statusMsg');

    fill.style.width = '0%';
    msg.textContent = 'Uploading...';

    xhr.upload.addEventListener('progress', function(e) {
      if (e.lengthComputable) {
        const percent = (e.loaded / e.total) * 100;
        fill.style.width = percent + '%';
      }
    });

    xhr.onload = function() {
      if (xhr.status === 200) {
        fill.style.width = '100%';
        msg.textContent = (xhr.responseText === 'success') ? '✅ Upload complete!' : xhr.responseText;
        form.reset();
      } else {
        msg.textContent = '❌ Upload failed';
      }
    };

    xhr.open('POST', 'upload.php');
    xhr.send(formData);
  });
  </script>
</body>
</html>
