<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_auth();
if (!can_create_ticket($user)) {
    http_response_code(403);
    exit('Za kreiranje zahteva morate imati osnovnu korisničku ulogu USERF ili USERDS.');
}
$ticketOrganizationUnit = user_organization_unit($user);
if ($ticketOrganizationUnit === null) {
    $assignedBaseRoles = array_values(array_intersect($user['role_codes'] ?? [], base_user_role_codes()));
    if (is_system_admin($user) && !$assignedBaseRoles) {
        // Backwards-compatible fallback for a legacy system administrator without a base role.
        $ticketOrganizationUnit = 'F';
    } else {
        http_response_code(409);
        exit('Nalog nema jednoznačnu organizacionu pripadnost za kreiranje tiketa. Administrator mora dodeliti tačno jednu osnovnu ulogu USERF ili USERDS.');
    }
}
$pageTitle = 'Novi zahtev';
$pageSubtitle = 'Prijava novog tiketa za podršku';
$locationOptions = ticket_location_options();
$priorityOptions = ticket_form_priority_options();
$defaultPriority = array_key_exists('low', $priorityOptions) ? 'low' : (string)array_key_first($priorityOptions);
$defaultCategory = 'Službeni prostor';
$defaultAssetInventoryNo = '';
$prefillEquipmentId = (int)($_GET['equipment_id'] ?? 0);
if ($prefillEquipmentId > 0) {
    $equipmentStmt = db()->prepare("SELECT inventory_no FROM equipment WHERE id = ? AND user_id = ? AND status IN ('assigned', 'repair') LIMIT 1");
    $equipmentStmt->execute([$prefillEquipmentId, (int)$user['id']]);
    $prefillEquipment = $equipmentStmt->fetch();
    if ($prefillEquipment) {
        $defaultAssetInventoryNo = trim((string)($prefillEquipment['inventory_no'] ?? ''));
        foreach (ticket_category_records(true) as $categoryRecord) {
            if ((string)$categoryRecord['name'] === 'ICT oprema') {
                $defaultCategory = 'ICT oprema';
                break;
            }
            if ((string)$categoryRecord['ticket_code'] === '1') {
                $defaultCategory = (string)$categoryRecord['name'];
            }
        }
    }
}
$defaultLocationKey = (string)array_key_first($locationOptions);
foreach ($locationOptions as $key => $label) {
    if (trim((string)($user['location'] ?? '')) !== '' && trim((string)$user['location']) === trim((string)$label)) {
        $defaultLocationKey = (string)$key;
        break;
    }
}

