<?php

namespace App\Http\Controllers;

use App\Models\Gallery;
use App\Services\PrinterService;
use App\Settings\GeneralSettings;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PrintController extends Controller
{
    public function __construct(private GeneralSettings $settings) {}

    public function printImage(Request $request, PrinterService $printerService)
    {
        $request->validate([
            'image_path' => 'required|string',
            'quantity' => 'required|integer|min:1',
            'gallery' => 'required|string|exists:galleries,slug',
        ]);

        $gallery = Gallery::where('slug', $request->string('gallery'))->firstOrFail();

        if ($gallery && ! $gallery->allow_print) {
            return response()->json(['error' => 'Printing is disabled for this gallery.'], 403);
        }

        $imagePath = public_path(str_replace(url('/'), '', $request->input('image_path')));

        if (! str_contains($imagePath, DIRECTORY_SEPARATOR.trim($gallery->images_path, '/').DIRECTORY_SEPARATOR)) {
            Log::warning('PrintController: Image path does not belong to gallery.', [
                'gallery' => $gallery->slug,
                'image_path' => $imagePath,
            ]);

            return response()->json(['error' => 'Image file not found.'], 404);
        }
        $quantity = $request->input('quantity');

        $printerName = $this->settings->selected_printer === '__custom__'
            ? $this->settings->custom_printer_address
            : $this->settings->selected_printer;

        if (! $printerName) {
            Log::error('PrintController: Default printer name not found in settings.');

            return response()->json(['error' => 'Default printer not configured.'], 500);
        }

        if (! file_exists($imagePath)) {
            Log::error("PrintController: Image file not found at {$imagePath}");

            return response()->json(['error' => 'Image file not found.'], 404);
        }

        $printSuccess = $printerService->printImage($imagePath, $printerName, $quantity);

        if ($printSuccess) {
            Log::info("PrintController: Successfully sent print command for {$imagePath} (x{$quantity}) to {$printerName}");

            return response()->json(['message' => 'Print command sent successfully.']);
        } else {
            Log::error("PrintController: Failed to send print command for {$imagePath} (x{$quantity}) to {$printerName}");

            return response()->json(['error' => 'Failed to send print command.'], 500);
        }
    }
}
