<?php

/** GET /api/tickets — list, scoped by role. */
route('GET', ['tickets'], function () {
    $u      = Auth::require();
    $params = [];
    $where  = [Tickets::scope($u, $params)];

    if (!empty($_GET['status'])) {
        $where[]  = 't.status = ?';
        $params[] = $_GET['status'];
    }
    if (!empty($_GET['type'])) {
        $where[]  = 't.type = ?';
        $params[] = $_GET['type'];
    }
    if (!empty($_GET['q'])) {
        $where[]  = '(t.ticket_number LIKE ? OR t.description LIKE ? OR t.serial_snapshot LIKE ? OR t.location LIKE ?)';
        $like     = '%' . $_GET['q'] . '%';
        array_push($params, $like, $like, $like, $like);
    }
    if (isset($_GET['open']) && $_GET['open'] === '1') {
        $where[] = 't.status NOT IN ("closed", "cancelled")';
    }

    Response::json(DB::all(
        'SELECT t.id, t.ticket_number, t.type, t.status, t.severity, t.location, t.unit_name,
                t.description, t.created_at, t.handler_done_at, t.closed_at,
                c.name AS customer_name, p.name AS product_name, t.serial_snapshot,
                creator.full_name AS created_by_name, handler.full_name AS assigned_to_name
         FROM tickets t
         JOIN customers c      ON c.id = t.customer_id
         LEFT JOIN products p  ON p.id = t.product_id
         JOIN users creator    ON creator.id = t.created_by
         LEFT JOIN users handler ON handler.id = t.assigned_to
         WHERE ' . implode(' AND ', $where) . '
         ORDER BY FIELD(t.status, "new","triage","assigned","in_progress","pending_customer","handler_done","closed","cancelled"),
                  FIELD(t.severity, "critical","high","medium","low"), t.created_at DESC
         LIMIT 500',
        $params
    ));
});

