<?php
require_once __DIR__ . '/../lib/core.php';
dc_require_login();
dc_require_csrf();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$door = null;
$error = '';

if ($id > 0) {
    $stmt = dc_db()->prepare('SELECT d.*, c.code category_code, p.project_number FROM door_cert_doors d JOIN door_cert_categories c ON c.id=d.category_id JOIN door_cert_projects p ON p.id=d.project_id WHERE d.id=?');
    $stmt->execute(array($id));
    $door = $stmt->fetch();
}

$categories = dc_db()->query('SELECT * FROM door_cert_categories ORDER BY code')->fetchAll();
$projects = dc_db()->query('SELECT * FROM door_cert_projects ORDER BY project_number')->fetchAll();
$standardRows = dc_db()->query('SELECT * FROM door_cert_standards WHERE is_active=1 ORDER BY name')->fetchAll();
$standardOptions = array();
foreach ($standardRows as $standardRow) {
    $standardOptions[] = $standardRow['name'];
}
foreach (dc_recent_field_values('standards', DC_DEFAULT_STANDARDS, 8) as $recentStandard) {
    foreach (dc_parse_standards($recentStandard) as $standardOption) {
        if (!in_array($standardOption, $standardOptions, true)) {
            $standardOptions[] = $standardOption;
        }
    }
}
$fireRatingOptions = dc_recent_field_values('fire_rating', 'FD 120', 8);
foreach (array('UL-10C, NFPA-252 & B.S 476 STANDARD', 'UL-10C, NFPA-252, FM 4100 & B.S 476 STANDARD') as $option) {
    if (!in_array($option, $standardOptions, true)) {
        $standardOptions[] = $option;
    }
}
foreach (array('FD 120', 'DFD 120') as $option) {
    if (!in_array($option, $fireRatingOptions, true)) {
        $fireRatingOptions[] = $option;
    }
}

$form = array(
    'id' => $door ? (int)$door['id'] : 0,
    'category_id' => $door ? (int)$door['category_id'] : ($categories ? (int)$categories[0]['id'] : 0),
    'project_id' => $door ? (int)$door['project_id'] : ($projects ? (int)$projects[0]['id'] : 0),
    'year' => $door ? substr($door['door_id'], strpos($door['door_id'], '-') + 1, 4) : date('Y'),
    'door_number' => $door ? $door['door_number'] : '1000',
    'po_number' => $door ? $door['po_number'] : '',
    'area_location' => $door ? $door['area_location'] : '',
    'fire_rating' => $door ? $door['fire_rating'] : dc_latest_field_value('fire_rating', 'FD 120'),
    'status' => $door ? $door['status'] : 'active',
    'standards' => $door ? $door['standards'] : dc_latest_field_value('standards', DC_DEFAULT_STANDARDS),
    'manufacture_date' => $door ? $door['manufacture_date'] : '',
    'valid_from' => $door ? $door['valid_from'] : '',
    'valid_to' => $door ? $door['valid_to'] : '',
    'notes' => $door ? $door['notes'] : '',
    'qr_token' => $door ? $door['qr_token'] : '',
);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach (array('id', 'category_id', 'project_id', 'year', 'door_number', 'po_number', 'area_location', 'fire_rating', 'status', 'manufacture_date', 'valid_from', 'valid_to', 'notes', 'qr_token') as $field) {
        if (isset($_POST[$field])) {
            $form[$field] = is_string($_POST[$field]) ? trim($_POST[$field]) : $_POST[$field];
        }
    }
    $form['standards'] = dc_store_standards(isset($_POST['standards']) ? $_POST['standards'] : array());

    $id = (int)$form['id'];
    $categoryId = (int)$form['category_id'];
    $projectId = (int)$form['project_id'];
    $doorNumber = trim($form['door_number']);
    $year = (int)$form['year'];

    $catStmt = dc_db()->prepare('SELECT * FROM door_cert_categories WHERE id=?');
    $catStmt->execute(array($categoryId));
    $category = $catStmt->fetch();
    $projectStmt = dc_db()->prepare('SELECT * FROM door_cert_projects WHERE id=?');
    $projectStmt->execute(array($projectId));
    $project = $projectStmt->fetch();

    if (!$category || !$project) {
        $error = 'Invalid project or category.';
    } else {
        $doorId = dc_build_door_id($category['code'], $year, $project['project_number'], $doorNumber);
        if ($door && (int)$door['category_id'] === $categoryId && (int)$door['project_id'] === $projectId && (string)$door['door_number'] === (string)$doorNumber && (string)$form['year'] === substr($door['door_id'], strpos($door['door_id'], '-') + 1, 4)) {
            $doorId = $door['door_id'];
        }

        if (dc_door_id_exists($doorId, $id)) {
            $error = 'Door ID ' . $doorId . ' is already assigned. Please choose another door number.';
        } else {
            $token = $id > 0 ? ($door ? $door['qr_token'] : $form['qr_token']) : dc_random_token();
            $data = array(
                $doorId, $categoryId, $projectId, $doorNumber, trim($form['po_number']), trim($form['area_location']),
                trim($form['fire_rating']), dc_store_standards($form['standards']), $form['manufacture_date'] ?: null,
                $form['valid_from'] ?: null, $form['valid_to'] ?: null, $form['status'], $token, trim($form['notes'])
            );

            try {
                if ($id > 0) {
                    $data[] = $id;
                    $stmt = dc_db()->prepare('UPDATE door_cert_doors SET door_id=?, category_id=?, project_id=?, door_number=?, po_number=?, area_location=?, fire_rating=?, standards=?, manufacture_date=?, valid_from=?, valid_to=?, status=?, qr_token=?, notes=? WHERE id=?');
                    $stmt->execute($data);
                } else {
                    $stmt = dc_db()->prepare('INSERT INTO door_cert_doors (door_id, category_id, project_id, door_number, po_number, area_location, fire_rating, standards, manufacture_date, valid_from, valid_to, status, qr_token, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
                    $stmt->execute($data);
                    $id = (int)dc_db()->lastInsertId();
                }

                $stmt = dc_db()->prepare('SELECT d.*, c.code category_code, p.project_number FROM door_cert_doors d JOIN door_cert_categories c ON c.id=d.category_id JOIN door_cert_projects p ON p.id=d.project_id WHERE d.id=?');
                $stmt->execute(array($id));
                $saved = $stmt->fetch();
                $qrPath = dc_save_qr($saved['door_id'], dc_verify_url($saved));
                if ($qrPath) {
                    $stmt = dc_db()->prepare('UPDATE door_cert_doors SET qr_image_path=? WHERE id=?');
                    $stmt->execute(array($qrPath, $id));
                }
                dc_flash('success', 'Door saved.');
                dc_redirect('admin/doors.php');
            } catch (PDOException $e) {
                $error = 'Door could not be saved. Please check that the door number is unique.';
            }
        }
    }
}

