<?php

namespace model\service;

class UtilService
{

    private $uploadDir;
    private $maxFileSize = 5 * 1024 * 1024; // 5MB

    private $allowedExtensions = [
        'pdf' => ['application/pdf'],
        'jpg' => ['image/jpeg', 'image/pjpeg'],
        'jpeg' => ['image/jpeg', 'image/pjpeg'],
        'png' => ['image/png'],
        'doc' => ['application/msword'],
        'docx' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document']
    ];

    public function __construct()
    {
        $this->uploadDir = dirname(__DIR__, 2) . '/concours/';
    }

    /**
     * Upload multiple documents for a student
     */
    public function uploadDocuments($data, $files)
    {
        $fileFields = ['cv', 'diplome', 'releves_notes', 'demande_maniscrite', 'cin_recto', 'cin_verso', 'photo'];

        try {
            $concoursId = $data['concours_id'] ?? null;
            $cin = $data['cin'] ?? null;
            $candidatId = $data['candidat_id'] ?? null;

            if (!$concoursId || !$cin) {
                return ['success' => false, 'message' => 'Données manquantes'];
            }

            $concoursService = new \InscriptionConcoursService();
            $concours = $concoursService->getConcoursById($concoursId);



            if (!$concours) {
                return ['success' => false, 'message' => 'Concours non trouvé'];
            }

            $concoursCode = $concours['code'];
            $folderPath = $this->uploadDir . $concoursCode . '/' . $cin . '/';

            if (!is_dir($folderPath)) {
                if (!mkdir($folderPath, 0755, true)) {
                    return ['success' => false, 'message' => 'Impossible de créer le dossier'];
                }
            }

            $uploadedFiles = [];
            $errors = [];

            foreach ($fileFields as $fieldName) {
                if (isset($files[$fieldName]) && $files[$fieldName]['error'] === UPLOAD_ERR_OK) {
                    $file = $files[$fieldName];

                    $validation = $this->validateFile($file, $fieldName);
                    if (!$validation['valid']) {
                        $errors[$fieldName] = $validation['message'];
                        continue;
                    }

                    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                    $fileName = $fieldName . '.' . $extension;
                    $filePath = $folderPath . $fileName;

                    if (move_uploaded_file($file['tmp_name'], $filePath)) {
                        $uploadedFiles[$fieldName] = [
                            'path' => $filePath,
                            'name' => $fileName,  // <-- C'est ce nom qui sera enregistré
                            'size' => $file['size'],
                            'type' => $file['type']
                        ];
                    } else {
                        $errors[$fieldName] = 'Erreur lors du déplacement du fichier';
                    }
                }
            }

            return [
                'success' => true,
                'message' => 'Opération effectuée avec succès',
                'uploaded' => $uploadedFiles,
                'errors' => $errors,
                'folder' => $folderPath
            ];

        } catch (\Exception $e) {
            return ['success' => false, 'message' => 'Erreur: ' . $e->getMessage()];
        }
    }

    /**
     * Valider un fichier
     */
    private function validateFile($file, $fieldName)
    {
        if ($file['size'] > $this->maxFileSize) {
            return ['valid' => false, 'message' => 'Le fichier est trop volumineux (max 5MB)'];
        }

        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);

        $allowedMimes = [];
        switch ($fieldName) {
            case 'cv':
                $allowedMimes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
                break;
            case 'diplome':
            case 'releves_notes':
            case 'demande_maniscrite':
                $allowedMimes = ['application/pdf', 'image/jpeg', 'image/pjpeg', 'image/png'];
                break;
            case 'cin_recto':
            case 'cin_verso':
                $allowedMimes = ['image/jpeg', 'image/pjpeg', 'image/png'];
                break;
            default:
                $allowedMimes = ['application/pdf', 'image/jpeg', 'image/pjpeg', 'image/png'];
        }

        if (!in_array($mimeType, $allowedMimes)) {
            return ['valid' => false, 'message' => 'Type de fichier non autorisé pour ' . $fieldName];
        }

        return ['valid' => true, 'message' => 'OK'];
    }

    /**
     * Mettre à jour les chemins des documents dans la base de données
     */
    private function updateDocumentPaths($studentId, $concoursId, $uploadedFiles)
    {
        try {

            $service = new \InscriptionConcoursService();

            $inscription = $service->findInscriptionByStudentAndConcours($studentId, $concoursId);

            if (!$inscription) {
                return;
            }

            $updateData = [];
            $documentFields = [
                'cv' => 'cv_path',
                'diplome' => 'diplome_path',
                'releves_notes' => 'releves_notes_path',
                'demande_maniscrite' => 'demande_maniscrite_path',
                'cin_recto' => 'cin_recto_path',
                'cin_verso' => 'cin_verso_path'
            ];

            foreach ($uploadedFiles as $field => $file) {
                if (isset($documentFields[$field])) {
                    $updateData[$documentFields[$field]] = $file['name'];
                }
            }
            if (!empty($updateData)) {
                $service->updateInscription($inscription['id'], $updateData);
            }

        } catch (\Exception $e) {
            error_log('Erreur lors de la mise à jour des chemins: ' . $e->getMessage());
        }
    }

    /**
     * Récupérer le concours par ID
     */
    public function getConcoursById($id)
    {
        try {

            $service = new \InscriptionConcoursService();
            return $service->getConcoursById($id);
        } catch (\Exception $e) {
            return null;
        }
    }


    public function createConcoursFolder($folderName) {
        $targetFolder = $this->uploadDir . $folderName;

        if (!is_dir($targetFolder)) {
            if (mkdir($targetFolder, 0755, true)) {
                return "Folder created: " . $targetFolder;
            } else {
                return "Failed to create folder.";
            }
        }
        return "Folder already exists.";
    }

}