<?php
$step = $step ?? 1;
$closeTarget = $closeTarget ?? 'helpdesk/handovers';
$createTarget = $createTarget ?? 'helpdesk/handovers/create';
$form = is_array($form ?? null) ? $form : [];
$errors = is_array($errors ?? null) ? $errors : [];
$validationSummaryErrors = is_array($validationSummaryErrors ?? null) ? $validationSummaryErrors : [];
$productsWithSchema = is_array($productsWithSchema ?? null) ? $productsWithSchema : [];
$schemaFields = is_array($schemaFields ?? null) ? $schemaFields : [];
$fieldValues = is_array($fieldValues ?? null) ? $fieldValues : [];
$wizardData = is_array($wizardData ?? null) ? $wizardData : [];
$productDisplayName = $productDisplayName ?? '';
$canManage = $canManage ?? false;
$mode = $mode ?? '';
$tenantUsers = is_array($tenantUsers ?? null) ? $tenantUsers : [];
$formStep = $canManage ? 2 : 1;
$protocolStep = $canManage ? 3 : 2;

// Build step indicator
if ($canManage) {
    $steps = [
        ['label' => t('Type'), 'number' => 1],
        ['label' => t('Customer & product'), 'number' => 2],
        ['label' => t('Protocol'), 'number' => 3],
    ];
    // For assign mode, step 3 is skipped — show only 2 steps
    if ($mode === 'assign') {
        $steps = [
            ['label' => t('Type'), 'number' => 1],
            ['label' => t('Customer & product'), 'number' => 2],
        ];
    }
} else {
    $steps = [
        ['label' => t('Customer & product'), 'number' => 1],
        ['label' => t('Protocol'), 'number' => 2],
    ];
}