dc_admin_header($door ? 'Edit Door' : 'Add Door');
?>
<div class="dc-card">
  <?php if ($error): ?>
    <div class="dc-alert error"><?php echo dc_h($error); ?></div>
  <?php endif; ?>
  <?php if (!$categories || !$projects): ?>
    <div class="dc-alert error">Add at least one project and one category before creating doors.</div>
  <?php endif; ?>
  <form method="post" id="door-form">
    <?php echo dc_csrf_field(); ?>
    <input type="hidden" name="id" id="door-record-id" value="<?php echo dc_h($form['id']); ?>">
    <input type="hidden" name="qr_token" value="<?php echo dc_h($form['qr_token']); ?>">
    <div class="dc-grid">
      <div>
        <label>Category</label>
        <select name="category_id" id="category-id" required>
          <?php foreach ($categories as $category): ?>
            <option value="<?php echo (int)$category['id']; ?>" <?php echo (int)$form['category_id'] === (int)$category['id'] ? 'selected' : ''; ?>><?php echo dc_h($category['code'] . ' - ' . $category['name']); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label>Project</label>
        <select name="project_id" id="project-id" required>
          <?php foreach ($projects as $project): ?>
            <option value="<?php echo (int)$project['id']; ?>" <?php echo (int)$form['project_id'] === (int)$project['id'] ? 'selected' : ''; ?>><?php echo dc_h($project['project_number'] . ' - ' . $project['client_name']); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>
    <div class="dc-grid three">
      <div><label>Year</label><input id="door-year" name="year" type="number" value="<?php echo dc_h($form['year']); ?>" required></div>
      <div><label>Door Number</label><input id="door-number" name="door_number" value="<?php echo dc_h($form['door_number']); ?>" required><div id="door-id-check" class="dc-help"></div></div>
      <div><label>PO Number</label><input name="po_number" value="<?php echo dc_h($form['po_number']); ?>"></div>
    </div>
    <label>Area / Location</label><input name="area_location" value="<?php echo dc_h($form['area_location']); ?>">
    <div class="dc-grid">
      <div>
        <label>Fire Rating</label>
        <input name="fire_rating" list="fire-rating-options" value="<?php echo dc_h($form['fire_rating']); ?>">
        <datalist id="fire-rating-options">
          <?php foreach ($fireRatingOptions as $option): ?>
            <option value="<?php echo dc_h($option); ?>"></option>
          <?php endforeach; ?>
        </datalist>
      </div>
      <div><label>Status</label><select name="status"><option value="active" <?php echo $form['status'] === 'active' ? 'selected' : ''; ?>>Active</option><option value="expired" <?php echo $form['status'] === 'expired' ? 'selected' : ''; ?>>Expired</option><option value="suspended" <?php echo $form['status'] === 'suspended' ? 'selected' : ''; ?>>Suspended</option></select></div>
    </div>
    <label>Standards</label>
    <?php $selectedStandards = dc_parse_standards($form['standards']); ?>
    <select name="standards[]" multiple size="5">
      <?php foreach ($standardOptions as $option): ?>
        <option value="<?php echo dc_h($option); ?>" <?php echo in_array($option, $selectedStandards, true) ? 'selected' : ''; ?>><?php echo dc_h($option); ?></option>
      <?php endforeach; ?>
    </select>
    <div class="dc-help">Hold Ctrl to select multiple standards. Manage this list from Standards.</div>
    <div class="dc-grid">
      <div><label>Manufacture Date</label><input id="manufacture-date" name="manufacture_date" type="date" value="<?php echo dc_h($form['manufacture_date']); ?>"></div>
      <div><label>Valid From</label><input id="valid-from" name="valid_from" type="date" value="<?php echo dc_h($form['valid_from']); ?>"></div>
    </div>
    <label>Valid To</label><input id="valid-to" name="valid_to" type="date" value="<?php echo dc_h($form['valid_to']); ?>">
    <label>Notes</label><textarea name="notes" rows="3"><?php echo dc_h($form['notes']); ?></textarea>
    <p><button type="submit" id="save-door">Save Door</button></p>
  </form>
