<?php

/**
 * GET /api/documents
 * Customers see documents published to everyone plus those aimed at their own
 * organisation. Staff see the lot.
 */
route('GET', ['documents'], function () {
    $u      = Auth::require();
    $params = [];
    $where  = ['d.is_active = 1'];

    if ($u['role'] === 'customer') {
        $where[]  = '(d.customer_id IS NULL OR d.customer_id = ?)';
        $params[] = $u['customer_id'];
    }
    if (!empty($_GET['q'])) {
        $where[]  = '(d.title LIKE ? OR d.description LIKE ? OR d.original_name LIKE ?)';
        $like     = '%' . $_GET['q'] . '%';
        array_push($params, $like, $like, $like);
    }

    Response::json(DB::all(
        'SELECT d.id, d.title, d.description, d.category, d.original_name, d.mime_type,
                d.size_bytes, d.created_at, d.download_count, d.customer_id, d.product_id,
                c.name AS customer_name, p.name AS product_name
         FROM documents d
         LEFT JOIN customers c ON c.id = d.customer_id
         LEFT JOIN products  p ON p.id = d.product_id
         WHERE ' . implode(' AND ', $where) . '
         ORDER BY d.category IS NULL, d.category, d.created_at DESC',
        $params
    ));
});

/** GET /api/documents/{id}/file */
route('GET', ['documents', '#', 'file'], function (int $id) {
    $u = Auth::require();
    $d = DB::one('SELECT * FROM documents WHERE id = ? AND is_active = 1', [$id]);
    if (!$d) {
        throw new ApiError('המסמך לא נמצא', 404);
    }
    if ($u['role'] === 'customer'
        && $d['customer_id'] !== null
        && (int) $d['customer_id'] !== (int) $u['customer_id']) {
        throw new ApiError('אין הרשאה למסמך זה', 403);
    }
    DB::run('UPDATE documents SET download_count = download_count + 1 WHERE id = ?', [$id]);
    Uploads::serve($d);
});

/* ------------------------------------------------------------- management */

/** GET /api/admin/documents — the full list, including hidden ones. */
route('GET', ['admin', 'documents'], function () {
    Auth::require('support', 'admin');
    Response::json(DB::all(
        'SELECT d.*, c.name AS customer_name, p.name AS product_name, u.full_name AS uploaded_by_name
         FROM documents d
         LEFT JOIN customers c ON c.id = d.customer_id
         LEFT JOIN products  p ON p.id = d.product_id
         JOIN users u ON u.id = d.uploaded_by
         ORDER BY d.created_at DESC'
    ));
});

/** POST /api/admin/documents — multipart: file + title, description, category… */
route('POST', ['admin', 'documents'], function () {
    $u = Auth::require('support', 'admin');
    Uploads::assertRequestFits();

    $files = Uploads::normalise('file');
    if (!$files) {
        throw new ApiError('לא התקבל קובץ מהדפדפן. אם מדובר בקובץ גדול, ייתכן שהוא חורג ממגבלת השרת.', 400);
    }
    $title = trim((string) ($_POST['title'] ?? ''));
    if ($title === '') {
        $title = pathinfo((string) $files[0]['name'], PATHINFO_FILENAME);
    }

    $meta = Uploads::storeDocument($files[0]);
    $id = DB::insert(
        'INSERT INTO documents
         (title, description, category, customer_id, product_id, original_name,
          stored_name, rel_path, mime_type, size_bytes, uploaded_by)
         VALUES (?,?,?,?,?,?,?,?,?,?,?)',
        [
            mb_substr($title, 0, 200),
            mb_substr(trim((string) ($_POST['description'] ?? '')), 0, 500) ?: null,
            mb_substr(trim((string) ($_POST['category'] ?? '')), 0, 60) ?: null,
            !empty($_POST['customer_id']) ? (int) $_POST['customer_id'] : null,
            !empty($_POST['product_id'])  ? (int) $_POST['product_id']  : null,
            $meta['original_name'], $meta['stored_name'], $meta['rel_path'],
            $meta['mime_type'], $meta['size_bytes'], $u['id'],
        ]
    );
    Response::json(['id' => $id], 201);
});

/** PATCH /api/admin/documents/{id} — metadata only; the file itself is fixed. */
route('PATCH', ['admin', 'documents', '#'], function (int $id) {
    Auth::require('support', 'admin');
    $b = Response::body();
    if (!DB::value('SELECT id FROM documents WHERE id = ?', [$id])) {
        throw new ApiError('המסמך לא נמצא', 404);
    }
    DB::run(
        'UPDATE documents SET title = ?, description = ?, category = ?,
         customer_id = ?, product_id = ?, is_active = ? WHERE id = ?',
        [
            mb_substr(trim((string) ($b['title'] ?? '')), 0, 200),
            mb_substr(trim((string) ($b['description'] ?? '')), 0, 500) ?: null,
            mb_substr(trim((string) ($b['category'] ?? '')), 0, 60) ?: null,
            !empty($b['customer_id']) ? (int) $b['customer_id'] : null,
            !empty($b['product_id'])  ? (int) $b['product_id']  : null,
            (int) (bool) ($b['is_active'] ?? 1), $id,
        ]
    );
    Response::json(['ok' => true]);
});

/** DELETE /api/admin/documents/{id} */
route('DELETE', ['admin', 'documents', '#'], function (int $id) {
    Auth::require('support', 'admin');
    $d = DB::one('SELECT * FROM documents WHERE id = ?', [$id]);
    if (!$d) {
        throw new ApiError('המסמך לא נמצא', 404);
    }
    @unlink(Uploads::dir() . '/' . $d['rel_path'] . '/' . $d['stored_name']);
    DB::run('DELETE FROM documents WHERE id = ?', [$id]);
    Response::json(['ok' => true]);
});
