<?php

use MintyPHP\Buffer;
use MintyPHP\DB;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\HandoverService;
use MintyPHP\Module\Helpdesk\Service\SoftwareProductService;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(HelpdeskAuthorizationPolicy::ABILITY_HANDOVERS_MANAGE);

$request = requestInput();
$returnTarget = requestResolveReturnTarget('helpdesk/handovers');
$handoverId = (int) ($id ?? 0);
$editTarget = lurl('helpdesk/handovers/edit/' . $handoverId);
$assignTarget = lurl('helpdesk/handovers/assign/' . $handoverId);

$session = app(SessionStoreInterface::class)->all();
$tenantId = (int) ($session['current_tenant']['id'] ?? 0);
$userId = (int) ($session['user']['id'] ?? 0);

$service = app(HandoverService::class);
$handover = $service->findById($tenantId, $handoverId);

if ($handover === null) {
    Flash::error(t('Handover not found'), $returnTarget, 'handover_not_found');
    Router::redirect($returnTarget);
    return;
}

$errorBag = formErrors();

if ($request->isMethod('POST')) {
    if (!Session::checkCsrfToken()) {
        Flash::error(t('Form expired, please try again'), $assignTarget, 'csrf_expired');
        Router::redirect($assignTarget);
        return;
    }

    $assignedTo = (int) $request->body('assigned_to', 0);
    $dueDate = trim((string) $request->body('due_date', ''));
    $resend = (string) $request->body('action', '') === 'resend';

    if ($resend) {
        $result = $service->resendNotification($tenantId, $handoverId, HandoverService::PERMISSION_MANAGE);
        if ($result['ok']) {
            Flash::success(t('Notification resent'), $editTarget, 'notification_resent');
        } else {
            $firstError = reset($result['errors']) ?: t('Failed to resend notification');
            Flash::error($firstError, $editTarget, 'notification_resend_failed');
        }
        Router::redirect($editTarget);
        return;
    }

    $result = $service->assign($tenantId, $handoverId, $assignedTo, $userId, $dueDate ?: null, HandoverService::PERMISSION_MANAGE);

    if ($result['ok']) {
        Flash::success(t('Handover assigned'), $editTarget, 'handover_assigned');
        Router::redirect($editTarget);
        return;
    }

    foreach ($result['errors'] as $key => $msg) {
        $errorBag->add($key, $msg);
    }
}

// Load active users for this tenant for the assignee dropdown
$tenantUsers = DB::select(
    'SELECT u.id, u.display_name, u.email'
    . ' FROM users u'
    . ' JOIN user_tenants ut ON ut.user_id = u.id'
    . ' WHERE ut.tenant_id = ? AND u.active = 1'
    . ' ORDER BY u.display_name ASC',
    (string) $tenantId
);
if (!is_array($tenantUsers)) {
    $tenantUsers = [];
}

$productCode = (string) ($handover['product_code'] ?? '');
$product = app(SoftwareProductService::class)->findByCode($productCode);
$productName = trim((string) ($product['name'] ?? '')) !== ''
    ? $product['name']
    : (trim((string) ($product['bc_description'] ?? '')) !== '' ? $product['bc_description'] : $productCode);

$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();

$titleText = t('Assign handover');
Buffer::set('title', $titleText);
Buffer::set('style_groups', json_encode(['helpdesk']));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Helpdesk'), 'path' => 'helpdesk'],
    ['label' => t('Handovers'), 'path' => 'helpdesk/handovers'],
    ['label' => $productName, 'path' => 'helpdesk/handovers/edit/' . $handoverId],
    ['label' => $titleText],
];
