<?php

namespace App\Http\Controllers\Api\Reports;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Reports\SlipLogListRequest;
use App\Http\Requests\Reports\SlipPreviewRequest;
use App\Http\Requests\Reports\SlipPrintRequest;
use App\Http\Requests\Reports\SlipReprintRequest;
use App\Http\Resources\Reports\LateSlipLogResource;
use App\Services\Reports\SlipPrinterService;
use Illuminate\Http\JsonResponse;

class SlipPrinterController extends BaseApiController
{
    public function __construct(private SlipPrinterService $service)
    {
        parent::__construct();
    }

    public function print(SlipPrintRequest $request)
    {
        $userId = (int) (auth()->id() ?? 0);
        $result = $this->service->print($request->validated(), $userId);

        if (!$result['ok']) {
            return response()->json(['ok' => false, 'message' => $result['message'] ?? 'Print failed.'], 422);
        }

        return response($result['pdf'], 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'inline; filename="' . $result['filename'] . '"',
        ]);
    }

    public function preview(SlipPreviewRequest $request): JsonResponse
    {
        $userId = (int) (auth()->id() ?? 0);
        $result = $this->service->preview($request->validated(), $userId);

        return response()->json([
            'ok' => true,
            'text' => $result['text'],
            'width' => $result['width'],
        ]);
    }

    public function logs(SlipLogListRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $rows = $this->service->logs($payload['school_year'] ?? null, $payload['semester'] ?? null);

        return response()->json([
            'ok' => true,
            'logs' => LateSlipLogResource::collection($rows),
        ]);
    }

    public function reprint(SlipReprintRequest $request)
    {
        $userId = (int) (auth()->id() ?? 0);
        $result = $this->service->reprint((int) $request->validated()['id'], $userId);

        if (!$result['ok']) {
            return response()->json(['ok' => false, 'message' => $result['message'] ?? 'Slip not found.'], 404);
        }

        return response($result['pdf'], 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'inline; filename="' . $result['filename'] . '"',
        ]);
    }
}