</div>
<script>
(function () {
  var form = document.getElementById('door-form');
  var saveButton = document.getElementById('save-door');
  var checkBox = document.getElementById('door-id-check');
  var fields = ['category-id', 'project-id', 'door-year', 'door-number'];
  var timer = null;

  function pad(number) {
    return String(number).padStart(2, '0');
  }

  function addYears(dateValue, years) {
    var parts = dateValue.split('-').map(Number);
    if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {
      return '';
    }
    var year = parts[0] + years;
    var month = parts[1];
    var day = Math.min(parts[2], new Date(year, month, 0).getDate());
    return year + '-' + pad(month) + '-' + pad(day);
  }

  document.getElementById('manufacture-date').addEventListener('change', function () {
    if (!this.value) {
      return;
    }
    document.getElementById('valid-from').value = this.value;
    document.getElementById('valid-to').value = addYears(this.value, 5);
  });

  function runDoorCheck() {
    var params = new URLSearchParams();
    params.set('id', document.getElementById('door-record-id').value || '0');
    params.set('category_id', document.getElementById('category-id').value);
    params.set('project_id', document.getElementById('project-id').value);
    params.set('year', document.getElementById('door-year').value);
    params.set('door_number', document.getElementById('door-number').value);
    if (!params.get('category_id') || !params.get('project_id') || !params.get('year') || !params.get('door_number')) {
      return;
    }

    fetch('check-door-id.php?' + params.toString(), { credentials: 'same-origin' })
      .then(function (response) { return response.json(); })
      .then(function (data) {
        checkBox.className = data.exists ? 'dc-help error' : 'dc-help success';
        checkBox.textContent = data.exists ? data.door_id + ' is already assigned.' : data.door_id + ' is available.';
        saveButton.disabled = !!data.exists;
      })
      .catch(function () {
        checkBox.className = 'dc-help';
        checkBox.textContent = '';
        saveButton.disabled = false;
      });
  }

  fields.forEach(function (id) {
    var el = document.getElementById(id);
    if (!el) {
      return;
    }
    el.addEventListener('input', function () {
      window.clearTimeout(timer);
      timer = window.setTimeout(runDoorCheck, 250);
    });
    el.addEventListener('change', runDoorCheck);
  });
  runDoorCheck();

  form.addEventListener('submit', function (event) {
    if (saveButton.disabled) {
      event.preventDefault();
    }
  });
})();
</script>
<?php dc_footer(); ?>