// Map actual step number to display step number for indicator
$displayStep = $step;
if ($canManage && $mode === 'assign' && $step === 2) {
    $displayStep = 2;
}
?>
<div class="app-wizard-content">
  <div class="app-wizard-header">
    <a href="<?php e(lurl($closeTarget)); ?>" class="app-wizard-back" data-tooltip="<?php e(t('Back to list')); ?>">
      <i class="bi bi-arrow-left"></i>
    </a>
    <h1 class="app-wizard-title"><?php e(t('New handover')); ?></h1>
  </div>

  <!-- Step indicator -->
  <nav class="app-wizard-steps" aria-label="<?php e(t('Progress')); ?>">
    <?php foreach ($steps as $s): ?>
      <div class="app-wizard-step<?php if ($s['number'] === $displayStep): ?> is-active<?php elseif ($s['number'] < $displayStep): ?> is-completed<?php endif; ?>"
           <?php if ($s['number'] === $displayStep): ?>aria-current="step"<?php endif; ?>>
        <span class="app-wizard-step-number"><?php e($s['number']); ?></span>
        <span class="app-wizard-step-label"><?php e($s['label']); ?></span>
      </div>
      <?php if ($s['number'] < count($steps)): ?>
        <div class="app-wizard-step-connector<?php if ($s['number'] < $displayStep): ?> is-completed<?php endif; ?>" aria-hidden="true"></div>
      <?php endif; ?>
    <?php endforeach; ?>
  </nav>

  <?php if ($validationSummaryErrors): ?>
    <?php require templatePath('partials/app-details-validation-summary.phtml'); ?>
  <?php endif; ?>

  <!-- Manager step 1: choose mode -->
  <?php if ($canManage && $step === 1): ?>
    <div class="app-wizard-card">
      <form method="post" id="wizard-mode-select">
        <h2 class="app-wizard-card-heading"><?php e(t('How do you want to proceed?')); ?></h2>

        <div class="app-wizard-field-group">
          <label style="display:flex;align-items:flex-start;gap:10px;cursor:pointer;padding:12px 14px;border:1px solid var(--border-color,#ddd);border-radius:6px;margin-bottom:8px;">
            <input type="radio" name="mode" value="self" style="margin-top:3px;">
            <span>
              <strong><?php e(t('Create myself')); ?></strong><br>
              <small style="color:var(--text-muted,#888)"><?php e(t('I will fill in the handover protocol myself.')); ?></small>
            </span>
          </label>
          <label style="display:flex;align-items:flex-start;gap:10px;cursor:pointer;padding:12px 14px;border:1px solid var(--border-color,#ddd);border-radius:6px;">
            <input type="radio" name="mode" value="assign" style="margin-top:3px;">
            <span>
              <strong><?php e(t('Assign to employee')); ?></strong><br>
              <small style="color:var(--text-muted,#888)"><?php e(t('An employee will receive an invitation to fill in the protocol.')); ?></small>
            </span>
          </label>
          <?php if (!empty($errors['mode'])): ?>
            <p class="field-error"><?php e($errors['mode']); ?></p>
          <?php endif; ?>
        </div>

        <?php \MintyPHP\Session::getCsrfInput(); ?>

        <div class="app-wizard-actions">
          <a href="<?php e(lurl($closeTarget)); ?>" role="button" class="outline secondary"><?php e(t('Cancel')); ?></a>
          <button type="submit" class="primary"><?php e(t('Continue')); ?></button>
        </div>
      </form>
    </div>

  <!-- Form step: select customer + product (+ assignee for assign mode) -->
  <?php elseif ($step === $formStep): ?>
    <div class="app-wizard-card">
      <form method="post" id="wizard-step-form">
        <?php if ($mode === 'assign'): ?>
          <h2 class="app-wizard-card-heading"><?php e(t('Select customer, product and employee')); ?></h2>
        <?php else: ?>
          <h2 class="app-wizard-card-heading"><?php e(t('Select customer and product')); ?></h2>
          <p class="app-wizard-card-description"><?php e(t('Choose the customer and software product for this handover protocol.')); ?></p>
        <?php endif; ?>

        <div class="app-wizard-field-group">
          <label><?php e(t('Customer')); ?> <span class="handover-form-required">*</span></label>
          <div
            data-app-lookup
            data-lookup-url="<?php e(lurl('helpdesk/debitor-lookup-data')); ?>"
            data-lookup-min-chars="2"
            data-lookup-debounce="300"
            data-lookup-value-key="value"
            data-lookup-display-key="label"
            data-lookup-placeholder="<?php e(t('Search by name or number...')); ?>"
            data-lookup-empty-text="<?php e(t('No customers found')); ?>"
            data-lookup-error-text="<?php e(t('Search failed')); ?>"
            data-lookup-initial-value="<?php e($form['debitor_no'] ?? ''); ?>"
            data-lookup-initial-display="<?php e($form['debitor_name'] ?? ''); ?>"
          >
            <input type="hidden" name="debitor_no" data-lookup-value value="<?php e($form['debitor_no'] ?? ''); ?>">
            <input type="hidden" name="debitor_name" data-lookup-display-value value="<?php e($form['debitor_name'] ?? ''); ?>">
          </div>
          <?php if (!empty($errors['debitor_no'])): ?>
            <p class="field-error"><?php e($errors['debitor_no']); ?></p>
          <?php endif; ?>
        </div>

        <div class="app-wizard-field-group" id="wizard-domain-group" data-app-component="helpdesk-handover-domain-select"
             data-domains-url="<?php e(lurl('helpdesk/handover-domains-data')); ?>"
             data-text-initial="<?php e(t('Select a customer first...')); ?>"
             data-text-loading="<?php e(t('Loading domains...')); ?>"
             data-text-select="<?php e(t('Please select...')); ?>"
             data-text-empty="<?php e(t('No domains found for this customer')); ?>"
             data-text-error="<?php e(t('Failed to load domains')); ?>"
             data-initial-debitor="<?php e($form['debitor_no'] ?? ''); ?>"
             data-initial-domain="<?php e($form['domain_no'] ?? ''); ?>"
        >
          <label for="wizard-domain"><?php e(t('Domain')); ?> <span class="handover-form-required">*</span></label>
          <select id="wizard-domain" name="domain_no" disabled>
            <option value=""><?php e(t('Select a customer first...')); ?></option>
          </select>
          <input type="hidden" name="domain_url" id="wizard-domain-url" value="<?php e($form['domain_url'] ?? ''); ?>">
          <div id="wizard-domain-feedback" class="app-wizard-field-feedback" role="alert" hidden></div>
          <?php if (!empty($errors['domain_no'])): ?>
            <p class="field-error"><?php e($errors['domain_no']); ?></p>
          <?php endif; ?>
        </div>

        <div class="app-wizard-field-group">
          <label for="wizard-product-code"><?php e(t('Software product')); ?> <span class="handover-form-required">*</span></label>
          <?php if ($productsWithSchema === []): ?>
            <div class="notice" data-variant="info" role="alert">
              <p><?php e(t('No software products with handover protocol schemas found.')); ?></p>
            </div>
          <?php else: ?>
            <select id="wizard-product-code" name="product_code">
              <option value=""><?php e(t('Please select...')); ?></option>
              <?php foreach ($productsWithSchema as $p):
                  $code = (string) ($p['code'] ?? '');
                  $name = trim((string) ($p['name'] ?? ''));
                  $desc = (string) ($p['bc_description'] ?? '');
                  $displayLabel = $name !== '' ? $name : ($desc !== '' ? $desc : $code);
              ?>
                <option value="<?php e($code); ?>"<?php if (($form['product_code'] ?? '') === $code): ?> selected<?php endif; ?>>
                  <?php e($displayLabel); ?>
                </option>
              <?php endforeach; ?>
            </select>
            <?php if (!empty($errors['product_code'])): ?>
              <p class="field-error"><?php e($errors['product_code']); ?></p>
            <?php endif; ?>
          <?php endif; ?>
        </div>

        <?php if ($mode === 'assign'): ?>
        <div class="app-wizard-field-group">
          <label for="wizard-assigned-to"><?php e(t('Assign to')); ?> <span class="handover-form-required">*</span></label>
          <?php if ($tenantUsers === []): ?>
            <p class="field-error"><?php e(t('No active employees found.')); ?></p>
          <?php else: ?>
            <select id="wizard-assigned-to" name="assigned_to">
              <option value="0"><?php e(t('— Select employee —')); ?></option>
              <?php foreach ($tenantUsers as $u):
                  $uId = (int) ($u['u']['id'] ?? $u['id'] ?? 0);
                  $uName = (string) ($u['u']['display_name'] ?? $u['display_name'] ?? '');
                  $uEmail = (string) ($u['u']['email'] ?? $u['email'] ?? '');
              ?>
                <option value="<?php e($uId); ?>"<?php if ((int) ($form['assigned_to'] ?? 0) === $uId): ?> selected<?php endif; ?>>
                  <?php e($uName ?: $uEmail); ?>
                </option>
              <?php endforeach; ?>
            </select>
            <?php if (!empty($errors['assigned_to'])): ?>
              <p class="field-error"><?php e($errors['assigned_to']); ?></p>
            <?php endif; ?>
          <?php endif; ?>
        </div>

        <div class="app-wizard-field-group">
          <label for="wizard-due-date"><?php e(t('Due date (optional)')); ?></label>
          <input type="date" id="wizard-due-date" name="due_date" value="<?php e($form['due_date'] ?? ''); ?>">
        </div>
        <?php endif; ?>

        <?php \MintyPHP\Session::getCsrfInput(); ?>

        <div class="app-wizard-actions">
          <?php if ($canManage): ?>
            <a href="<?php e(lurl($createTarget)); ?>" role="button" class="outline secondary"><?php e(t('Back')); ?></a>
          <?php else: ?>
            <a href="<?php e(lurl($closeTarget)); ?>" role="button" class="outline secondary"><?php e(t('Cancel')); ?></a>
          <?php endif; ?>
          <?php if ($mode === 'assign'): ?>
            <button type="submit" class="primary"><?php e(t('Create and assign')); ?></button>
          <?php else: ?>
            <button type="submit" class="primary"><?php e(t('Continue')); ?></button>
          <?php endif; ?>
        </div>
      </form>
    </div>

  <!-- Protocol step: fill protocol -->
  <?php elseif ($step === $protocolStep): ?>
    <div class="app-wizard-card">
      <?php
      $backUrl = lurl($createTarget) . '?step=' . $formStep . ($canManage ? '&mode=' . urlencode($mode) : '');
      ?>
      <form method="post" id="wizard-step-protocol">
        <h2 class="app-wizard-card-heading"><?php e(t('Fill handover protocol')); ?></h2>
        <p class="app-wizard-card-description">
          <?php e($wizardData['debitor_name'] ?? ''); ?> &mdash; <?php e($productDisplayName); ?>
        </p>

        <?php
        $readonly = false;
        require __DIR__ . '/_form.phtml';
        ?>

        <?php \MintyPHP\Session::getCsrfInput(); ?>

        <div class="app-wizard-actions">
          <a href="<?php e($backUrl); ?>" role="button" class="outline secondary"><?php e(t('Back')); ?></a>
          <button type="submit" class="primary"><?php e(t('Create handover')); ?></button>
        </div>
      </form>
    </div>
  <?php endif; ?>
</div>
