<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PdfSetting;
use App\Models\Setting;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;

class PdfSettingsController extends Controller
{
    /**
     * Display the PDF settings page.
     */
    public function index(): Response
    {
        $pdfSettings = PdfSetting::all()->keyBy('document_type');
        
        // Ensure all document types have settings (create defaults if missing)
        $documentTypes = PdfSetting::getDocumentTypes();
        foreach ($documentTypes as $type => $label) {
            if (!$pdfSettings->has($type)) {
                $pdfSettings[$type] = PdfSetting::create(
                    PdfSetting::getDefaultSettings($type)
                );
            }
        }

        return Inertia::render('Admin/Settings/PdfSettings', [
            'pdfSettings' => $pdfSettings,
            'documentTypes' => $documentTypes,
            'globalSettings' => [
                'logo' => Setting::get('logo'),
                'site_name' => Setting::get('site_name', 'CoachPro'),
            ],
        ]);
    }

    /**
     * Update settings for a specific document type.
     */
    public function update(Request $request, string $documentType): RedirectResponse
    {
        // Validate document type
        $validTypes = array_keys(PdfSetting::getDocumentTypes());
        if (!in_array($documentType, $validTypes)) {
            return back()->with('error', 'Tipo de documento no válido.');
        }

        $validated = $request->validate([
            'primary_color' => 'required|string|regex:/^#[0-9A-Fa-f]{6}$/',
            'secondary_color' => 'required|string|regex:/^#[0-9A-Fa-f]{6}$/',
            'accent_color' => 'required|string|regex:/^#[0-9A-Fa-f]{6}$/',
            'header_title' => 'nullable|string|max:255',
            'header_subtitle' => 'nullable|string|max:500',
            'show_logo' => 'boolean',
            'show_date' => 'boolean',
            'show_page_numbers' => 'boolean',
            'footer_text' => 'nullable|string|max:500',
            'footer_note' => 'nullable|string|max:500',
            'footer_website' => 'nullable|string|max:255',
            'footer_email' => 'nullable|email|max:255',
            'footer_phone' => 'nullable|string|max:50',
            'show_coach_info' => 'boolean',
            'show_coach_photo' => 'boolean',
            'show_coach_credentials' => 'boolean',
            'show_coach_contact' => 'boolean',
            'paper_size' => 'required|string|in:a4,letter',
            'orientation' => 'required|string|in:portrait,landscape',
            'margin_top' => 'required|integer|min:5|max:50',
            'margin_bottom' => 'required|integer|min:5|max:50',
            'margin_left' => 'required|integer|min:5|max:50',
            'margin_right' => 'required|integer|min:5|max:50',
            'font_family' => 'required|string|max:100',
            'font_size_base' => 'required|integer|min:8|max:16',
            'font_size_header' => 'required|integer|min:16|max:36',
            'custom_css' => 'nullable|string|max:5000',
            'watermark_text' => 'nullable|string|max:100',
            'watermark_enabled' => 'boolean',
            'is_active' => 'boolean',
        ]);

        $setting = PdfSetting::updateOrCreate(
            ['document_type' => $documentType],
            $validated
        );

        return back()->with('success', 'Configuración de PDF actualizada para ' . PdfSetting::getDocumentTypes()[$documentType] . '.');
    }

    /**
     * Upload logo for a specific document type.
     */
    public function uploadLogo(Request $request, string $documentType): RedirectResponse
    {
        // Validate document type
        $validTypes = array_keys(PdfSetting::getDocumentTypes());
        if (!in_array($documentType, $validTypes)) {
            return back()->with('error', 'Tipo de documento no válido.');
        }

        $request->validate([
            'logo' => 'required|image|mimes:png,jpg,jpeg|max:5120',
        ]);

        $setting = PdfSetting::firstOrCreate(
            ['document_type' => $documentType],
            PdfSetting::getDefaultSettings($documentType)
        );

        // Delete old logo if exists
        if ($setting->logo && Storage::disk('public')->exists($setting->logo)) {
            Storage::disk('public')->delete($setting->logo);
        }

        $path = $request->file('logo')->store('pdf-logos', 'public');
        $setting->update(['logo' => $path]);

        return back()->with('success', 'Logo de PDF actualizado.');
    }

