<?php
require_once __DIR__ . '/../models/Gallery.php';
require_once __DIR__ . '/../models/GalleryImages.php';

header('Content-Type: application/json');   
class GalleryController
{
    public static function index(){
        $galleries = Gallery::all();
        echo json_encode([
            'success' => true,
            'message' => '¡Galerías obtenidas con exito!',
            'galleries' => $galleries
        ]);
    }
    public static function recent(){
        $galleriesRecent = Gallery::findRecent();
        echo json_encode([
            'success'=>true,
            'message'=>'¡Galerías obtenidas exitosamente!',
            'galleries_recent'=> $galleriesRecent
        ]);
    }
    public static function store($name,$place,$date, $images){
        $galleryId = Gallery::create($name,$place,$date);
        if($galleryId){
            $all_images_saved = true;
            foreach ($images as $image) {
                if (!GalleryImages::create($galleryId, $image['name'], $image['isCover'])) {
                    $all_images_saved = false;
                    break; 
                }
            }

            if ($all_images_saved) {
                echo json_encode([
                    'success' => true,
                    'message' => '¡Galería creada correctamente!',
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => '¡Error al guardar las imágenes de la galería!'
                ]);
            }
        }else{
            echo json_encode([
                'success' => false,
                'message' => '¡Error al crear la galería!'
            ]);
        }
    }
    public static function show($id){
        $gallery = Gallery::findById($id);
        if ($gallery) {
            $images = GalleryImages::findByGalleryId($id);
            $gallery['images'] = $images ? $images : [];
        }
        echo json_encode([
            'success' => $gallery ? true : false,
            'message' => $gallery ? 'Galería encontrada correctamente' : 'Galería no encontrada.',
            'gallery' => $gallery
        ]);
    }
    public static function update(int $id, $name, $place, $date, $images, $status)
    {
        $galleryData = ['name' => $name, 'place' => $place, 'date' => $date, 'status' => $status];
        if (!Gallery::update($id, $galleryData)) {
            echo json_encode(['success' => false, 'message' => 'Error al actualizar los detalles de la galería.']);
            return;
        }

        $currentImages = GalleryImages::findByGalleryId($id);
        $currentImageNames = $currentImages ? array_map(fn($img) => $img['name'], $currentImages) : [];
        $finalImages = $images ?? [];
        $finalImageNames = array_map(fn($img) => $img['name'], $finalImages);


        $imagesToDelete = array_diff($currentImageNames, $finalImageNames);
        foreach ($imagesToDelete as $imageName) {
            self::deleteImage($imageName);
        }

        GalleryImages::deleteByGalleryId($id);

        if (!empty($finalImages)) {
            foreach ($finalImages as $image) {
                GalleryImages::create($id, $image['name'], $image['isCover']);
            }
        }

        echo json_encode([
            'success' => true,
            'message' => '¡Galería actualizada correctamente!',
        ]);
    }
    public static function status(int $id, $status)
    {
        if(Gallery::update($id,['status'=>$status])){
            echo json_encode([
                'success' => true,
                'message' => '¡Galería actualizada correctamente!',
            ]);
        }else{
            echo json_encode([
                'success' => false,
                'message' => '¡Error al actualizar la galería!'
            ]);
        }
    }
    public static function uploadImage($file){
        $uploadDir  = __DIR__ . '/../../resources/images/galleries/';
        if(!is_dir($uploadDir)){
            mkdir($uploadDir, 0777, true);
        }

        $fileName = is_array($file['name']) ? $file['name'][0] : $file['name'];
        $tmpName = is_array($file['tmp_name']) ? $file['tmp_name'][0] : $file['tmp_name'];

        $ext = pathinfo($fileName, PATHINFO_EXTENSION);
        $safeName = uniqid('gallery_',true).'.'.$ext;
        $uploadFile = $uploadDir . $safeName;
        if(move_uploaded_file($tmpName, $uploadFile)){
            echo $safeName;
        }
    }
    public static function deleteImage($filename){
        $uploadDir  = __DIR__ . '/../../resources/images/galleries/';
        $file = $uploadDir . $filename;
        if(file_exists($file)){
            unlink($file);
        }
    }
}