$errors = [];
$participantIds = normalize_participant_ids($_POST['participant_ids'] ?? []);
$selectedParticipantUsers = array_values(array_filter(participant_users_by_ids($participantIds), static function (array $participant) use ($user): bool {
    return (int)$participant['id'] !== (int)$user['id'];
}));
if (is_post()) {
    validate_csrf();
    $attachments = normalized_uploaded_files('attachments');
    $category = trim((string)($_POST['category'] ?? $defaultCategory));
    $priority = trim((string)($_POST['priority'] ?? $defaultPriority));
    $locationKey = trim((string)($_POST['department_location'] ?? ''));
    $departmentLocation = isset($locationOptions[$locationKey]) ? trim((string)$locationOptions[$locationKey]) : '';
    $issueLocation = trim((string)($_POST['issue_location'] ?? ''));
    $assetInventoryNo = trim((string)($_POST['asset_inventory_no'] ?? $defaultAssetInventoryNo));
    $description = trim((string)($_POST['description'] ?? ''));
    $title = limit_text($issueLocation !== '' ? $category . ' — ' . $issueLocation : $category, 190);

    if (!array_key_exists($category, category_options())) {
        $errors[] = 'Izaberite validnu kategoriju.';
    }
    if (!array_key_exists($priority, $priorityOptions)) {
        $errors[] = 'Izaberite validan prioritet.';
    }
    if ($departmentLocation === '') {
        $errors[] = 'Izaberite odeljenje ili lokaciju.';
    }
    if ($issueLocation !== '' && (mb_strlen($issueLocation) < 3 || mb_strlen($issueLocation) > 190)) {
        $errors[] = 'Mesto kvara mora imati između 3 i 190 karaktera kada je uneto.';
    }
    if (mb_strlen($assetInventoryNo) > 120) {
        $errors[] = 'Inventarski broj može imati najviše 120 karaktera.';
    }
    if ($description === '') {
        $errors[] = 'Molimo unesite opis problema.';
    } elseif (mb_strlen($description) < 10) {
        $errors[] = 'Opis problema mora imati najmanje 10 karaktera.';
    }
    if (mb_strlen($description) > 2500) {
        $errors[] = 'Opis može imati najviše 2500 karaktera.';
    }
    $errors = array_merge($errors, validate_ticket_attachments($attachments));

    if (!$errors) {
        $responsibleRoleCode = category_responsible_role_code($category, $ticketOrganizationUnit);
        $pdo = db();
        $savedPaths = [];
        $addedParticipants = [];
        try {
            $pdo->beginTransaction();
            $ticketNo = generate_ticket_no($pdo, $category);
            $stmt = $pdo->prepare('INSERT INTO tickets (ticket_no, user_id, responsible_role_code, title, description, category, department_location, issue_location, asset_inventory_no, priority, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "open", NOW(), NOW())');
            $stmt->execute([$ticketNo, $user['id'], $responsibleRoleCode, $title, $description, $category, $departmentLocation, $issueLocation !== '' ? $issueLocation : null, $assetInventoryNo !== '' ? $assetInventoryNo : null, $priority]);
            $ticketId = (int)$pdo->lastInsertId();
            $savedPaths = store_ticket_attachments($pdo, $ticketId, (int)$user['id'], $attachments);
            $addedParticipants = add_ticket_participants($pdo, $ticketId, (int)$user['id'], (int)$user['id'], $participantIds);
            audit_ticket_event($ticketId, (int)$user['id'], 'created', null, 'open');
            audit_ticket_event($ticketId, (int)$user['id'], 'responsible_role_set', null, $responsibleRoleCode);
            foreach ($addedParticipants as $participant) {
                audit_ticket_event($ticketId, (int)$user['id'], 'participant_added', null, (string)$participant['name']);
            }
            notify_responsible_role($responsibleRoleCode, 'Novi zahtev ' . $ticketNo, $user['name'] . ' je prijavio/la zahtev: ' . $title, 'ticket_view.php?id=' . $ticketId, [(int)$user['id']]);
            $pdo->commit();
            foreach ($addedParticipants as $participant) {
                notify_user((int)$participant['id'], 'Dodati ste kao učesnik', $user['name'] . ' vas je dodao/la kao učesnika na zahtev ' . $ticketNo . ': ' . $title, 'ticket_view.php?id=' . $ticketId);
            }
            flash('success', 'Zahtev je kreiran: ' . $ticketNo);
            redirect('ticket_view.php?id=' . $ticketId);
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            foreach ($savedPaths as $path) {
                if (is_file($path)) {
                    unlink($path);
                }
            }
            $errors[] = 'Zahtev nije sačuvan. Proverite da li su importovani upgrade_v3_7.sql, upgrade_v3_8.sql i upgrade_v3_15.sql i da li folder uploads/tickets ima dozvolu za upis.';
        }
    }
}

