<?php

namespace App\Services;

use App\Models\CertificateTemplate;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class CertificateTemplateService
{
    public function store(UploadedFile $file, array $data): CertificateTemplate
    {
        $extension = strtolower($file->getClientOriginalExtension());
        $path = $file->store('certificate-templates', 'local');

        if (! empty($data['is_active'])) {
            CertificateTemplate::where('is_active', true)->update(['is_active' => false]);
        }

        return CertificateTemplate::create([
            'template_name' => $data['template_name'],
            'template_file' => $path,
            'file_type' => $extension,
            'page_size' => $data['page_size'] ?? 'A4',
            'orientation' => $data['orientation'] ?? 'landscape',
            'name_position_x' => $data['name_position_x'] ?? 0,
            'name_position_y' => $data['name_position_y'] ?? 350,
            'name_width' => $data['name_width'] ?? 600,
            'name_font' => $data['name_font'] ?? 'DejaVu Sans',
            'name_font_size' => $data['name_font_size'] ?? 30,
            'name_font_color' => $data['name_font_color'] ?? '#000000',
            'name_alignment' => $data['name_alignment'] ?? 'center',
            'name_text_transform' => $data['name_text_transform'] ?? 'uppercase',
            'is_active' => $data['is_active'] ?? false,
            'settings_json' => $data['settings_json'] ?? null,
        ]);
    }

    public function update(CertificateTemplate $template, array $data, ?UploadedFile $file = null): CertificateTemplate
    {
        if ($file) {
            if ($template->template_file && Storage::disk('local')->exists($template->template_file)) {
                Storage::disk('local')->delete($template->template_file);
            }
            $data['template_file'] = $file->store('certificate-templates', 'local');
            $data['file_type'] = strtolower($file->getClientOriginalExtension());
        }

        if (! empty($data['is_active'])) {
            CertificateTemplate::where('id', '!=', $template->id)
                ->where('is_active', true)
                ->update(['is_active' => false]);
        }

        $template->update($data);

        return $template->fresh();
    }

    public function activate(CertificateTemplate $template): void
    {
        CertificateTemplate::where('is_active', true)->update(['is_active' => false]);
        $template->update(['is_active' => true]);
    }

    public function getPreviewData(CertificateTemplate $template): array
    {
        return [
            'sample_name' => 'MUHAMMAD NUR HAKIM BIN ABDUL RAHMAN',
            'template' => $template,
        ];
    }
}
