<?php
$rule = is_array($rule ?? null) ? $rule : null;
$isEdit = $rule !== null && isset($rule['id']);
$integrations = is_array($integrations ?? null) ? $integrations : [];
$emailTemplates = is_array($emailTemplates ?? null) ? $emailTemplates : [];
$conditions = $rule !== null && is_array($rule['conditions'] ?? null) ? $rule['conditions'] : [];
$actions = $rule !== null && is_array($rule['actions'] ?? null) ? $rule['actions'] : [];

$eventLabels = [
    'receipt.created' => 'Utworzono paragon',
    'shipment.created' => 'Utworzenie przesylki',
    'shipment.status_changed' => 'Zmiana statusu przesylki',
    'payment.status_changed' => 'Zmiana statusu platnosci',
    'order.status_changed' => 'Zmiana statusu zamowienia',
    'order.status_aged' => 'Minelo X dni od zmiany statusu',
];

$recipientLabels = [
    'client' => 'Klient',
    'client_and_company' => 'Klient + e-mail z danych firmy',
    'company' => 'E-mail z danych firmy',
];
$receiptConfigs = is_array($receiptConfigs ?? null) ? $receiptConfigs : [];
$receiptIssueDateModes = is_array($receiptIssueDateModes ?? null) ? $receiptIssueDateModes : [];
$receiptDuplicatePolicies = is_array($receiptDuplicatePolicies ?? null) ? $receiptDuplicatePolicies : [];
$receiptIssueDateModeLabels = [
    'today' => 'Data dzisiejsza',
    'order_date' => 'Data zamowienia',
    'payment_date' => 'Data platnosci (fallback: dzisiaj)',
];
$receiptDuplicatePolicyLabels = [
    'skip_if_exists' => 'Pomin jesli paragon juz istnieje',
    'allow_duplicates' => 'Wystawiaj kolejne paragony',
];
$shipmentStatusOptions = is_array($shipmentStatusOptions ?? null) ? $shipmentStatusOptions : [];
$orderStatusOptions = is_array($orderStatusOptions ?? null) ? $orderStatusOptions : [];
?>