require_once __DIR__ . '/app/header.php';
?>
<section class="card card-pad ticket-create-card">
    <div class="section-heading">
        <div>
            <span class="badge">Novi tiket</span>
            <h2>Prijava kvara / zahteva</h2>
            <p>Popunite osnovne podatke kako bi podrška mogla brže da obradi zahtev.</p>
        </div>
    </div>

    <?php foreach ($errors as $error): ?>
        <div class="alert alert-danger"><?= e($error) ?></div>
    <?php endforeach; ?>

    <form method="post" enctype="multipart/form-data" class="ticket-create-form">
        <?= csrf_field() ?>
        <label class="ticket-form-group">Kategorija
            <select name="category" required>
                <?php foreach (category_options() as $value => $label): ?>
                    <option value="<?= e($value) ?>" <?= safe_selected($_POST['category'] ?? $defaultCategory, $value) ?>><?= e($label) ?></option>
                <?php endforeach; ?>
            </select>
        </label>
        <label class="ticket-form-group">Prioritet
            <select name="priority" required>
                <?php foreach ($priorityOptions as $value => $label): ?>
                    <option value="<?= e($value) ?>" <?= safe_selected($_POST['priority'] ?? $defaultPriority, $value) ?>><?= e($label) ?></option>
                <?php endforeach; ?>
            </select>
        </label>
        <label class="ticket-form-group">Odeljenje / Lokacija
            <select name="department_location" required>
                <?php foreach ($locationOptions as $value => $label): ?>
                    <option value="<?= e($value) ?>" <?= safe_selected($_POST['department_location'] ?? $defaultLocationKey, $value) ?>><?= e($label) ?></option>
                <?php endforeach; ?>
            </select>
        </label>
        <label class="ticket-form-group">Mesto kvara
            <input type="text" name="issue_location" minlength="3" maxlength="190" value="<?= e($_POST['issue_location'] ?? '') ?>" placeholder="Unesite mesto gde se dogodio kvar (opciono)">
        </label>
        <label class="ticket-form-group">Inventarski broj uređaja / osnovnog sredstva
            <input type="text" name="asset_inventory_no" maxlength="120" value="<?= e($_POST['asset_inventory_no'] ?? $defaultAssetInventoryNo) ?>" placeholder="Npr. 3107FEQ123">
        </label>
        <div class="ticket-form-group ticket-form-full participant-picker" data-participant-picker data-search-url="<?= e(url('participant_search.php?context=create&csrf_token=' . rawurlencode(csrf_token()))) ?>">
            <span class="ticket-form-label">Učesnici</span>
            <div class="participant-search-wrap">
                <input type="search" autocomplete="off" data-participant-search placeholder="Pretražite ime ili email postojećeg korisnika" aria-label="Pretražite učesnike" aria-autocomplete="list" aria-expanded="false">
                <div class="participant-results" data-participant-results role="listbox" hidden></div>
            </div>
            <div class="participant-selected" data-participant-selected aria-live="polite">
                <?php foreach ($selectedParticipantUsers as $participant): ?>
                    <span class="participant-chip" data-participant-id="<?= (int)$participant['id'] ?>">
                        <span><?= e($participant['name']) ?> · <?= e($participant['email']) ?></span>
                        <button type="button" data-remove-participant aria-label="Ukloni učesnika <?= e($participant['name']) ?>">×</button>
                        <input type="hidden" name="participant_ids[]" value="<?= (int)$participant['id'] ?>">
                    </span>
                <?php endforeach; ?>
            </div>
            <small>Izabrani korisnici će moći da prate tiket, komentarišu i dodaju priloge.</small>
        </div>
        <label class="ticket-form-group ticket-form-full ticket-description-field">Opis problema
            <textarea name="description" rows="7" required minlength="10" maxlength="2500" data-description-input placeholder="Npr. neispravna rasveta, neobičan zvuk motora, štampač ne radi…"><?= e($_POST['description'] ?? '') ?></textarea>
            <span class="description-counter" data-description-counter>0 / 2500</span>
        </label>
        <div class="ticket-form-group ticket-form-full">
            <span class="ticket-form-label">Prilozi</span>
            <div class="ticket-file-dropzone" data-ticket-dropzone tabindex="0" role="button" aria-label="Izaberite priloge">
                <strong>Prevucite fajlove ovde</strong><span> ili kliknite da izaberete</span>
                <small>Do 10 fajlova, ukupno najviše 50 MB. Dozvoljeno: JPG, JPEG, PNG, PDF, XLS, XLSX i TXT.</small>
                <input type="file" name="attachments[]" hidden multiple accept=".jpg,.jpeg,.png,.pdf,.xls,.xlsx,.txt" data-ticket-attachments data-max-files="<?= ticket_attachment_max_files() ?>" data-max-bytes="<?= ticket_attachment_max_total_bytes() ?>">
            </div>
            <div class="ticket-file-list" data-ticket-file-list aria-live="polite"></div>
            <span class="attachment-selection" data-attachment-selection aria-live="polite"></span>
        </div>
        <div class="inline-actions ticket-form-actions ticket-form-full">
            <a class="button button-light" href="<?= e(url('tickets.php')) ?>">Odustani</a>
            <button class="button button-primary" type="submit">Pošalji tiket</button>
        </div>
    </form>
</section>
<?php require_once __DIR__ . '/app/footer.php'; ?>
