<?php

final class Tickets
{
    public const STATUS_LABELS = [
        'new'              => 'חדשה',
        'triage'           => 'בבדיקת שירות לקוחות',
        'assigned'         => 'שויכה לטיפול',
        'in_progress'      => 'בטיפול',
        'pending_customer' => 'ממתינה ללקוח',
        'handler_done'     => 'הטיפול הסתיים, ממתינה לסגירה',
        'closed'           => 'סגורה',
        'cancelled'        => 'בוטלה',
    ];

    public const SEVERITY_LABELS = [
        'low' => 'נמוכה', 'medium' => 'בינונית', 'high' => 'גבוהה', 'critical' => 'קריטית',
    ];

    public const TYPE_LABELS = ['fault' => 'תקלה', 'training' => 'הדרכה והטמעה'];

    /** Reserves the next ticket number for the current year. */
    public static function nextNumber(): string
    {
        $year = (int) date('Y');
        DB::run('INSERT INTO ticket_counters (year, last_number) VALUES (?, 1)
                 ON DUPLICATE KEY UPDATE last_number = last_number + 1', [$year]);
        $n = (int) DB::value('SELECT last_number FROM ticket_counters WHERE year = ?', [$year]);
        return $year . '-' . str_pad((string) $n, 6, '0', STR_PAD_LEFT);
    }

    /** SQL fragment limiting the ticket list to what this user may see. */
    public static function scope(array $user, array &$params): string
    {
        switch ($user['role']) {
            case 'admin':
            case 'support':
                return '1=1';
            case 'customer':
                $params[] = $user['customer_id'];
                return 't.customer_id = ?';
            default: // technician, instructor
                $params[] = $user['id'];
                return 't.assigned_to = ?';
        }
    }

    public static function canView(array $user, array $ticket): bool
    {
        return match ($user['role']) {
            'admin', 'support' => true,
            'customer'         => (int) $ticket['customer_id'] === (int) $user['customer_id'],
            default            => (int) $ticket['assigned_to'] === (int) $user['id'],
        };
    }

    public static function find(int $id): array
    {
        $t = DB::one('SELECT * FROM tickets WHERE id = ?', [$id]);
        if (!$t) {
            throw new ApiError('הקריאה לא נמצאה', 404);
        }
        return $t;
    }

    /** Loads a ticket and checks the caller may see it. */
    public static function findVisible(array $user, int $id): array
    {
        $t = self::find($id);
        if (!self::canView($user, $t)) {
            throw new ApiError('אין הרשאה לצפות בקריאה זו', 403);
        }
        return $t;
    }

    public static function setStatus(int $ticketId, string $from, string $to, int $userId, ?string $note = null): void
    {
        if ($from === $to) {
            return;
        }
        DB::run('UPDATE tickets SET status = ? WHERE id = ?', [$to, $ticketId]);
        Audit::log($ticketId, $userId, 'status_changed', 'status',
            self::STATUS_LABELS[$from] ?? $from, self::STATUS_LABELS[$to] ?? $to, $note);
    }

    /** Copies a procedure template onto a ticket as its checklist. */
    public static function applyTemplate(int $ticketId, int $templateId): int
    {
        $items = DB::all(
            'SELECT * FROM procedure_template_items WHERE template_id = ? AND is_active = 1 ORDER BY sort_order, id',
            [$templateId]
        );
        foreach ($items as $it) {
            DB::run(
                'INSERT INTO ticket_tasks (ticket_id, template_id, template_item_id, sort_order, label, input_type, is_required)
                 VALUES (?,?,?,?,?,?,?)',
                [$ticketId, $templateId, $it['id'], $it['sort_order'], $it['label'], $it['input_type'], $it['is_required']]
            );
        }
        return count($items);
    }

    public static function defaultTemplateId(string $type): ?int
    {
        $id = DB::value(
            'SELECT id FROM procedure_templates
             WHERE is_active = 1 AND is_default = 1 AND applies_to IN (?, "both")
             ORDER BY applies_to = ? DESC, id LIMIT 1',
            [$type, $type]
        );
        return $id === null ? null : (int) $id;
    }
}
