<?php

namespace App\Http\Controllers\Certificate;

use App\Constants\Settings;
use App\Http\Controllers\Controller;
use App\Models\Certificate\Certificate;
use App\Models\Certificate\CertificateTemplate;
use App\Models\Student\StudentInfo;
use App\Services\StudentInfoService;
use Illuminate\Http\Request;

class CertificateController extends Controller
{
    protected $studentInfoService;

    public function __construct(StudentInfoService $studentInfoService)
    {
        $this->studentInfoService = $studentInfoService;
    }

    public function index()
    {
        $studentCertificates = Certificate::with(['student', 'assignedBy', 'certificateTemplate'])->get();
        return view('pages.certificate.student-certificate.index', compact('studentCertificates'));
    }

    public function create(Request $request)
    {
        $students = $this->studentInfoService->getStudents($request->query());
        $data['students'] = $students;
        $data['certificateTemplates'] = CertificateTemplate::pluck('title', 'id');
        $data['student_name'] = $this->studentInfoService->getStudentNameWithID($request->student_id_no, $students);
        $data['studentCertificate'] = [];
        $data['student'] = isset($students) ? $students[0] : '';
        $template = CertificateTemplate::find($request->certificate_template_id);
        $data['template'] = $template;
        $data['studentCertificate'] = $this->prepareCertificateBody(htmlspecialchars_decode($template?->body), $data['student']);
       
        return view('pages.certificate.student-certificate.create', $data);
    }

    protected function prepareCertificateBody($body, $student)
    {
        $school_logo = asset(get_setting_value(Settings::SCHOOL_LOGO));
        $school_logo_url = "<img src='$school_logo' alt='School Logo'/>";
    
        // Replace placeholders with actual student data
        $replacements = [
            '[School_Logo]' => $school_logo_url, 
            '[School_Name]' => get_setting_value(Settings::SCHOOL_NAME),
            '[Branch_Name]' => 'Your Branch Name', // This can be dynamic if needed
            '[Student_Name]' => $student->first_name . ' ' . $student->last_name, // Fixed typo (should use `last_name`)
            '[Student_Class]' => $student->studentClass?->class_name,
            '[Student_Section]' => $student->section?->section_name,
            '[Student_Shift]' => $student->shift?->shift_name,
            '[Student_Roll]' => $student->class_roll,
            '[Last_Exam_Result]' => '4.20', // Replace with actual result if needed
            '[Principal_Signature]' => '<img src="path_to_signature" alt="Principal Signature"/>'
        ];
    
        // Use regex to replace placeholders even with extra spaces or HTML tags
        foreach ($replacements as $placeholder => $replacement) {
            $body = preg_replace_callback('/'.preg_quote($placeholder, '/').'/', function ($matches) use ($replacement) {
                return $replacement;
            }, $body);
        }
    
        return $body;
    }
    

    public function store(Request $request)
    {
        // $request->validate([
        //     'title' => 'required|string|max:255',
        //     'body' => 'required|string',
        //     'status' => 'in:active,inactive',
        // ]);

        Certificate::create([
            "branch_id" => auth()->user()->branch_id,
            "student_id" => $request->student_id,
            "class_id" => $request->class_id,
            "shift_id" => $request->shift_id,
            "certificate_template_id" => $request->certificate_template_id,
            "assigned_by" => auth()->user()->id,
            "assigned_at" => date('Y-m-d'),
        ]);

        return redirect()->route('student-certificate.index')->with('success', 'Template created successfully.');
    }

    public function show(Certificate $certificate)
    {
        $data['template'] = CertificateTemplate::find($certificate->certificate_template_id);
        $data['certificate'] = $certificate;
        $data['student '] = StudentInfo::where('id', $certificate->student_id)->first();
        $data['studentCertificate'] = $this->prepareCertificateBody(htmlspecialchars_decode($data['template']?->body), $data['student ']);
        return view('pages.certificate.student-certificate.show', $data);
    }


    public function edit($id)
    {
        $certificate = Certificate::findOrFail($id);
        return view('pages.certificate.student-certificate.edit', compact('certificate'));
    }

    public function update(Request $request, $id)
    {
        // Validate the request data
        $request->validate([
            'title' => 'required|string|max:255',
            'body' => 'required|string',
            'background_image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'padding_x' => 'required|integer|min:0',
            'padding_y' => 'required|integer|min:0',
            'status' => 'required|in:active,inactive',
        ]);


        // Redirect back with a success message
        return redirect()->route('student-certificate.index')->with('success', 'Certificate template updated successfully.');
    }

    public function destroy(Certificate $certificate)
    {
        $certificate->delete();
        return redirect()->route('certificate_templates.index')->with('success', 'Template deleted successfully.');
    }
}