<section class="card">
  <h2 class="section-title"><?= $isEdit ? 'Edytuj zadanie automatyczne' : 'Nowe zadanie automatyczne' ?></h2>

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

  <form action="<?= $isEdit ? '/settings/automation/update' : '/settings/automation/store' ?>" method="post" novalidate class="mt-12" id="js-automation-form">
    <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
    <?php if ($isEdit): ?>
      <input type="hidden" name="id" value="<?= (int) ($rule['id'] ?? 0) ?>">
    <?php endif; ?>

    <div class="form-grid-2">
      <label class="form-field">
        <span class="field-label">Nazwa zadania *</span>
        <input class="form-control" type="text" name="name" maxlength="128" required value="<?= $e((string) ($rule['name'] ?? '')) ?>" placeholder="np. Paragon Allegro - wyslij e-mail">
      </label>
      <label class="form-field">
        <span class="field-label">Zdarzenie *</span>
        <select class="form-control" name="event_type">
          <?php foreach ($eventLabels as $key => $label): ?>
            <option value="<?= $e($key) ?>"<?= ((string) ($rule['event_type'] ?? 'receipt.created')) === $key ? ' selected' : '' ?>><?= $e($label) ?></option>
          <?php endforeach; ?>
        </select>
      </label>
    </div>

    <div class="form-grid-2 mt-0">
      <label class="form-field" style="display:flex;align-items:center;gap:6px;flex-direction:row">
        <input type="checkbox" name="is_active" value="1"<?= $rule !== null ? (((int) ($rule['is_active'] ?? 0)) === 1 ? ' checked' : '') : ' checked' ?>>
        <span class="field-label" style="margin:0">Aktywne</span>
      </label>
    </div>

    <h3 class="section-title mt-16">Warunki</h3>
    <p class="muted">Wszystkie warunki musza byc spelnione (AND).</p>

    <div id="js-conditions-container">
      <?php if (count($conditions) > 0): ?>
        <?php foreach ($conditions as $idx => $cond): ?>
          <div class="automation-row mt-8" data-index="<?= $idx ?>">
            <div class="automation-row__fields">
              <select class="form-control automation-row__type" name="conditions[<?= $idx ?>][type]" onchange="window.AutomationForm.onConditionTypeChange(this)">
                <option value="integration"<?= ((string) ($cond['condition_type'] ?? '')) === 'integration' ? ' selected' : '' ?>>Integracja (kanal sprzedazy)</option>
                <option value="shipment_status"<?= ((string) ($cond['condition_type'] ?? '')) === 'shipment_status' ? ' selected' : '' ?>>Status przesylki</option>
                <option value="payment_status"<?= ((string) ($cond['condition_type'] ?? '')) === 'payment_status' ? ' selected' : '' ?>>Status platnosci</option>
                <option value="order_status"<?= ((string) ($cond['condition_type'] ?? '')) === 'order_status' ? ' selected' : '' ?>>Status zamowienia</option>
                <option value="days_in_status"<?= ((string) ($cond['condition_type'] ?? '')) === 'days_in_status' ? ' selected' : '' ?>>Liczba dni w statusie</option>
              </select>
              <div class="automation-row__config">
                <?php
                  $condValue = is_array($cond['condition_value'] ?? null) ? $cond['condition_value'] : [];
                  $conditionType = (string) ($cond['condition_type'] ?? 'integration');
                  $selectedIds = is_array($condValue['integration_ids'] ?? null) ? $condValue['integration_ids'] : [];
                  $selectedStatusKeys = is_array($condValue['status_keys'] ?? null) ? $condValue['status_keys'] : [];
                  $selectedOrderStatusCodes = is_array($condValue['order_status_codes'] ?? null) ? $condValue['order_status_codes'] : [];
                ?>
                <?php if ($conditionType === 'shipment_status'): ?>
                  <div class="checkbox-group">
                    <?php foreach ($shipmentStatusOptions as $statusKey => $statusConfig): ?>
                      <?php $statusLabel = (string) ($statusConfig['label'] ?? $statusKey); ?>
                      <label class="checkbox-label">
                        <input type="checkbox" name="conditions[<?= $idx ?>][shipment_status_keys][]" value="<?= $e((string) $statusKey) ?>"<?= in_array((string) $statusKey, $selectedStatusKeys, true) ? ' checked' : '' ?>>
                        <?= $e($statusLabel) ?>
                      </label>
                    <?php endforeach; ?>
                  </div>
                <?php elseif ($conditionType === 'payment_status'): ?>
                  <div class="checkbox-group">
                    <?php foreach ($paymentStatusOptions as $statusKey => $statusLabel): ?>
                      <label class="checkbox-label">
                        <input type="checkbox" name="conditions[<?= $idx ?>][payment_status_keys][]" value="<?= $e((string) $statusKey) ?>"<?= in_array((string) $statusKey, $selectedStatusKeys, true) ? ' checked' : '' ?>>
                        <?= $e($statusLabel) ?>
                      </label>
                    <?php endforeach; ?>
                  </div>
                <?php elseif ($conditionType === 'order_status'): ?>
                  <div class="checkbox-group">
                    <?php foreach ($orderStatusOptions as $statusOption): ?>
                      <?php $statusCode = strtolower(trim((string) ($statusOption['code'] ?? ''))); ?>
                      <label class="checkbox-label">
                        <input type="checkbox" name="conditions[<?= $idx ?>][order_status_codes][]" value="<?= $e($statusCode) ?>"<?= in_array($statusCode, $selectedOrderStatusCodes, true) ? ' checked' : '' ?>>
                        <?= $e((string) ($statusOption['name'] ?? $statusCode)) ?>
                      </label>
                    <?php endforeach; ?>
                  </div>
                <?php elseif ($conditionType === 'days_in_status'): ?>
                  <input type="number" min="1" step="1" class="form-control" name="conditions[<?= $idx ?>][days]" value="<?= (int) ($condValue['days'] ?? '') > 0 ? (int) $condValue['days'] : '' ?>" placeholder="Liczba dni">
                <?php else: ?>
                  <div class="checkbox-group">
                    <?php foreach ($integrations as $integ): ?>
                      <label class="checkbox-label">
                        <input type="checkbox" name="conditions[<?= $idx ?>][integration_ids][]" value="<?= (int) $integ['id'] ?>"<?= in_array((int) $integ['id'], $selectedIds, true) ? ' checked' : '' ?>>
                        <?= $e((string) ($integ['name'] ?? '')) ?> <span class="muted">(<?= $e((string) ($integ['type'] ?? '')) ?>)</span>
                      </label>
                    <?php endforeach; ?>
                  </div>
                <?php endif; ?>
              </div>
            </div>
            <button type="button" class="btn btn--sm btn--danger automation-row__remove" onclick="window.AutomationForm.removeRow(this)">&times;</button>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
    <button type="button" class="btn btn--sm btn--secondary mt-8" id="js-add-condition">+ Dodaj warunek</button>

    <h3 class="section-title mt-16">Akcje</h3>
    <p class="muted">Wszystkie akcje zostana wykonane po kolei.</p>

    <div id="js-actions-container">
      <?php if (count($actions) > 0): ?>
        <?php foreach ($actions as $idx => $act): ?>
          <div class="automation-row mt-8" data-index="<?= $idx ?>">
            <div class="automation-row__fields">
              <select class="form-control automation-row__type" name="actions[<?= $idx ?>][type]" onchange="window.AutomationForm.onActionTypeChange(this)">
                <option value="send_email"<?= ((string) ($act['action_type'] ?? '')) === 'send_email' ? ' selected' : '' ?>>Wyslij e-mail</option>
                <option value="issue_receipt"<?= ((string) ($act['action_type'] ?? '')) === 'issue_receipt' ? ' selected' : '' ?>>Wystaw paragon</option>
                <option value="update_shipment_status"<?= ((string) ($act['action_type'] ?? '')) === 'update_shipment_status' ? ' selected' : '' ?>>Zmiana statusu przesylki</option>
                <option value="update_order_status"<?= ((string) ($act['action_type'] ?? '')) === 'update_order_status' ? ' selected' : '' ?>>Zmiana statusu zamowienia</option>
              </select>
              <div class="automation-row__config">
                <?php
                $actConfig = is_array($act['action_config'] ?? null) ? $act['action_config'] : [];
                $actionType = (string) ($act['action_type'] ?? 'send_email');
                ?>
                <?php if ($actionType === 'issue_receipt'): ?>
                  <select class="form-control" name="actions[<?= $idx ?>][receipt_config_id]">
                    <option value="">-- Wybierz konfiguracje paragonu --</option>
                    <?php foreach ($receiptConfigs as $cfg): ?>
                      <option value="<?= (int) ($cfg['id'] ?? 0) ?>"<?= ((int) ($actConfig['receipt_config_id'] ?? 0)) === (int) ($cfg['id'] ?? 0) ? ' selected' : '' ?>>
                        <?= $e((string) ($cfg['name'] ?? '')) ?> (<?= $e((string) ($cfg['number_format'] ?? '')) ?>)
                      </option>
                    <?php endforeach; ?>
                  </select>
                  <select class="form-control" name="actions[<?= $idx ?>][issue_date_mode]">
                    <?php foreach ($receiptIssueDateModes as $mode): ?>
                      <?php $modeKey = (string) $mode; ?>
                      <option value="<?= $e($modeKey) ?>"<?= ((string) ($actConfig['issue_date_mode'] ?? 'today')) === $modeKey ? ' selected' : '' ?>>
                        <?= $e((string) ($receiptIssueDateModeLabels[$modeKey] ?? $modeKey)) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                  <select class="form-control" name="actions[<?= $idx ?>][duplicate_policy]">
                    <?php foreach ($receiptDuplicatePolicies as $policy): ?>
                      <?php $policyKey = (string) $policy; ?>
                      <option value="<?= $e($policyKey) ?>"<?= ((string) ($actConfig['duplicate_policy'] ?? 'skip_if_exists')) === $policyKey ? ' selected' : '' ?>>
                        <?= $e((string) ($receiptDuplicatePolicyLabels[$policyKey] ?? $policyKey)) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                <?php elseif ($actionType === 'update_shipment_status'): ?>
                  <select class="form-control" name="actions[<?= $idx ?>][shipment_status_key]">
                    <option value="">-- Wybierz docelowy status przesylki --</option>
                    <?php foreach ($shipmentStatusOptions as $statusKey => $statusConfig): ?>
                      <?php $statusLabel = (string) ($statusConfig['label'] ?? $statusKey); ?>
                      <option value="<?= $e((string) $statusKey) ?>"<?= ((string) ($actConfig['status_key'] ?? '')) === (string) $statusKey ? ' selected' : '' ?>>
                        <?= $e($statusLabel) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                <?php elseif ($actionType === 'update_order_status'): ?>
                  <select class="form-control" name="actions[<?= $idx ?>][order_status_code]">
                    <option value="">-- Wybierz docelowy status zamowienia --</option>
                    <?php foreach ($orderStatusOptions as $statusOption): ?>
                      <?php
                        $statusCode = (string) ($statusOption['code'] ?? '');
                        $statusName = (string) ($statusOption['name'] ?? $statusCode);
                      ?>
                      <option value="<?= $e($statusCode) ?>"<?= ((string) ($actConfig['status_code'] ?? '')) === $statusCode ? ' selected' : '' ?>>
                        <?= $e($statusName) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                <?php else: ?>
                  <select class="form-control" name="actions[<?= $idx ?>][template_id]">
                    <option value="">-- Wybierz szablon --</option>
                    <?php foreach ($emailTemplates as $tpl): ?>
                      <option value="<?= (int) $tpl['id'] ?>"<?= ((int) ($actConfig['template_id'] ?? 0)) === (int) $tpl['id'] ? ' selected' : '' ?>><?= $e((string) ($tpl['name'] ?? '')) ?></option>
                    <?php endforeach; ?>
                  </select>
                  <select class="form-control" name="actions[<?= $idx ?>][recipient]">
                    <?php foreach ($recipientLabels as $key => $label): ?>
                      <option value="<?= $e($key) ?>"<?= ((string) ($actConfig['recipient'] ?? '')) === $key ? ' selected' : '' ?>><?= $e($label) ?></option>
                    <?php endforeach; ?>
                  </select>
                <?php endif; ?>
              </div>
            </div>
            <button type="button" class="btn btn--sm btn--danger automation-row__remove" onclick="window.AutomationForm.removeRow(this)">&times;</button>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
    <button type="button" class="btn btn--sm btn--secondary mt-8" id="js-add-action">+ Dodaj akcje</button>

    <div class="form-actions mt-16">
      <button type="submit" class="btn btn--primary"><?= $isEdit ? 'Zapisz zmiany' : 'Utworz zadanie' ?></button>
      <a href="/settings/automation" class="btn btn--secondary">Anuluj</a>
    </div>
  </form>
