<?php

namespace App\Mixins\Certificate;

use App\Models\Certificate;
use App\Models\CertificateTemplate;
use App\Models\Reward;
use App\Models\RewardAccounting;
use App\Models\DiplomaProgramCounter;

use \Barryvdh\DomPDF\Facade\Pdf;
use Intervention\Image\Facades\Image;

class MakeCertificate
{
    public function makeQuizCertificate($quizResult)
    {
        $template = CertificateTemplate::where('status', 'publish')
            ->where('type', 'quiz')
            ->first();

        if (!empty($template)) {
            $quiz = $quizResult->quiz;
            $user = $quizResult->user;

            $userCertificate = $this->saveQuizCertificate($user, $quiz, $quizResult);

            $body = $this->makeBody(
                $userCertificate,
                $user,
                $template->body,
                $quiz->webinar->title,
                $quizResult->user_grade,
                $quiz->webinar->teacher->full_name,
                $quiz->webinar->duration);

            /*$data = [
                'pageTitle' => trans('public.certificate'),
                'image' => public_path($template->image),
                'body' => $body,
            ];*/

            $img = $this->makeImage($template, $body);
            return $img->response('png');
        }

        abort(404);
    }

    public function makeImtmontessoriCertificate(Certificate $certificate)
    {
        //$img=Image::make(public_path('certificate.jpeg'));
        $Arabic = new \I18N_Arabic('Glyphs');
        $student=$certificate->student->full_name;
        $name = $Arabic->utf8Glyphs($student);
        $age = $certificate->age;
        $date = $certificate->date;
        // Use user's serial number instead of certificate serial number
        $s_no = $certificate->student->getSerialNumber();

        // Get diploma counter data if webinar_id exists
        $counter = null;
        if (!empty($certificate->webinar_id)) {
            $counter = DiplomaProgramCounter::where('webinar_id', $certificate->webinar_id)
                ->where('is_active', true)
                ->first();
        }





        if ($certificate->template){
                // Check if template file exists
                $templatePath = public_path($certificate->template);
                if (!file_exists($templatePath)) {
                    abort(404, 'Certificate template image not found: ' . $certificate->template);
                }

                // Approximate text width calculation

                $img=Image::make($templatePath);


            // Add other text elements
            //        $img->text($age, 810, 1050, function ($font) use ($fontPath) {
            //            $font->file($fontPath);
            //            $font->size(33);
            //            $font->color("#ff3132");
            //        });

            if ($certificate->dimensions_type === 'height'){
                // Fixed center position for name - always in same place
                $fontSize = 45; // Reduced font size
                $fontPath = public_path('assets/default/fonts/IBMPlexSansArabic-Medium.ttf');
                $imageWidth = $img->width();
                $imageHeight = $img->height();
                // Fixed center position - always in same place
                $xPosition = $imageWidth / 2;

                // Add centered text
                $img->text($name, $xPosition, 680, function ($font) use ($fontPath, $fontSize) {
                    $font->file($fontPath);
                    $font->size($fontSize);
                    $font->color("#cf9e5e");
                    $font->align('center');
                });
                $img->text($date, 200, 1380, function ($font) use ($fontPath) {
                    $font->file($fontPath);
                    $font->size(37);
                    $font->color("#000");
                });
                $img->text($s_no, 700, 1380, function ($font) use ($fontPath) {
                    $font->file($fontPath);
                    $font->size(30);
                    $font->color("#000");
                });

                // Add counter data if available (after contact information section)
                if (!empty($counter)) {
                    $counterY = 1650; // Position after contact information cards (below email, phone, address)
                    $counterFontSize = 25;
                    $counterText = $Arabic->utf8Glyphs(
                        "عدد الطلبات: " . number_format($counter->orders_count) . 
                        " | إجمالي المبيعات: " . number_format($counter->total_sales, 0) . 
                        " | عدد المنتجات: " . number_format($counter->products_count) . 
                        " | نسبة الإنجاز: " . number_format($counter->completion_rate) . "%"
                    );
                    $img->text($counterText, $xPosition, $counterY, function ($font) use ($fontPath, $counterFontSize) {
                        $font->file($fontPath);
                        $font->size($counterFontSize);
                        $font->color("#333");
                        $font->align('center');
                    });
                }
            }elseif ($certificate->dimensions_type === 'width1'){
                // Fixed center position for name - always in same place
                $fontSize = 85; // Reduced font size
                $fontPath = public_path('assets/default/fonts/GreatVibes-Regular.ttf');
                $arabicFontPath = public_path('assets/default/fonts/IBMPlexSansArabic-Medium.ttf');

                // Get the image width
                $imageWidth = $img->width();
                $imageHeight = $img->height();

                // Fixed center position - always in same place
                $xPosition = $imageWidth / 2;

                // Add centered text
                $img->text(ucfirst(strtolower($name)), $xPosition, 430, function ($font) use ($fontPath, $fontSize) {
                    $font->file($fontPath);
                    $font->size($fontSize);
                    $font->color("#bb944c");
                    $font->align('center');
                });
                $img->text($date, 1200, 870, function ($font) use ($fontPath) {
                    $font->file($fontPath);
                    $font->size(40);
                    $font->color("#000");
                });
                $img->text($s_no, 420, 890, function ($font) use ($fontPath) {
                    $font->file($fontPath);
                    $font->size(40);
                    $font->color("#000");
                });

                // Add counter data if available (after contact information section)
                if (!empty($counter)) {
                    $counterY = 1100; // Position after contact information cards (below email, phone, address)
                    $counterFontSize = 22;
                    $counterText = $Arabic->utf8Glyphs(
                        "عدد الطلبات: " . number_format($counter->orders_count) . 
                        " | إجمالي المبيعات: " . number_format($counter->total_sales, 0) . 
                        " | عدد المنتجات: " . number_format($counter->products_count) . 
                        " | نسبة الإنجاز: " . number_format($counter->completion_rate) . "%"
                    );
                    $img->text($counterText, $xPosition, $counterY, function ($font) use ($arabicFontPath, $counterFontSize) {
                        $font->file($arabicFontPath);
                        $font->size($counterFontSize);
                        $font->color("#333");
                        $font->align('center');
                    });
                }
            }elseif($certificate->dimensions_type === 'width2'){
                // Fixed center position for name - always in same place
                $fontSize = 85; // Reduced font size
                $fontPath = public_path('assets/default/fonts/GreatVibes-Regular.ttf');
                $arabicFontPath = public_path('assets/default/fonts/IBMPlexSansArabic-Medium.ttf');

                // Get the image width
                $imageWidth = $img->width();
                $imageHeight = $img->height();

                // Fixed center position - always in same place
                $xPosition = $imageWidth / 2;

                // Add centered text
                $img->text(ucfirst(strtolower($name)), $xPosition, 520, function ($font) use ($fontPath, $fontSize) {
                    $font->file($fontPath);
                    $font->size($fontSize);
                    $font->color("#bb944c");
                    $font->align('center');
                });
                $img->text($date, 450, 980, function ($font) use ($fontPath) {
                    $font->file($fontPath);
                    $font->size(40);
                    $font->color("#000");
                });
                $img->text($s_no, 1070, 980, function ($font) use ($fontPath) {
                    $font->file($fontPath);
                    $font->size(40);
                    $font->color("#000");
                });

                // Add counter data if available (after contact information section)
                if (!empty($counter)) {
                    $counterY = 1200; // Position after contact information cards (below email, phone, address)
                    $counterFontSize = 22;
                    $counterText = $Arabic->utf8Glyphs(
                        "عدد الطلبات: " . number_format($counter->orders_count) . 
                        " | إجمالي المبيعات: " . number_format($counter->total_sales, 0) . 
                        " | عدد المنتجات: " . number_format($counter->products_count) . 
                        " | نسبة الإنجاز: " . number_format($counter->completion_rate) . "%"
                    );
                    $img->text($counterText, $xPosition, $counterY, function ($font) use ($arabicFontPath, $counterFontSize) {
                        $font->file($arabicFontPath);
                        $font->size($counterFontSize);
                        $font->color("#333");
                        $font->align('center');
                    });
                }
            }

        }else{
            // Fixed center position for name - always in same place
            $fontSize = 45; // Reduced font size
            $fontPath = public_path('assets/default/fonts/IBMPlexSansArabic-Medium.ttf');

            if ($certificate->student_type == 'normal') {
                $certificatePath = public_path('certificate.jpeg');
                if (!file_exists($certificatePath)) {
                    abort(404, 'Certificate image not found: certificate.jpeg');
                }
                $img = Image::make($certificatePath);
            } else {
                $specialCertificatePath = public_path('special_certificate.jpeg');
                if (!file_exists($specialCertificatePath)) {
                    abort(404, 'Certificate image not found: special_certificate.jpeg');
                }
                $img=Image::make($specialCertificatePath);
            }

            // Get the image width
            $imageWidth = $img->width();
            $imageHeight = $img->height();

            // Fixed center position - always in same place
            $xPosition = $imageWidth / 2;

            // Add centered text
            $img->text($name, $xPosition, 680, function ($font) use ($fontPath, $fontSize) {
                $font->file($fontPath);
                $font->size($fontSize);
                $font->color("#cf9e5e");
                $font->align('center');
            });

            // Add other text elements
            $img->text($age, 810, 1050, function ($font) use ($fontPath) {
                $font->file($fontPath);
                $font->size(33);
                $font->color("#ff3132");
            });

            $img->text($date, 200, 1380, function ($font) use ($fontPath) {
                $font->file($fontPath);
                $font->size(37);
                $font->color("#000");
            });

            $img->text($s_no, 700, 1380, function ($font) use ($fontPath) {
                $font->file($fontPath);
                $font->size(30);
                $font->color("#000");
            });

            // Add counter data if available (after contact information section)
            if (!empty($counter)) {
                $counterY = 1650; // Position after contact information cards (below email, phone, address)
                $counterFontSize = 25;
                $counterText = $Arabic->utf8Glyphs(
                    "عدد الطلبات: " . number_format($counter->orders_count) . 
                    " | إجمالي المبيعات: " . number_format($counter->total_sales, 0) . 
                    " | عدد المنتجات: " . number_format($counter->products_count) . 
                    " | نسبة الإنجاز: " . number_format($counter->completion_rate) . "%"
                );
                $img->text($counterText, $xPosition, $counterY, function ($font) use ($fontPath, $counterFontSize) {
                    $font->file($fontPath);
                    $font->size($counterFontSize);
                    $font->color("#333");
                    $font->align('center');
                });
            }

        }




        return $img->response('png');
        //return $img;
        //return $img->response('png');


        abort(404);
    }



