<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Project;
use App\Models\Document;
use App\Enums\DocumentType;
use Illuminate\Support\Facades\Storage;


use App\Models\category;
use App\Models\Chapter;
use Yajra\DataTables\Facades\DataTables;

class ChapterController extends Controller
{    
    public function store(Request $request)
    {
        $request->validate([
            'libelle' => 'required|string|max:255',
            'coursFileName' => 'nullable|file|mimes:pdf,doc,docx|max:10240',
            'resumeFileName' => 'nullable|file|mimes:pdf,doc,docx|max:10240',
            'videoFileName' => 'nullable',
            // Ajoutez d'autres règles de validation au besoin 'nullable|file|mimes:mp4,mov,avi|max:102400',
        ]);

       
        $chapter = new Chapter();
        $chapter->libelle = $request->input('libelle');
        $chapter->document_id = $request->input('document_id');
   
        // Stockage des fichiers dans le dossier "uploads" (à ajuster selon vos besoins)
        if ($request->hasFile('coursFileName') && $request->file('coursFileName')->isValid()) {
            $coursFile = $request->file('coursFileName');
            $coursFileName = $this->generateUniqueFileName($coursFile, 'documents');
            $chapter->coursFileName = $coursFileName;
        }
        
        if ($request->hasFile('resumeFileName') && $request->file('resumeFileName')->isValid()) {
            $resumeFile = $request->file('resumeFileName');
            $resumeFileName = $this->generateUniqueFileName($resumeFile, 'documents');
            $chapter->resumeFileName = $resumeFileName;
        }
        
        if ($request->hasFile('videoFileName') && $request->file('videoFileName')->isValid()) {
            $videoFile = $request->file('videoFileName');            
            $videoFileName = $this->generateUniqueFileName($videoFile, 'documents');
            $chapter->videoFileName = $videoFileName;
        }
        // Enregistrez le chapitre dans la base de données
        $chapter->save();

        return redirect()->back()->with('success', 'Chapitre ajoutées avec succès.');
    }

    public function storemulti(Request $request)
    {

        // Validez les données du formulaire
        $request->validate([
            'libelle.*' => 'required|string|max:255',
            'coursFileName.*' => 'nullable|file|mimes:pdf,doc,docx|max:10240',
            'resumeFileName.*' => 'nullable|file|mimes:pdf,doc,docx|max:10240',
            'videoFileName.*' => 'nullable',
        ]);

       
        foreach ($request->input('libelle') as $key => $libelle) {
            $chapter = new Chapter();
            $chapter->libelle = $libelle;
            $chapter->document_id = $request->input('document_id');

            // Stockage des fichiers dans le dossier "documents" (à ajuster selon vos besoins)
            if ($request->hasFile("coursFileName.$key") && $request->file("coursFileName.$key")->isValid()) {
                $coursFile = $request->file("coursFileName.$key");
                $coursFileName = $this->generateUniqueFileName($coursFile, 'documents');
                $chapter->coursFileName = $coursFileName;
            }

            if ($request->hasFile("resumeFileName.$key") && $request->file("resumeFileName.$key")->isValid()) {
                $resumeFile = $request->file("resumeFileName.$key");
                $resumeFileName = $this->generateUniqueFileName($resumeFile, 'documents');
                $chapter->resumeFileName = $resumeFileName;
            }

            if ($request->hasFile("videoFileName.$key") && $request->file("videoFileName.$key")->isValid()) {
                $videoFile = $request->file("videoFileName.$key");
                $videoFileName = $this->generateUniqueFileName($videoFile, 'documents');
                $chapter->videoFileName = $videoFileName;
            }

            // Enregistrez le chapitre dans la base de données
            $chapter->save();
        }

        return redirect()->back()->with('success', 'Chapitres ajoutées avec succès.');
    }

    private function generateUniqueFileName($file, $folder)
    {
        $uid = uniqid();
        $extension = $file->getClientOriginalExtension();
        $fileName = "{$uid}.{$extension}";

        // Vérifier si le fichier existe déjà, si oui, régénérer un nouveau nom unique
        while (Storage::disk('public')->exists("{$folder}/{$fileName}")) {
            $uid = uniqid();
            $fileName = "{$uid}.{$extension}";
        }

        // Stockage du fichier avec le nouveau nom unique
        $file->storeAs($folder, $fileName, 'public');

        return $fileName;
    }

    public function destroy(Chapter $chapter)
    {
        $chapter->delete();

        return response()->json(null, 204);
    }

}