    /**
     * Remove logo for a specific document type.
     */
    public function removeLogo(string $documentType): RedirectResponse
    {
        $setting = PdfSetting::where('document_type', $documentType)->first();

        if ($setting && $setting->logo) {
            if (Storage::disk('public')->exists($setting->logo)) {
                Storage::disk('public')->delete($setting->logo);
            }
            $setting->update(['logo' => null]);
        }

        return back()->with('success', 'Logo de PDF eliminado.');
    }

    /**
     * Reset settings to defaults for a specific document type.
     */
    public function reset(string $documentType): RedirectResponse
    {
        // Validate document type
        $validTypes = array_keys(PdfSetting::getDocumentTypes());
        if (!in_array($documentType, $validTypes)) {
            return back()->with('error', 'Tipo de documento no válido.');
        }

        $setting = PdfSetting::where('document_type', $documentType)->first();
        
        if ($setting) {
            // Keep logo but reset other settings
            $logo = $setting->logo;
            $defaults = PdfSetting::getDefaultSettings($documentType);
            $defaults['logo'] = $logo;
            $setting->update($defaults);
        }

        return back()->with('success', 'Configuración restablecida a valores predeterminados.');
    }

    /**
     * Preview PDF with current settings.
     */
    public function preview(string $documentType)
    {
        // Validate document type
        $validTypes = array_keys(PdfSetting::getDocumentTypes());
        if (!in_array($documentType, $validTypes)) {
            return response()->json(['error' => 'Tipo de documento no válido.'], 400);
        }

        $settings = PdfSetting::getSettingsForType($documentType);

        // Return preview data or generate sample PDF
        return response()->json([
            'settings' => $settings,
            'preview_url' => route('admin.pdf-settings.sample', $documentType),
        ]);
    }

    /**
     * Generate sample PDF for preview.
     */
    public function sample(string $documentType)
    {
        $settings = PdfSetting::getSettingsForType($documentType);
        
        // Generate sample PDF based on document type
        $view = match($documentType) {
            PdfSetting::TYPE_WORKOUT => 'pdf.sample-workout',
            PdfSetting::TYPE_MEAL_PLAN => 'pdf.sample-meal-plan',
            PdfSetting::TYPE_INVOICE => 'pdf.sample-invoice',
            default => 'pdf.sample-generic',
        };

        // For now, return settings info - actual preview would need sample data
        return response()->json([
            'type' => $documentType,
            'settings' => $settings,
        ]);
    }

    /**
     * Copy settings from one document type to another.
     */
    public function copy(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'source_type' => 'required|string',
            'target_type' => 'required|string',
        ]);

        $validTypes = array_keys(PdfSetting::getDocumentTypes());
        if (!in_array($validated['source_type'], $validTypes) || 
            !in_array($validated['target_type'], $validTypes)) {
            return back()->with('error', 'Tipos de documento no válidos.');
        }

        $source = PdfSetting::where('document_type', $validated['source_type'])->first();
        
        if (!$source) {
            return back()->with('error', 'Configuración de origen no encontrada.');
        }

        $target = PdfSetting::where('document_type', $validated['target_type'])->first();
        
        $data = $source->toArray();
        unset($data['id'], $data['document_type'], $data['created_at'], $data['updated_at']);
        
        // Keep target's logo
        if ($target) {
            $data['logo'] = $target->logo;
            $target->update($data);
        } else {
            $data['document_type'] = $validated['target_type'];
            PdfSetting::create($data);
        }

        return back()->with('success', 'Configuración copiada exitosamente.');
    }
}
