<?php

/** POST /api/tickets/{id}/attachments — multipart upload of images and video. */
route('POST', ['tickets', '#', 'attachments'], function (int $id) {
    $u = Auth::require();
    $t = Tickets::findVisible($u, $id);
    if ($u['role'] === 'customer' && in_array($t['status'], ['closed', 'cancelled'], true)) {
        throw new ApiError('לא ניתן להוסיף קבצים לקריאה סגורה', 409);
    }

    Uploads::assertRequestFits();
    $files = Uploads::normalise('files');
    if (!$files) {
        throw new ApiError('לא התקבלו קבצים. אם מדובר בקבצים גדולים, ייתכן שהם חורגים ממגבלת השרת.', 400);
    }
    $taskId   = !empty($_POST['ticket_task_id']) ? (int) $_POST['ticket_task_id'] : null;
    $internal = $u['role'] !== 'customer' && !empty($_POST['is_internal']);

    $saved = [];
    foreach ($files as $file) {
        $meta = Uploads::store($file, $id);
        $saved[] = DB::insert(
            'INSERT INTO ticket_attachments
             (ticket_id, ticket_task_id, uploaded_by, original_name, stored_name, rel_path, mime_type, size_bytes, kind, is_internal)
             VALUES (?,?,?,?,?,?,?,?,?,?)',
            [$id, $taskId, $u['id'], $meta['original_name'], $meta['stored_name'], $meta['rel_path'],
             $meta['mime_type'], $meta['size_bytes'], $meta['kind'], $internal ? 1 : 0]
        );
    }
    Audit::log($id, $u['id'], 'attachment_added', null, null, null, count($saved) . ' קבצים נוספו');
    Response::json(['ok' => true, 'ids' => $saved], 201);
});

/** GET /api/attachments/{id}/file — permission checked, then handed to Apache. */
route('GET', ['attachments', '#', 'file'], function (int $id) {
    $u = Auth::require();
    $a = DB::one('SELECT * FROM ticket_attachments WHERE id = ?', [$id]);
    if (!$a) {
        throw new ApiError('הקובץ לא נמצא', 404);
    }
    $t = Tickets::findVisible($u, (int) $a['ticket_id']);
    if ((int) $a['is_internal'] === 1 && $u['role'] === 'customer') {
        throw new ApiError('אין הרשאה לקובץ זה', 403);
    }
    Uploads::serve($a);
});

/** DELETE /api/attachments/{id} */
route('DELETE', ['attachments', '#'], function (int $id) {
    $u = Auth::require();
    $a = DB::one('SELECT * FROM ticket_attachments WHERE id = ?', [$id]);
    if (!$a) {
        throw new ApiError('הקובץ לא נמצא', 404);
    }
    Tickets::findVisible($u, (int) $a['ticket_id']);
    if ($u['role'] !== 'admin' && (int) $a['uploaded_by'] !== (int) $u['id']) {
        throw new ApiError('ניתן למחוק רק קבצים שהעליתם', 403);
    }
    @unlink(Uploads::dir() . '/' . $a['rel_path'] . '/' . $a['stored_name']);
    DB::run('DELETE FROM ticket_attachments WHERE id = ?', [$id]);
    Audit::log((int) $a['ticket_id'], $u['id'], 'attachment_removed', null, $a['original_name'], null);
    Response::json(['ok' => true]);
});
