<?php

use MintyPHP\Module\Helpdesk\Service\HandoverRevisionService;
use MintyPHP\Module\Helpdesk\Service\HandoverService;

$handover = is_array($handover ?? null) ? $handover : [];
$schemaFields = is_array($schemaFields ?? null) ? $schemaFields : [];
$fieldValues = is_array($fieldValues ?? null) ? $fieldValues : [];
$validationSummaryErrors = is_array($validationSummaryErrors ?? null) ? $validationSummaryErrors : [];
$errors = is_array($errors ?? null) ? $errors : [];
$closeTarget = $closeTarget ?? 'helpdesk/handovers';
$canEdit = $canEdit ?? false;
$allowedStatuses = is_array($allowedStatuses ?? null) ? $allowedStatuses : [];
$currentStatus = $currentStatus ?? 'draft';
$revisions = is_array($revisions ?? null) ? $revisions : [];
$isViewingRevision = !empty($isViewingRevision);
$activeRevisionNumber = $activeRevisionNumber ?? 0;
$compareRevisionNumber = $compareRevisionNumber ?? 0;
$fieldDiff = is_array($fieldDiff ?? null) ? $fieldDiff : [];
$canManage = $canManage ?? false;
$canSubmitForReview = $canSubmitForReview ?? false;
$assignUrl = $assignUrl ?? '';

