<?php

namespace App\Modules\Operation;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Session;

class PrinterSettingsController extends Controller
{
    private OperationModel $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new OperationModel();
    }

    /**
     * Show printer settings page.
     * Route: GET /app/couple/settings/printer
     *
     * @return void
     */
    public function index(): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        $printerConfig = $this->model->getPrinterConfig($workspaceId);

        if (!$printerConfig) {
            // Default configuration
            $printerConfig = [
                'label_width_mm' => 50,
                'label_height_mm' => 30,
            ];
        }

        $this->render('operation/settings_printer', [
            'title'   => 'Thermal Printer Configuration',
            'config'  => $printerConfig,
            'errors'  => Session::get('errors') ?? [],
            'success' => Session::get('success') ?? null
        ]);
        
        Session::set('errors', null);
        Session::set('success', null);
    }

    /**
     * Update printer settings.
     * Route: POST /app/couple/settings/printer
     *
     * @param Request $request
     * @return void
     */
    public function update(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        
        $width = (int) $request->post('label_width_mm');
        $height = (int) $request->post('label_height_mm');

        if ($width < 20 || $width > 200 || $height < 10 || $height > 200) {
            Session::set('errors', ['general' => 'Please provide valid dimensions (Width: 20-200mm, Height: 10-200mm).']);
            $this->redirect('/app/couple/settings/printer');
            return;
        }

        $success = $this->model->updatePrinterConfig($workspaceId, $width, $height);

        if ($success) {
            Session::set('success', 'Printer configuration saved successfully.');
        } else {
            Session::set('errors', ['general' => 'Failed to save printer configuration.']);
        }

        $this->redirect('/app/couple/settings/printer');
    }
}
