<?php
$mappings = is_array($mappings ?? null) ? $mappings : [];
$scripts = is_array($scripts ?? null) ? $scripts : [];
?>

<section class="card">
  <h2 class="section-title"><?= $e($t('settings.project_mapping.title')) ?></h2>
  <p class="muted mt-4"><?= $e($t('settings.project_mapping.description')) ?></p>

  <?php if (!empty($errorMessage)): ?>
    <div class="alert alert--danger mt-12" role="alert"><?= $e((string) $errorMessage) ?></div>
  <?php endif; ?>
  <?php if (!empty($successMessage)): ?>
    <div class="alert alert--success mt-12" role="status"><?= $e((string) $successMessage) ?></div>
  <?php endif; ?>
</section>

<section class="card mt-12">
  <h3 class="section-title"><?= $e($t('settings.project_mapping.add_title')) ?></h3>
  <form action="/settings/project-mappings" method="post" class="pm-form mt-8" novalidate>
    <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">

    <div class="pm-form__row">
      <label class="form-field pm-form__field">
        <span class="field-label"><?= $e($t('settings.project_mapping.fields.pattern')) ?></span>
        <input class="form-control" type="text" name="product_name_pattern" placeholder="<?= $e($t('settings.project_mapping.placeholders.pattern')) ?>" required>
      </label>

      <label class="form-field pm-form__field">
        <span class="field-label"><?= $e($t('settings.project_mapping.fields.script')) ?></span>
        <select class="form-control" name="script_name" required>
          <option value="">-- <?= $e($t('settings.project_mapping.placeholders.script')) ?> --</option>
          <?php foreach ($scripts as $script): ?>
            <option value="<?= $e($script) ?>"><?= $e($script) ?></option>
          <?php endforeach; ?>
        </select>
      </label>

      <label class="form-field pm-form__field">
        <span class="field-label"><?= $e($t('settings.project_mapping.fields.output_dir')) ?></span>
        <input class="form-control" type="text" name="output_dir" placeholder="<?= $e($t('settings.project_mapping.placeholders.output_dir')) ?>">
      </label>

      <label class="form-field pm-form__field pm-form__field--check">
        <span class="field-label">&nbsp;</span>
        <span class="checkbox-row">
          <input type="checkbox" name="requires_photo" value="1">
          <?= $e($t('settings.project_mapping.fields.requires_photo')) ?>
        </span>
      </label>

      <div class="pm-form__actions">
        <button type="submit" class="btn btn--action"><?= $e($t('settings.project_mapping.actions.add')) ?></button>
      </div>
    </div>
  </form>
</section>

<section class="card mt-12">
  <h3 class="section-title"><?= $e($t('settings.project_mapping.list_title')) ?></h3>

  <?php if (empty($mappings)): ?>
    <p class="muted mt-8"><?= $e($t('settings.project_mapping.empty')) ?></p>
  <?php else: ?>
    <table class="table mt-8">
      <thead>
        <tr>
          <th><?= $e($t('settings.project_mapping.fields.pattern')) ?></th>
          <th><?= $e($t('settings.project_mapping.fields.script')) ?></th>
          <th><?= $e($t('settings.project_mapping.fields.output_dir')) ?></th>
          <th class="text-center"><?= $e($t('settings.project_mapping.fields.requires_photo')) ?></th>
          <th class="text-center"><?= $e($t('settings.project_mapping.fields.active')) ?></th>
          <th class="text-center"><?= $e($t('settings.project_mapping.fields.actions')) ?></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($mappings as $mapping): ?>
          <tr class="pm-row<?= !$mapping['is_active'] ? ' pm-row--inactive' : '' ?>" data-id="<?= (int) $mapping['id'] ?>">
            <td class="pm-row__pattern"><?= $e((string) $mapping['product_name_pattern']) ?></td>
            <td class="pm-row__script"><?= $e((string) $mapping['script_name']) ?></td>
            <td class="pm-row__dir"><?= $e((string) ($mapping['output_dir'] ?? '-')) ?></td>
            <td class="text-center"><?= !empty($mapping['requires_photo']) ? '✓' : '' ?></td>
            <td class="text-center">
              <form action="/settings/project-mappings/<?= (int) $mapping['id'] ?>/toggle" method="post" class="inline-form">
                <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
                <button type="submit" class="btn btn--sm <?= $mapping['is_active'] ? 'btn--success' : 'btn--muted' ?>">
                  <?= $mapping['is_active'] ? $e($t('settings.project_mapping.status.active')) : $e($t('settings.project_mapping.status.inactive')) ?>
                </button>
              </form>
            </td>
            <td class="text-center pm-row__actions">
              <button type="button" class="btn btn--sm btn--outline js-pm-edit"
                data-id="<?= (int) $mapping['id'] ?>"
                data-pattern="<?= $e((string) $mapping['product_name_pattern']) ?>"
                data-script="<?= $e((string) $mapping['script_name']) ?>"
                data-output-dir="<?= $e((string) ($mapping['output_dir'] ?? '')) ?>"
                data-requires-photo="<?= !empty($mapping['requires_photo']) ? '1' : '0' ?>">
                <?= $e($t('settings.project_mapping.actions.edit')) ?>
              </button>
              <button type="button" class="btn btn--sm btn--danger js-pm-delete"
                data-id="<?= (int) $mapping['id'] ?>"
                data-token="<?= $e($csrfToken ?? '') ?>">
                <?= $e($t('settings.project_mapping.actions.delete')) ?>
              </button>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>