    private function saveQuizCertificate($user, $quiz, $quizResult)
    {
        $certificate = Certificate::where('quiz_id', $quiz->id)
            ->where('student_id', $user->id)
            ->where('quiz_result_id', $quizResult->id)
            ->first();

        $data = [
            'quiz_id' => $quiz->id,
            'student_id' => $user->id,
            'quiz_result_id' => $quizResult->id,
            'user_grade' => $quizResult->user_grade,
            'type' => 'quiz',
            'created_at' => time()
        ];

        if (!empty($certificate)) {
            $certificate->update($data);
        } else {
            $certificate = Certificate::create($data);

            $notifyOptions = [
                '[c.title]' => $quiz->webinar_title,
            ];
            sendNotification('new_certificate', $notifyOptions, $user->id);
        }

        return $certificate;
    }

    private function makeBody($userCertificate, $user, $body, $courseTitle = null, $userGrade = null, $teacherFullName = null, $duration = null)
    {
        $body = str_replace('[student]', $user->full_name, $body);
        $body = str_replace('[course]', $courseTitle, $body);
        $body = str_replace('[grade]', $userGrade, $body);
        $body = str_replace('[certificate_id]', $userCertificate->id, $body);
        $body = str_replace('[date]', dateTimeFormat($userCertificate->created_at, 'j M Y | H:i'), $body);
        $body = str_replace('[instructor_name]', $teacherFullName, $body);
        $body = str_replace('[duration]', $duration, $body);
        $body = str_replace('[user_serial_number]', $user->getSerialNumber(), $body);

        $userCertificateAdditional = $user->userMetas->where('name', 'certificate_additional')->first();
        $userCertificateAdditionalValue = !empty($userCertificateAdditional) ? $userCertificateAdditional->value : null;
        $body = str_replace('[user_certificate_additional]', $userCertificateAdditionalValue, $body);

        return $body;
    }

