<?php

namespace App\Services;

use App\Models\LastCertificate;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

class CertificateGeneratorService
{
    /**
     * Generate a certificate for a user using the certificate generator package.
     *
     * @param User $user
     * @param Request $request
     * @return LastCertificate
     * @throws \Exception
     */
    public function generateCertificate(User $user, Request $request): LastCertificate
    {
        try {
            // Validate the request
            $validatedData = $request->validate([
                'template_name' => 'required|string|max:255',
                'certificate_data' => 'required|array',
                'image_data' => 'required|string', // Base64 encoded image data
            ]);

            // Ensure the certificates directory exists
            $certificatesDir = 'certificates';
            if (!Storage::disk('public')->exists($certificatesDir)) {
                Storage::disk('public')->makeDirectory($certificatesDir);
            }

            // Generate unique filename
            $filename = 'certificate_' . $user->id . '_' . time() . '_' . Str::random(10) . '.png';
            $filePath = $certificatesDir . '/' . $filename;

            // Decode and save the image
            $imageData = $validatedData['image_data'];
            if (strpos($imageData, 'data:image/png;base64,') === 0) {
                $imageData = substr($imageData, 22); // Remove the data URL prefix
            }

            $imageBinary = base64_decode($imageData);

            if ($imageBinary === false) {
                throw new \Exception('Invalid base64 image data');
            }

            // Save the image to storage
            Storage::disk('public')->put($filePath, $imageBinary);

            // Create the certificate record
            $certificate = LastCertificate::create([
                'user_id' => $user->id,
                'image_path' => $filePath,
                'template_name' => $validatedData['template_name'],
                'certificate_data' => $validatedData['certificate_data'],
                'generated_at' => now(),
            ]);

            return $certificate;

        } catch (\Exception $e) {
            \Log::error('Certificate generation failed: ' . $e->getMessage(), [
                'user_id' => $user->id,
                'request_data' => $request->all(),
            ]);

            throw new \Exception('Failed to generate certificate: ' . $e->getMessage());
        }
    }

    /**
     * Get user data for certificate generation.
     *
     * @param User $user
     * @return array
     */
    public function getUserDataForCertificate(User $user): array
    {
        return [
            'name' => $user->full_name ?? $user->name ?? 'N/A',
            'serial_number' => $user->getSerialNumber(),
            'email' => $user->email,
            'user_id' => $user->id,
        ];
    }

    /**
     * Get available certificate templates.
     *
     * @return array
     */
    public function getAvailableTemplates(): array
    {
        return [
            'default' => [
                'name' => 'Default Template',
                'description' => 'A simple, clean certificate template',
                'preview' => '/images/certificate-templates/default-preview.png',
            ],
            'modern' => [
                'name' => 'Modern Template',
                'description' => 'A modern, professional certificate template',
                'preview' => '/images/certificate-templates/modern-preview.png',
            ],
            'classic' => [
                'name' => 'Classic Template',
                'description' => 'A traditional, formal certificate template',
                'preview' => '/images/certificate-templates/classic-preview.png',
            ],
        ];
    }

    /**
     * Delete a certificate and its associated file.
     *
     * @param LastCertificate $certificate
     * @return bool
     */
    public function deleteCertificate(LastCertificate $certificate): bool
    {
        try {
            // Delete the file from storage
            if (Storage::disk('public')->exists($certificate->image_path)) {
                Storage::disk('public')->delete($certificate->image_path);
            }

            // Delete the database record
            return $certificate->delete();

        } catch (\Exception $e) {
            \Log::error('Certificate deletion failed: ' . $e->getMessage(), [
                'certificate_id' => $certificate->id,
            ]);

            return false;
        }
    }

    /**
     * Get certificate statistics.
     *
     * @return array
     */
    public function getCertificateStats(): array
    {
        return [
            'total_certificates' => LastCertificate::count(),
            'certificates_this_month' => LastCertificate::whereMonth('generated_at', now()->month)->count(),
            'certificates_this_week' => LastCertificate::whereBetween('generated_at', [
                now()->startOfWeek(),
                now()->endOfWeek()
            ])->count(),
            'most_used_template' => ($result = LastCertificate::selectRaw('template_name, COUNT(*) as count')
                ->groupBy('template_name')
                ->orderBy('count', 'desc')
                ->first()) ? $result->template_name : 'N/A',
        ];
    }
}