$formId = 'handover-form';
$readonly = !$canEdit || $isViewingRevision;
$editTarget = $editTarget ?? ('helpdesk/handovers/edit/' . ($handover['id'] ?? 0));
$editBasePath = $editBasePath ?? ('helpdesk/handovers/edit/' . ($handover['id'] ?? 0));
?>
<div class="app-details-container">
  <section>
    <?php
    $titlebar = [
        'title' => $titleText ?? t('Handover'),
        'backHref' => $closeTarget,
        'backTitle' => t('Back to list'),
        'actions' => ($canEdit && !$isViewingRevision) ? [
            [
                'form' => $formId,
                'name' => 'action',
                'value' => 'save',
                'class' => 'secondary outline',
                'label' => t('Save'),
            ],
            [
                'form' => $formId,
                'name' => 'action',
                'value' => 'save_close',
                'class' => 'primary',
                'label' => t('Save & close'),
            ],
        ] : [],
    ];
    require templatePath('partials/app-details-titlebar.phtml');
    ?>

    <?php if ($isViewingRevision): ?>
      <div class="handover-revision-banner">
        <p>
          <i class="bi bi-clock-history"></i>
          <?php e(t('Viewing version %d', $activeRevisionNumber)); ?>
          <?php if ($compareRevisionNumber > 0): ?>
            — <?php e(t('compared with version %d', $compareRevisionNumber)); ?>
          <?php endif; ?>
        </p>
        <a href="<?php e(lurl($editBasePath)); ?>" role="button" class="outline secondary small"><?php e(t('Back to current')); ?></a>
      </div>
    <?php endif; ?>

    <?php require templatePath('partials/app-details-validation-summary.phtml'); ?>

    <?php if ($canEdit && !$isViewingRevision): ?>
      <form id="<?php e($formId); ?>" method="post" data-standard-detail-form="1">
        <div class="app-tabs" data-tabs data-app-component="tabs" data-tabs-param="tab" data-tabs-storage-key="helpdesk-handover-form">
          <div class="app-tabs-nav">
            <button type="button" data-tab="protocol" data-tab-default><?php e(t('Handover protocol')); ?></button>
          </div>

          <div data-tab-panel="protocol">
            <?php require __DIR__ . '/_form.phtml'; ?>
          </div>
        </div>

        <?php \MintyPHP\Session::getCsrfInput(); ?>
      </form>
    <?php else: ?>
      <div class="app-tabs" data-tabs data-app-component="tabs" data-tabs-param="tab" data-tabs-storage-key="helpdesk-handover-form">
        <div class="app-tabs-nav">
          <button type="button" data-tab="protocol" data-tab-default><?php e(t('Handover protocol')); ?></button>
        </div>

        <div data-tab-panel="protocol">
          <?php require __DIR__ . '/_form.phtml'; ?>
        </div>
      </div>
    <?php endif; ?>
  </section>

  <aside id="app-details-aside-section">
    <div class="app-details-aside-section">
      <?php
      $debitorNo = trim((string) ($handover['debitor_no'] ?? ''));
      $debitorName = trim((string) ($handover['debitor_name'] ?? ''));
      $domainNo = trim((string) ($handover['domain_no'] ?? ''));
      $domainUrl = trim((string) ($handover['domain_url'] ?? ''));
      $canViewSoftwareProducts = $canViewSoftwareProducts ?? false;
      $productCode = $handover['product_code'] ?? '';
      ?>
      <hgroup>
        <h2>
          <?php if ($debitorNo !== ''): ?>
            <a href="<?php e(lurl('helpdesk/debitor/' . rawurlencode($debitorNo))); ?>"><?php e($debitorName !== '' ? $debitorName : $debitorNo); ?></a>
          <?php else: ?>
            <?php e($debitorName !== '' ? $debitorName : '—'); ?>
          <?php endif; ?>
        </h2>
        <p>
          <?php if ($domainNo !== ''): ?>
            <a href="<?php e(lurl('helpdesk/domain/' . rawurlencode($domainNo))); ?>"><?php e($domainUrl !== '' ? $domainUrl : $domainNo); ?></a>
          <?php elseif ($domainUrl !== ''): ?>
            <?php e($domainUrl); ?>
          <?php else: ?>
            —
          <?php endif; ?>
        </p>
        <p>
          <?php if ($canViewSoftwareProducts && $productCode !== ''): ?>
            <a href="<?php e(lurl('helpdesk/software-products/edit/' . rawurlencode($productCode))); ?>"><?php e($productName ?? $productCode); ?></a>
          <?php else: ?>
            <?php e($productName ?? $productCode); ?>
          <?php endif; ?>
        </p>
      </hgroup>

      <?php if (!$isViewingRevision && $canEdit && $allowedStatuses && count($allowedStatuses) > 1): ?>
        <label for="handover-status"><small><?php e(t('Status')); ?></small></label>
        <select id="handover-status" name="status" form="<?php e($formId); ?>">
          <?php foreach ($allowedStatuses as $status): ?>
            <option value="<?php e($status); ?>"<?php if ($status === $currentStatus): ?> selected<?php endif; ?>>
              <?php e(HandoverService::statusLabel($status)); ?>
            </option>
          <?php endforeach; ?>
        </select>
      <?php else: ?>
        <div class="badge-list">
          <span class="badge" data-variant="<?php e(HandoverService::statusVariant($currentStatus)); ?>">
            <?php e(HandoverService::statusLabel($currentStatus)); ?>
          </span>
        </div>
      <?php endif; ?>

      <?php
      $assignedToLabel = trim((string) ($handover['assigned_to_label'] ?? ''));
      $assignedAt = trim((string) ($handover['assigned_at'] ?? ''));
      $dueDate = trim((string) ($handover['due_date'] ?? ''));
      $hasAssignee = !empty($handover['assigned_to']);
      ?>

      <?php if ($hasAssignee || $canManage): ?>
        <hr>
        <details name="handover-aside" open>
          <summary><small><?php e(t('Assignment')); ?></small></summary>
          <hr>
          <?php if ($hasAssignee): ?>
            <p>
              <small><?php e(t('Assigned to')); ?></small><br>
              <strong><?php e($assignedToLabel ?: ('# ' . ($handover['assigned_to'] ?? ''))); ?></strong>
            </p>
            <?php if ($assignedAt !== ''): ?>
              <p><small><?php e(t('Assigned at')); ?>: <?php e(dt($assignedAt)); ?></small></p>
            <?php endif; ?>
            <?php if ($dueDate !== ''): ?>
              <p><small><?php e(t('Due date')); ?>: <?php e($dueDate); ?></small></p>
            <?php endif; ?>
          <?php else: ?>
            <p><small><?php e(t('Not assigned yet')); ?></small></p>
          <?php endif; ?>

          <?php if ($canManage && $assignUrl !== '' && !$isViewingRevision): ?>
            <a href="<?php e($assignUrl); ?>" role="button" class="secondary outline small" style="margin-top: 6px; display: inline-block;">
              <i class="bi bi-person-check"></i>
              <?php e($hasAssignee ? t('Change assignment') : t('Assign')); ?>
            </a>
          <?php endif; ?>
        </details>
      <?php endif; ?>

      <?php if ($canSubmitForReview && !$isViewingRevision && in_array($currentStatus, [\MintyPHP\Module\Helpdesk\Service\HandoverService::STATUS_DRAFT, \MintyPHP\Module\Helpdesk\Service\HandoverService::STATUS_IN_PROGRESS], true)): ?>
        <hr>
        <form method="post">
          <input type="hidden" name="action" value="submit_for_review">
          <?php \MintyPHP\Session::getCsrfInput(); ?>
          <button
            type="submit"
            class="primary small"
            style="width: 100%;"
            data-confirm-message="<?php e(t('Submit this handover for review?')); ?>"
            data-confirm-variant="warning"
          >
            <i class="bi bi-send-check"></i> <?php e(t('Submit for review')); ?>
          </button>
        </form>
      <?php endif; ?>

      <?php if ($canManage && !$isViewingRevision): ?>
        <hr>
        <form method="post">
          <input type="hidden" name="action" value="delete">
          <?php \MintyPHP\Session::getCsrfInput(); ?>
          <button
            type="submit"
            class="danger outline small"
            style="width: 100%;"
            data-confirm-message="<?php e(t('Delete this handover?')); ?>"
            data-confirm-variant="danger"
          >
            <i class="bi bi-trash3"></i> <?php e(t('Delete handover')); ?>
          </button>
        </form>
      <?php endif; ?>

      <hr>

      <?php if ($revisions !== []): ?>
        <details name="handover-aside" open>
          <summary><?php e(t('History')); ?></summary>
          <hr>
          <?php $latestRevNum = (int) ($revisions[0]['revision'] ?? 0); ?>
          <div class="handover-revision-timeline">
            <?php foreach ($revisions as $rev):
                $revNum = (int) ($rev['revision'] ?? 0);
                $isActive = $revNum === $activeRevisionNumber;
                $isCurrent = $revNum === $latestRevNum;
                $revUrl = lurl($editBasePath . '?revision=' . $revNum);
                $compareUrl = lurl($editBasePath . '?revision=' . $latestRevNum . '&compare=' . $revNum);
            ?>
              <div class="handover-revision-item<?php if ($isActive): ?> is-active<?php endif; ?>"
                   <?php if ($isActive): ?>aria-current="true"<?php endif; ?>>
                <a href="<?php e($revUrl); ?>" class="handover-revision-link">
                  <span class="handover-revision-number">
                    <?php e('v' . $revNum); ?>
                    <?php if ($isCurrent): ?>
                      <span class="badge small" data-variant="neutral"><?php e(t('Current')); ?></span>
                    <?php endif; ?>
                  </span>
                  <span class="handover-revision-meta">
                    <span class="handover-revision-change"><?php e(HandoverRevisionService::changeTypeLabel((string) ($rev['change_type'] ?? ''))); ?></span>
                    <span><?php e($rev['changed_by_label'] ?? ('#' . ($rev['changed_by'] ?? ''))); ?> · <?php e(dt($rev['created_at'] ?? '')); ?></span>
                  </span>
                </a>
                <?php if (!$isCurrent): ?>
                  <a href="<?php e($compareUrl); ?>" class="handover-revision-compare" aria-label="<?php e(t('Compare with current')); ?>" data-tooltip="<?php e(t('Compare with current')); ?>">
                    <i class="bi bi-arrow-left-right"></i>
                  </a>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          </div>

          <?php if ($isViewingRevision && $canManage && $activeRevisionNumber < (int) ($revisions[0]['revision'] ?? 0)): ?>
            <form method="post" class="handover-revision-restore">
              <input type="hidden" name="action" value="restore">
              <input type="hidden" name="restore_revision" value="<?php e($activeRevisionNumber); ?>">
              <?php \MintyPHP\Session::getCsrfInput(); ?>
              <button
                type="submit"
                class="secondary outline small"
                data-confirm-message="<?php e(t('Restore this version?')); ?>"
                data-confirm-variant="warning"
              >
                <i class="bi bi-arrow-counterclockwise"></i> <?php e(t('Restore this version')); ?>
              </button>
            </form>
          <?php endif; ?>
        </details>
        <hr>
      <?php endif; ?>

      <?php
      $asideAuditDetailsName = 'handover-aside';
      $asideAuditOpen = false;
      $asideAuditCreated = (string) ($handover['created_at'] ?? '');
      $asideAuditCreatedByLabel = (string) ($handover['created_by_label'] ?? '');
      $asideAuditCreatedById = $handover['created_by'] ?? null;
      $asideAuditCreatedByUuid = (string) ($handover['created_by_uuid'] ?? '');
      $asideAuditModified = (string) ($handover['updated_at'] ?? '');
      $asideAuditModifiedByLabel = (string) ($handover['updated_by_label'] ?? '');
      $asideAuditModifiedById = $handover['updated_by'] ?? null;
      $asideAuditModifiedByUuid = (string) ($handover['updated_by_uuid'] ?? '');
      require templatePath('partials/app-details-aside-audit.phtml');
      ?>
      <hr>
    </div>
  </aside>
</div>