/** POST /api/tickets — a customer opens a ticket. */
route('POST', ['tickets'], function () {
    $u = Auth::require('customer', 'support', 'admin');
    $b = Response::body();

    $type = (string) ($b['type'] ?? '');
    if (!isset(Tickets::TYPE_LABELS[$type])) {
        throw new ApiError('יש לבחור סוג קריאה', 400);
    }
    $description = trim((string) ($b['description'] ?? ''));
    if ($description === '') {
        throw new ApiError('יש למלא תיאור', 400);
    }

    $customerId = $u['role'] === 'customer' ? (int) $u['customer_id'] : (int) ($b['customer_id'] ?? 0);
    if ($customerId <= 0) {
        throw new ApiError('יש לבחור לקוח', 400);
    }

    // The customer states how urgent it is from their side. Customer service can
    // still change it at triage — this is a request, not the final word.
    $severity = (string) ($b['severity'] ?? '');
    if ($severity !== '' && !isset(Tickets::SEVERITY_LABELS[$severity])) {
        throw new ApiError('רמת תיעדוף לא חוקית', 400);
    }

    // The serial can come from the catalog, or be typed in when the unit is not
    // registered yet — a customer should never be blocked from opening a call
    // just because the office has not added their device.
    $unitId = !empty($b['product_unit_id']) ? (int) $b['product_unit_id'] : null;
    if ($unitId) {
        $serial = DB::value('SELECT serial_number FROM product_units WHERE id = ?', [$unitId]);
    } else {
        $serial = mb_substr(trim((string) ($b['serial_number'] ?? '')), 0, 80) ?: null;
        // If that serial is already registered, link the ticket to it properly.
        if ($serial !== null) {
            $existing = DB::value('SELECT id FROM product_units WHERE serial_number = ?', [$serial]);
            if ($existing) {
                $unitId = (int) $existing;
            }
        }
    }

    $pdo = DB::conn();
    $pdo->beginTransaction();
    try {
        $number = Tickets::nextNumber();
        $id = DB::insert(
            'INSERT INTO tickets
             (ticket_number, type, status, severity, customer_id, created_by, manufacturer_id, product_id,
              product_unit_id, serial_snapshot, unit_name, contact_name, contact_phone, location, description)
             VALUES (?,?,"new",?,?,?,?,?,?,?,?,?,?,?,?)',
            [
                $number, $type, $severity !== '' ? $severity : null, $customerId, $u['id'],
                !empty($b['manufacturer_id']) ? (int) $b['manufacturer_id'] : null,
                !empty($b['product_id']) ? (int) $b['product_id'] : null,
                $unitId, $serial,
                trim((string) ($b['unit_name'] ?? '')) ?: null,
                trim((string) ($b['contact_name'] ?? '')) ?: null,
                trim((string) ($b['contact_phone'] ?? '')) ?: null,
                trim((string) ($b['location'] ?? '')) ?: null,
                $description,
            ]
        );
        $pdo->commit();
    } catch (Throwable $e) {
        $pdo->rollBack();
        throw $e;
    }

    Audit::log($id, $u['id'], 'created', null, null, null, 'נפתחה קריאה חדשה');

    $customerName = (string) DB::value('SELECT name FROM customers WHERE id = ?', [$customerId]);
    $productName  = (string) DB::value('SELECT name FROM products WHERE id = ?', [$b['product_id'] ?? 0]);
    $link         = Mailer::ticketUrl($id);

    Mailer::queueToSupport(
        "קריאה חדשה {$number} — " . Tickets::TYPE_LABELS[$type],
        Mailer::template('נפתחה קריאה חדשה במערכת', [
            'מספר קריאה' => $number,
            'סוג'         => Tickets::TYPE_LABELS[$type],
            'לקוח'        => $customerName,
            'פותח הקריאה' => $u['full_name'],
            'איש קשר'     => trim(($b['contact_name'] ?? '') . ' ' . ($b['contact_phone'] ?? '')),
            'יחידה'       => (string) ($b['unit_name'] ?? ''),
            'מיקום'       => (string) ($b['location'] ?? ''),
            'מוצר'        => $productName,
            'מספר סידורי' => (string) $serial,
            'תיאור'       => $description,
        ], 'הודעה זו נשלחה אוטומטית ממערכת קריאות השירות.', $link, 'טיפול בקריאה'),
        $id
    );

    // Confirmation to whoever opened it, so they have the number and a way back.
    Mailer::queue($u['email'], "נפתחה קריאה {$number}",
        Mailer::template('הקריאה שלך נקלטה', [
            'מספר קריאה' => $number,
            'סוג'         => Tickets::TYPE_LABELS[$type],
            'מוצר'        => $productName,
            'מספר סידורי' => (string) $serial,
            'תיאור'       => $description,
        ], 'נעדכן אותך בהתקדמות הטיפול. אפשר לעקוב ולהוסיף פרטים דרך הקישור.',
           $link, 'מעבר לקריאה'),
        $id);

    Response::json(['id' => $id, 'ticket_number' => $number], 201);
});