</section>

<!-- Modal edycji -->
<div id="pm-edit-modal" class="pm-modal" style="display:none;">
  <div class="pm-modal__overlay js-pm-modal-close"></div>
  <div class="pm-modal__content card">
    <h3 class="section-title"><?= $e($t('settings.project_mapping.edit_title')) ?></h3>
    <form id="pm-edit-form" method="post" novalidate>
      <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">

      <label class="form-field mt-8">
        <span class="field-label"><?= $e($t('settings.project_mapping.fields.pattern')) ?></span>
        <input class="form-control" type="text" name="product_name_pattern" required>
      </label>

      <label class="form-field mt-8">
        <span class="field-label"><?= $e($t('settings.project_mapping.fields.script')) ?></span>
        <select class="form-control" name="script_name" required>
          <?php foreach ($scripts as $script): ?>
            <option value="<?= $e($script) ?>"><?= $e($script) ?></option>
          <?php endforeach; ?>
        </select>
      </label>

      <label class="form-field mt-8">
        <span class="field-label"><?= $e($t('settings.project_mapping.fields.output_dir')) ?></span>
        <input class="form-control" type="text" name="output_dir">
      </label>

      <label class="form-field mt-8">
        <span class="checkbox-row">
          <input type="checkbox" name="requires_photo" value="1">
          <?= $e($t('settings.project_mapping.fields.requires_photo')) ?>
        </span>
      </label>

      <div class="mt-12">
        <button type="submit" class="btn btn--action"><?= $e($t('settings.project_mapping.actions.save')) ?></button>
        <button type="button" class="btn btn--outline js-pm-modal-close"><?= $e($t('settings.project_mapping.actions.cancel')) ?></button>
      </div>
    </form>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  var modal = document.getElementById('pm-edit-modal');
  var form = document.getElementById('pm-edit-form');

  document.querySelectorAll('.js-pm-edit').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var id = this.dataset.id;
      form.action = '/settings/project-mappings/' + id + '/update';
      form.querySelector('[name="product_name_pattern"]').value = this.dataset.pattern;
      form.querySelector('[name="script_name"]').value = this.dataset.script;
      form.querySelector('[name="output_dir"]').value = this.dataset.outputDir || '';
      form.querySelector('[name="requires_photo"]').checked = this.dataset.requiresPhoto === '1';
      modal.style.display = 'flex';
    });
  });

  document.querySelectorAll('.js-pm-modal-close').forEach(function(el) {
    el.addEventListener('click', function() {
      modal.style.display = 'none';
    });
  });

  function submitDelete(id, token) {
    var f = document.createElement('form');
    f.method = 'post';
    f.action = '/settings/project-mappings/' + id + '/delete';
    var t = document.createElement('input');
    t.type = 'hidden'; t.name = '_token'; t.value = token;
    f.appendChild(t);
    document.body.appendChild(f);
    f.submit();
  }

  document.querySelectorAll('.js-pm-delete').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var id = this.dataset.id;
      var token = this.dataset.token;
      if (!window.OrderProAlerts || typeof window.OrderProAlerts.confirm !== 'function') {
        return;
      }
      window.OrderProAlerts.confirm({
        title: '<?= $e($t('settings.project_mapping.actions.delete')) ?>',
        message: '<?= $e($t('settings.project_mapping.confirm_delete')) ?>',
        danger: true
      }).then(function(confirmed) {
        if (confirmed) submitDelete(id, token);
      });
    });
  });
});
</script>