</section>

<script>
window.AutomationFormData = {
  integrations: <?= json_encode(array_map(function($i) {
    return ['id' => (int) $i['id'], 'name' => (string) ($i['name'] ?? ''), 'type' => (string) ($i['type'] ?? '')];
  }, $integrations), JSON_UNESCAPED_UNICODE) ?>,
  emailTemplates: <?= json_encode(array_map(function($t) {
    return ['id' => (int) $t['id'], 'name' => (string) ($t['name'] ?? '')];
  }, $emailTemplates), JSON_UNESCAPED_UNICODE) ?>,
  receiptConfigs: <?= json_encode(array_map(function($cfg) {
    return [
      'id' => (int) ($cfg['id'] ?? 0),
      'name' => (string) ($cfg['name'] ?? ''),
      'number_format' => (string) ($cfg['number_format'] ?? '')
    ];
  }, $receiptConfigs), JSON_UNESCAPED_UNICODE) ?>,
  recipientLabels: <?= json_encode($recipientLabels, JSON_UNESCAPED_UNICODE) ?>,
  receiptIssueDateModes: <?= json_encode($receiptIssueDateModes, JSON_UNESCAPED_UNICODE) ?>,
  receiptIssueDateModeLabels: <?= json_encode($receiptIssueDateModeLabels, JSON_UNESCAPED_UNICODE) ?>,
  receiptDuplicatePolicies: <?= json_encode($receiptDuplicatePolicies, JSON_UNESCAPED_UNICODE) ?>,
  receiptDuplicatePolicyLabels: <?= json_encode($receiptDuplicatePolicyLabels, JSON_UNESCAPED_UNICODE) ?>,
  shipmentStatusOptions: <?= json_encode($shipmentStatusOptions, JSON_UNESCAPED_UNICODE) ?>,
  paymentStatusOptions: <?= json_encode($paymentStatusOptions, JSON_UNESCAPED_UNICODE) ?>,
  orderStatusOptions: <?= json_encode(array_map(function($status) {
    return [
      'code' => (string) ($status['code'] ?? ''),
      'name' => (string) ($status['name'] ?? '')
    ];
  }, $orderStatusOptions), JSON_UNESCAPED_UNICODE) ?>
};
</script>
<script src="/assets/js/modules/automation-form.js"></script>