/** GET /api/tickets/{id} — full view: fields, checklist, attachments, comments, history. */
route('GET', ['tickets', '#'], function (int $id) {
    $u = Auth::require();
    $t = Tickets::findVisible($u, $id);
    $isStaff = $u['role'] !== 'customer';

    $t['customer_name']     = DB::value('SELECT name FROM customers WHERE id = ?', [$t['customer_id']]);
    $t['product_name']      = DB::value('SELECT name FROM products WHERE id = ?', [$t['product_id']]);
    $t['manufacturer_name'] = DB::value('SELECT name FROM manufacturers WHERE id = ?', [$t['manufacturer_id']]);
    $t['created_by_name']   = DB::value('SELECT full_name FROM users WHERE id = ?', [$t['created_by']]);
    $t['assigned_to_name']  = $t['assigned_to'] ? DB::value('SELECT full_name FROM users WHERE id = ?', [$t['assigned_to']]) : null;
    $t['closed_by_name']    = $t['closed_by'] ? DB::value('SELECT full_name FROM users WHERE id = ?', [$t['closed_by']]) : null;

    Response::json([
        'ticket'      => $t,
        'tasks'       => $isStaff
            ? DB::all('SELECT tt.*, u.full_name AS completed_by_name
                       FROM ticket_tasks tt LEFT JOIN users u ON u.id = tt.completed_by
                       WHERE tt.ticket_id = ? ORDER BY tt.sort_order, tt.id', [$id])
            : [],
        'attachments' => DB::all(
            'SELECT a.id, a.original_name, a.mime_type, a.size_bytes, a.kind, a.created_at, u.full_name AS uploaded_by_name
             FROM ticket_attachments a JOIN users u ON u.id = a.uploaded_by
             WHERE a.ticket_id = ?' . ($isStaff ? '' : ' AND a.is_internal = 0') . '
             ORDER BY a.created_at', [$id]),
        'comments'    => DB::all(
            'SELECT c.id, c.body, c.is_internal, c.created_at, u.full_name AS author_name
             FROM ticket_comments c JOIN users u ON u.id = c.user_id
             WHERE c.ticket_id = ?' . ($isStaff ? '' : ' AND c.is_internal = 0') . '
             ORDER BY c.created_at', [$id]),
        'history'     => $isStaff
            ? DB::all('SELECT h.action, h.field_name, h.old_value, h.new_value, h.note, h.created_at, u.full_name AS user_name
                       FROM ticket_history h LEFT JOIN users u ON u.id = h.user_id
                       WHERE h.ticket_id = ? ORDER BY h.created_at, h.id', [$id])
            : [],
    ]);
});

/**
 * PATCH /api/tickets/{id}
 * Customers keep remembering details after they press send, so a ticket stays
 * editable until it is closed. Every change is written to the history.
 */
route('PATCH', ['tickets', '#'], function (int $id) {
    $u = Auth::require();
    $t = Tickets::findVisible($u, $id);

    if (in_array($u['role'], ['technician', 'instructor'], true)) {
        throw new ApiError('עדכון פרטי הקריאה נעשה על ידי הלקוח או שירות הלקוחות', 403);
    }
    if ($u['role'] === 'customer' && in_array($t['status'], ['closed', 'cancelled'], true)) {
        throw new ApiError('לא ניתן לערוך קריאה סגורה. אפשר לפתוח קריאה חדשה.', 409);
    }

    $b       = Response::body();
    $changes = [];

    $editable = [
        'unit_name'     => 'יחידה',
        'contact_name'  => 'איש קשר',
        'contact_phone' => 'טלפון',
        'location'      => 'מיקום',
        'description'   => 'תיאור',
    ];
    foreach ($editable as $field => $label) {
        if (!array_key_exists($field, $b)) {
            continue;
        }
        $value = trim((string) $b[$field]) ?: null;
        if ($field === 'description' && $value === null) {
            throw new ApiError('לא ניתן למחוק את התיאור', 400);
        }
        if ($value !== $t[$field]) {
            DB::run("UPDATE tickets SET {$field} = ? WHERE id = ?", [$value, $id]);
            Audit::log($id, $u['id'], 'edited', $field, (string) $t[$field], (string) $value);
            $changes[$label] = (string) $value;
        }
    }

    if (array_key_exists('severity', $b)) {
        $sev = (string) $b['severity'];
        if ($sev !== '' && !isset(Tickets::SEVERITY_LABELS[$sev])) {
            throw new ApiError('רמת תיעדוף לא חוקית', 400);
        }
        if ($sev !== (string) $t['severity']) {
            DB::run('UPDATE tickets SET severity = ? WHERE id = ?', [$sev ?: null, $id]);
            Audit::log($id, $u['id'], 'severity_set', 'severity',
                Tickets::SEVERITY_LABELS[$t['severity']] ?? null, Tickets::SEVERITY_LABELS[$sev] ?? null);
            $changes['תיעדוף'] = Tickets::SEVERITY_LABELS[$sev] ?? '';
        }
    }

    if (array_key_exists('serial_number', $b) || array_key_exists('product_id', $b)) {
        $productId = !empty($b['product_id']) ? (int) $b['product_id'] : null;
        $serial    = mb_substr(trim((string) ($b['serial_number'] ?? '')), 0, 80) ?: null;
        $unitId    = $serial ? DB::value('SELECT id FROM product_units WHERE serial_number = ?', [$serial]) : null;
        DB::run('UPDATE tickets SET product_id = ?, serial_snapshot = ?, product_unit_id = ? WHERE id = ?',
            [$productId, $serial, $unitId ? (int) $unitId : null, $id]);
        if ($serial !== $t['serial_snapshot']) {
            Audit::log($id, $u['id'], 'edited', 'serial', (string) $t['serial_snapshot'], (string) $serial);
            $changes['מספר סידורי'] = (string) $serial;
        }
    }

    // Tell the desk what the customer added, so nobody has to spot it themselves.
    if ($changes && $u['role'] === 'customer') {
        Mailer::queueToSupport("עודכנו פרטים בקריאה {$t['ticket_number']}",
            Mailer::template('הלקוח עדכן פרטים בקריאה',
                array_merge(['מספר קריאה' => $t['ticket_number'], 'עודכן על ידי' => $u['full_name']], $changes),
                null, Mailer::ticketUrl($id), 'צפייה בקריאה'),
            $id);
    }

    Response::json(['ok' => true, 'changed' => array_keys($changes)]);
});

/**
 * DELETE /api/tickets/{id}
 * Permanent. Tasks, comments, history and attachment rows go with it through
 * the foreign keys; the uploaded files are removed from disk here.
 */
route('DELETE', ['tickets', '#'], function (int $id) {
    Auth::require('admin');
    $t = Tickets::find($id);

    foreach (DB::all('SELECT rel_path, stored_name FROM ticket_attachments WHERE ticket_id = ?', [$id]) as $a) {
        @unlink(Uploads::dir() . '/' . $a['rel_path'] . '/' . $a['stored_name']);
    }
    DB::run('DELETE FROM tickets WHERE id = ?', [$id]);
    Response::json(['ok' => true, 'deleted' => $t['ticket_number']]);
});

/** POST /api/tickets/{id}/assign — customer service sets severity and routes the ticket. */
route('POST', ['tickets', '#', 'assign'], function (int $id) {
    $u = Auth::require('support', 'admin');
    $t = Tickets::find($id);
    $b = Response::body();

    $severity   = (string) ($b['severity'] ?? '');
    $assignedTo = (int) ($b['assigned_to'] ?? 0);
    if (!isset(Tickets::SEVERITY_LABELS[$severity])) {
        throw new ApiError('יש לבחור רמת חומרה', 400);
    }
    $handler = DB::one('SELECT u.id, u.full_name, u.email, r.code AS role
                        FROM users u JOIN roles r ON r.id = u.role_id
                        WHERE u.id = ? AND u.is_active = 1', [$assignedTo]);
    if (!$handler || !in_array($handler['role'], ['technician', 'instructor'], true)) {
        throw new ApiError('יש לבחור טכנאי או מדריך', 400);
    }

    $templateId = !empty($b['template_id']) ? (int) $b['template_id'] : Tickets::defaultTemplateId($t['type']);

    DB::run('UPDATE tickets SET severity = ?, assigned_to = ?, assigned_by = ?, assigned_at = NOW(), due_at = ?
             WHERE id = ?',
        [$severity, $assignedTo, $u['id'], !empty($b['due_at']) ? $b['due_at'] : null, $id]);

    // Reapply the checklist only if the ticket does not already have one.
    $hasTasks = (int) DB::value('SELECT COUNT(*) FROM ticket_tasks WHERE ticket_id = ?', [$id]);
    if (!$hasTasks && $templateId) {
        Tickets::applyTemplate($id, $templateId);
    }

    Audit::log($id, $u['id'], 'assigned', 'assigned_to', $t['assigned_to'], $handler['full_name']);
    Audit::log($id, $u['id'], 'severity_set', 'severity',
        Tickets::SEVERITY_LABELS[$t['severity']] ?? null, Tickets::SEVERITY_LABELS[$severity]);
    Tickets::setStatus($id, $t['status'], 'assigned', $u['id']);

    $customerName = (string) DB::value('SELECT name FROM customers WHERE id = ?', [$t['customer_id']]);
    Mailer::queue($handler['email'], "שויכה אליך קריאה {$t['ticket_number']}",
        Mailer::template('שויכה אליך קריאה לטיפול', [
            'מספר קריאה' => $t['ticket_number'],
            'סוג'         => Tickets::TYPE_LABELS[$t['type']],
            'חומרה'       => Tickets::SEVERITY_LABELS[$severity],
            'לקוח'        => $customerName,
            'איש קשר'     => trim(($t['contact_name'] ?? '') . ' ' . ($t['contact_phone'] ?? '')),
            'מיקום'       => (string) $t['location'],
            'תיאור'       => (string) $t['description'],
        ], 'הכניסה למערכת דורשת שם משתמש וסיסמה כרגיל.',
           Mailer::ticketUrl($id), 'פתיחת הקריאה'),
        $id);

    // The customer's own users hear that someone is on it.
    foreach (DB::all('SELECT email FROM users WHERE customer_id = ? AND is_active = 1', [$t['customer_id']]) as $cu) {
        Mailer::queue($cu['email'], "קריאה {$t['ticket_number']} הועברה לטיפול",
            Mailer::template('הקריאה הועברה לטיפול', [
                'מספר קריאה' => $t['ticket_number'],
                'מטפל'        => $handler['full_name'],
                'רמת חומרה'   => Tickets::SEVERITY_LABELS[$severity],
            ], null, Mailer::ticketUrl($id), 'מעבר לקריאה'),
            $id);
    }

    Response::json(['ok' => true]);
});

/** PATCH /api/tickets/{id}/tasks/{taskId} — the handler fills in one checklist row. */
route('PATCH', ['tickets', '#', 'tasks', '#'], function (int $id, int $taskId) {
    $u = Auth::requireStaff();
    $t = Tickets::findVisible($u, $id);
    if (in_array($t['status'], ['closed', 'cancelled'], true)) {
        throw new ApiError('לא ניתן לעדכן קריאה סגורה', 409);
    }
    $task = DB::one('SELECT * FROM ticket_tasks WHERE id = ? AND ticket_id = ?', [$taskId, $id]);
    if (!$task) {
        throw new ApiError('הסעיף לא נמצא', 404);
    }

    $b     = Response::body();
    $value = array_key_exists('value_text', $b) ? (string) $b['value_text'] : $task['value_text'];
    $done  = array_key_exists('is_done', $b) ? (int) (bool) $b['is_done'] : (int) $task['is_done'];

    DB::run('UPDATE ticket_tasks SET value_text = ?, is_done = ?,
             completed_by = ?, completed_at = ? WHERE id = ?',
        [$value, $done, $done ? $u['id'] : null, $done ? date('Y-m-d H:i:s') : null, $taskId]);

    if ($t['status'] === 'assigned') {
        Tickets::setStatus($id, 'assigned', 'in_progress', $u['id']);
        if ($t['first_response_at'] === null) {
            DB::run('UPDATE tickets SET first_response_at = NOW() WHERE id = ?', [$id]);
        }
    }
    Response::json(['ok' => true, 'status' => DB::value('SELECT status FROM tickets WHERE id = ?', [$id])]);
});

/** POST /api/tickets/{id}/handler-done — the technician or instructor finishes. */
route('POST', ['tickets', '#', 'handler-done'], function (int $id) {
    $u = Auth::requireStaff();
    $t = Tickets::findVisible($u, $id);

    $missing = DB::all('SELECT label FROM ticket_tasks WHERE ticket_id = ? AND is_required = 1 AND is_done = 0', [$id]);
    if ($missing) {
        throw new ApiError('יש להשלים סעיפי חובה: ' . implode(', ', array_column($missing, 'label')), 400);
    }
    $summary = trim((string) (Response::body()['handler_summary'] ?? ''));
    if ($summary === '') {
        throw new ApiError('יש לכתוב סיכום טיפול', 400);
    }

    DB::run('UPDATE tickets SET handler_summary = ?, handler_done_at = NOW() WHERE id = ?', [$summary, $id]);
    Tickets::setStatus($id, $t['status'], 'handler_done', $u['id'], 'הטיפול הועבר לשירות לקוחות');

    Mailer::queueToSupport("הסתיים הטיפול בקריאה {$t['ticket_number']}",
        Mailer::template('הטיפול הסתיים וממתין לסגירה', [
            'מספר קריאה' => $t['ticket_number'],
            'מטפל'        => $u['full_name'],
            'סיכום'       => $summary,
        ], null, Mailer::ticketUrl($id), 'בדיקה וסגירה'), $id);

    Response::json(['ok' => true]);
});

/** POST /api/tickets/{id}/close — customer service closes the ticket. */
route('POST', ['tickets', '#', 'close'], function (int $id) {
    $u = Auth::require('support', 'admin');
    $t = Tickets::find($id);
    if ($t['status'] === 'closed') {
        throw new ApiError('הקריאה כבר סגורה', 409);
    }
    $summary = trim((string) (Response::body()['close_summary'] ?? ''));
    DB::run('UPDATE tickets SET close_summary = ?, closed_by = ?, closed_at = NOW() WHERE id = ?',
        [$summary ?: null, $u['id'], $id]);
    Tickets::setStatus($id, $t['status'], 'closed', $u['id'], $summary ?: null);

    $body = Mailer::template('הקריאה נסגרה', [
        'מספר קריאה' => $t['ticket_number'],
        'סוג'         => Tickets::TYPE_LABELS[$t['type']],
        'נסגרה על ידי' => $u['full_name'],
        'סיכום'        => $summary,
    ], 'אם הנושא חוזר, אפשר לפתוח קריאה חדשה או להשיב להודעה זו.',
       Mailer::ticketUrl($id), 'צפייה בקריאה');

    $recipients = DB::all('SELECT email FROM users WHERE customer_id = ? AND is_active = 1', [$t['customer_id']]);
    if ($t['assigned_to']) {
        $handlerEmail = DB::value('SELECT email FROM users WHERE id = ?', [$t['assigned_to']]);
        if ($handlerEmail) {
            $recipients[] = ['email' => $handlerEmail];
        }
    }
    foreach (array_unique(array_column($recipients, 'email')) as $to) {
        Mailer::queue($to, "נסגרה קריאה {$t['ticket_number']}", $body, $id);
    }

    Response::json(['ok' => true]);
});

/** POST /api/tickets/{id}/reopen — send it back to the handler. */
route('POST', ['tickets', '#', 'reopen'], function (int $id) {
    $u = Auth::require('support', 'admin');
    $t = Tickets::find($id);
    $note = trim((string) (Response::body()['note'] ?? ''));
    DB::run('UPDATE tickets SET closed_at = NULL, closed_by = NULL, handler_done_at = NULL WHERE id = ?', [$id]);
    Tickets::setStatus($id, $t['status'], $t['assigned_to'] ? 'in_progress' : 'triage', $u['id'], $note ?: 'הקריאה הוחזרה לטיפול');
    Response::json(['ok' => true]);
});

/** POST /api/tickets/{id}/status — support moves a ticket to triage or pending_customer. */
route('POST', ['tickets', '#', 'status'], function (int $id) {
    $u = Auth::requireStaff();
    $t = Tickets::findVisible($u, $id);
    $to = (string) (Response::body()['status'] ?? '');
    if (!in_array($to, ['triage', 'pending_customer', 'in_progress', 'cancelled'], true)) {
        throw new ApiError('סטטוס לא חוקי', 400);
    }
    Tickets::setStatus($id, $t['status'], $to, $u['id'], (string) (Response::body()['note'] ?? '') ?: null);
    Response::json(['ok' => true]);
});

/** POST /api/tickets/{id}/comments */
route('POST', ['tickets', '#', 'comments'], function (int $id) {
    $u = Auth::require();
    $t = Tickets::findVisible($u, $id);
    $body = trim((string) (Response::body()['body'] ?? ''));
    if ($body === '') {
        throw new ApiError('לא ניתן לשלוח הודעה ריקה', 400);
    }
    $internal = $u['role'] !== 'customer' && !empty(Response::body()['is_internal']);
    DB::insert('INSERT INTO ticket_comments (ticket_id, user_id, body, is_internal) VALUES (?,?,?,?)',
        [$id, $u['id'], $body, $internal ? 1 : 0]);
    Response::json(['ok' => true], 201);
});
