<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Rapport;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

class RapportPdfController extends Controller
{
    public function generate($id)
    {
        try {
            Log::info('PDF Generation: Start', ['rapport_id' => $id]);

            // =========================
            // FETCH RAPPORT
            // =========================
            Log::info('PDF Generation: Fetching rapport from database', ['rapport_id' => $id]);
            
            $rapport = Rapport::with([
                'inspecteur.discipline',
                'inspecteur.pole',
                'professeur.cycle',
                'professeur.statut',
                'etablissement.commune.moughataa.region.pole',
                'etablissement.cycle',
                'etablissement.infrastructures.typeInfrastructure',
                'etablissement.structurePedagogiques.niveau.cycle',
                'etablissement.infrastructures.annee'
            ])->findOrFail($id);

            Log::info('PDF Generation: Rapport fetched successfully', ['rapport_id' => $id]);

            // =========================
            // DETERMINE LANGUAGE
            // =========================
            // Priority: 1. Discipline language (automatic), 2. Inspector language, 3. Default French
            if ($rapport->inspecteur->discipline->langue && in_array($rapport->inspecteur->discipline->langue, ['ar', 'fr', 'en'])) {
                $detectedLangue = $rapport->inspecteur->discipline->langue;
                Log::info('PDF Generation: Using discipline language', ['langue' => $detectedLangue]);
            } elseif ($rapport->inspecteur->langue && in_array($rapport->inspecteur->langue, ['ar', 'fr', 'en'])) {
                $detectedLangue = $rapport->inspecteur->langue;
                Log::info('PDF Generation: Using inspector language', ['langue' => $detectedLangue]);
            } else {
                $detectedLangue = 'fr'; // Default to French
                Log::info('PDF Generation: Using default language', ['langue' => $detectedLangue]);
            }

            $isArabic = $detectedLangue === 'ar';
            $isEnglish = $detectedLangue === 'en';

            // =========================
            // FILE PATHS
            // =========================
            // Select the appropriate template based on language
            if ($isArabic) {
                $input = storage_path('app/reports/rapport_ar.jasper');
            } elseif ($isEnglish) {
                $input = storage_path('app/reports/rapport_en.jasper');
            } else {
                $input = storage_path('app/reports/rapport_fr.jasper');
            }

            $outputDir = storage_path('app/public/rapports');

            Log::info('PDF Generation: File paths', [
                'input' => $input,
                'output_dir' => $outputDir,
                'input_exists' => file_exists($input),
                'detected_langue' => $detectedLangue,
            ]);

            if (!file_exists($input)) {
                Log::error('PDF Generation: Jasper file not found', ['input' => $input]);
                return response()->json([
                    'success' => false,
                    'error' => 'Jasper file not found',
                    'input' => $input,
                    'langue' => $detectedLangue,
                ], 500);
            }

            if (!file_exists($outputDir)) {
                Log::info('PDF Generation: Creating output directory', ['output_dir' => $outputDir]);
                mkdir($outputDir, 0777, true);
            }

            $output = $outputDir . "/rapport_" . $rapport->id . "_" . $detectedLangue;
            $pdfFile = $output . ".pdf";

            // Chemin absolu vers le logo
            $logoPath = storage_path('app/reports/logo.png');
            $fontPath = storage_path('app/reports/Amiri-Regular.ttf');

            Log::info('PDF Generation: Asset paths', [
                'logo_path' => $logoPath,
                'logo_exists' => file_exists($logoPath),
                'font_path' => $fontPath,
                'font_exists' => file_exists($fontPath),
            ]);

            // =========================
            // DYNAMIC LABELS (AR / FR / EN)
            // =========================
            if ($isArabic) {
                $labels = [
                    'txt_titre'      => "تقرير تفتيش تربوي",
                    'txt_pays'       => "الجمهورية الإسلامية الموريتانية",
                    'txt_ministere'  => "المفتشية العامة للتعليم",
                    'txt_inspecteur' => "1. المفتش",
                    'txt_discipline' => "المادة: ",
                    'txt_nom_insp'   => "المفتش: ",
                    'txt_date'       => "التاريخ: ",
                    'txt_professeur' => "2. الأستاذ",
                    'txt_nom_prof'   => "الأستاذ: ",
                    'txt_etab'       => "المؤسسة: ",
                    'txt_classe'     => "الفصل: ",
                    'txt_effectif'   => "عدد التلاميذ: ",
                    'txt_presents'   => "الحضور: ",
                    'txt_horaire'    => "التوقيت: ",
                    'txt_lecon'      => "3. الدرس",
                    'txt_titre_lec'  => "العنوان: ",
                    'txt_appreciation'=> "4. ملاحظات",
                    'txt_note'       => "المعدل: ",
                ];
            } elseif ($isEnglish) {
                $labels = [
                    'txt_titre'      => "Educational Inspection Report",
                    'txt_pays'       => "Islamic Republic of Mauritania",
                    'txt_ministere'  => "General Inspectorate of Education",
                    'txt_inspecteur' => "1. Inspector",
                    'txt_discipline' => "Discipline: ",
                    'txt_nom_insp'   => "Inspector: ",
                    'txt_date'       => "Date: ",
                    'txt_professeur' => "2. Teacher",
                    'txt_nom_prof'   => "Teacher: ",
                    'txt_etab'       => "Establishment: ",
                    'txt_classe'     => "Class: ",
                    'txt_effectif'   => "Number of students: ",
                    'txt_presents'   => "Present: ",
                    'txt_horaire'    => "Time: ",
                    'txt_lecon'      => "3. Lesson",
                    'txt_titre_lec'  => "Title: ",
                    'txt_appreciation'=> "4. Appreciation",
                    'txt_note'       => "Grade: ",
                ];
            } else {
                $labels = [
                    'txt_titre'      => "Rapport d'inspection pédagogique",
                    'txt_pays'       => "République Islamique de Mauritanie",
                    'txt_ministere'  => "Inspection Générale de l'Éducation",
                    'txt_inspecteur' => "1. Inspecteur",
                    'txt_discipline' => "Discipline : ",
                    'txt_nom_insp'   => "Inspecteur : ",
                    'txt_date'       => "Date : ",
                    'txt_professeur' => "2. Professeur",
                    'txt_nom_prof'   => "Professeur : ",
                    'txt_etab'       => "Établissement : ",
                    'txt_classe'     => "Classe : ",
                    'txt_effectif'   => "Effectif : ",
                    'txt_presents'   => "Présents : ",
                    'txt_horaire'    => "Horaire : ",
                    'txt_lecon'      => "3. Leçon",
                    'txt_titre_lec'  => "Titre : ",
                    'txt_appreciation'=> "4. Appréciation",
                    'txt_note'       => "Note : ",
                ];
            }

            // =========================
            // INFRASTRUCTURE DATA
            // =========================
            $infrastructureData = [];
            foreach ($rapport->etablissement->infrastructures as $infra) {
                $infrastructureData[$infra->typeInfrastructure->libelle ?? ''] = [
                    'nombre_movais' => $infra->nombre_movais ?? 0,
                    'nombre_moyens' => $infra->nombre_moyens ?? 0,
                ];
            }

            // =========================
            // STRUCTURE PÉDAGOGIQUE DATA
            // =========================
            $structureData = [];
            foreach ($rapport->etablissement->structurePedagogiques as $struct) {
                $structureData[] = [
                    'niveau' => $struct->niveau->libelle ?? '',
                    'nombre_section' => $struct->nombre_section ?? 0,
                    'nombre_eleves' => $struct->nombre_eleves ?? 0,
                    'nombre_filles' => $struct->nombre_filles ?? 0,
                ];
            }

            // =========================
            // SAFE VALUES
            // =========================
            $params = [
                'is_arabic'             => $isArabic ? 'true' : 'false',
                'logo_path'             => file_exists($logoPath) ? $logoPath : '',

                'date_inspection'       => $rapport->date_inspection ? (string)$rapport->date_inspection : '',
                'classe_visitee'        => (string)($rapport->classe_visitee ?? ''),
                'titre_lecon'           => (string)($rapport->titre_lecon ?? ''),
                'deroulement'           => (string)($rapport->deroulement ?? ''),
                'appreciation_generale' => (string)($rapport->appreciation_generale ?? ''),
                'note'                  => (string)($rapport->note ?? ''),
                'nombre_eleve'          => (string)($rapport->nombre_eleve ?? ''),
                'present'               => (string)($rapport->present ?? ''),
                'horaire'               => (string)($rapport->horaire ?? ''),

                // Données dynamiques selon la langue
                'inspecteur_nom'        => $isArabic ? (string)($rapport->inspecteur->nomar ?? '') : (string)($rapport->inspecteur->nomfr ?? ''),
                'discipline'            => (string)($rapport->inspecteur->discipline->libelle ?? ''),
                'professeur_nom'        => $isArabic ? (string)($rapport->professeur->nomar ?? '') : (string)($rapport->professeur->nomfr ?? ''),
                'etablissement'         => $isArabic ? (string)($rapport->etablissement->libellear ?? '') : (string)($rapport->etablissement->libellefr ?? ''),
            ];

            // Fusionner les textes traduits avec les paramètres de données
            $finalParams = array_merge($params, $labels);

            // =========================
            // COMMAND EXECUTION
            // =========================
            $jasper = env('JASPERSTARTER_BIN', '/usr/bin/jasperstarter');
            $arguments = [$jasper, 'process', $input, '-o', $output, '-f', 'pdf'];

            if (!empty($finalParams)) {
                $arguments[] = '-P';
                foreach ($finalParams as $key => $value) {
                    $cleanValue = str_replace(['"', "'", '='], ' ', $value);
                    $arguments[] = $key . '=' . $cleanValue;
                }
            }

            Log::info('PDF Generation: Executing JasperStarter', [
                'jasper_bin' => $jasper,
                'input' => $input,
                'output' => $output,
                'params_count' => count($finalParams),
            ]);

            $process = new Process($arguments);
            $process->run();

            if (!$process->isSuccessful()) {
                Log::error('PDF Generation: JasperStarter failed', [
                    'exit_code' => $process->getExitCode(),
                    'error_output' => $process->getErrorOutput(),
                    'output' => $process->getOutput(),
                ]);

                return response()->json([
                    'success' => false,
                    'error' => 'JasperStarter execution failed',
                    'exit_code' => $process->getExitCode(),
                    'error_output' => $process->getErrorOutput(),
                    'output' => $process->getOutput(),
                ], 500);
            }

            Log::info('PDF Generation: JasperStarter completed successfully');

            if (!file_exists($pdfFile)) {
                Log::error('PDF Generation: PDF file not created', ['pdf_file' => $pdfFile]);
                return response()->json([
                    'success' => false,
                    'error' => 'PDF file not created',
                    'pdf_file' => $pdfFile,
                    'error_output' => $process->getErrorOutput(),
                ], 500);
            }

            Log::info('PDF Generation: PDF file created successfully', ['pdf_file' => $pdfFile]);

            // Generate the public URL for the PDF using the request's scheme and host
            // This ensures the URL uses the same host as the API request (e.g., 10.0.2.2 for Android emulator)
            $request = request();
            $scheme = $request->getScheme();
            $host = $request->getHost();
            $port = $request->getPort();
            
            // Construct the URL dynamically based on the request
            $pdfUrl = $scheme . '://' . $host;
            if ($port && $port != 80 && $port != 443) {
                $pdfUrl .= ':' . $port;
            }
            $pdfUrl .= '/storage/rapports/' . basename($pdfFile);

            Log::info('PDF Generation: Returning JSON response with URL', [
                'pdf_url' => $pdfUrl,
                'pdf_file' => $pdfFile,
                'scheme' => $scheme,
                'host' => $host,
                'port' => $port,
            ]);

            return response()->json([
                'success' => true,
                'pdf_url' => $pdfUrl,
                'pdf_filename' => basename($pdfFile),
            ]);

        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            Log::error('PDF Generation: Rapport not found', [
                'rapport_id' => $id,
                'exception' => $e->getMessage(),
            ]);
            return response()->json([
                'success' => false,
                'error' => 'Rapport not found',
                'rapport_id' => $id,
                'exception' => $e->getMessage(),
            ], 404);

        } catch (\Exception $e) {
            Log::error('PDF Generation: Unexpected error', [
                'rapport_id' => $id,
                'exception' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            return response()->json([
                'success' => false,
                'error' => 'Unexpected error during PDF generation',
                'exception' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ], 500);
        }
    }
}