    private function makeImage($certificateTemplate, $body)
    {
        $imagePath = public_path($certificateTemplate->image);
        if (!file_exists($imagePath)) {
            abort(404, 'Certificate template image not found: ' . $certificateTemplate->image);
        }
        $img = Image::make($imagePath);


//        if ($certificateTemplate->rtl) {
        $Arabic = new \I18N_Arabic('Glyphs');
        $body = $Arabic->utf8Glyphs($body);
//        }

        $img->text($body, $certificateTemplate->position_x, $certificateTemplate->position_y, function ($font) use ($certificateTemplate) {
            $font->file(public_path('assets/default/fonts/IBMPlexSansArabic-Medium.ttf'));
            $font->size($certificateTemplate->font_size);
            $font->color($certificateTemplate->text_color);
            $font->align('center');
        });

        return $img;
    }

    public function makeCourseCertificate($certificate)
    {
        $template = CertificateTemplate::where('status', 'publish')
            ->where('type', 'course')
            ->first();

        $course = $certificate->webinar;

        if (!empty($template) and !empty($course)) {
            $user = $certificate->student;

            $userCertificate = $this->saveCourseCertificate($user, $course);


            $body = $this->makeBody(
                $userCertificate,
                $user,
                $template->body,
                $course->title,
                null,
                $course->teacher->full_name,
                $course->duration);

            /*$data = [
                'pageTitle' => trans('public.certificate'),
                'image' => public_path($template->image),
                'body' => $body,
            ];

            $pdf = Pdf::loadView('web.default.certificate_template.index', $data);
            return $pdf->setPaper('a4', 'landscape')
                ->setWarnings(false)
                ->stream('course_certificate.pdf');*/

            $img = $this->makeImage($template, $body);
            return $img->response('png');
        }

        abort(404);
    }

    public function saveCourseCertificate($user, $course)
    {
        $certificate = Certificate::where('webinar_id', $course->id)
            ->where('student_id', $user->id)
            ->first();

        $data = [
            'webinar_id' => $course->id,
            'student_id' => $user->id,
            'type' => 'course',
            'created_at' => time()
        ];

        if (!empty($certificate)) {
            $certificate->update($data);
        } else {
            $certificate = Certificate::create($data);

            $notifyOptions = [
                '[c.title]' => $course->title,
            ];
            sendNotification('new_certificate', $notifyOptions, $user->id);
        }

        return $certificate;
    }
}
