<?php
require_once __DIR__ . '/../../infrastructure/Database.php';

class GalleryImages
{
    public static function all()
    {
        try {
            $db = Database::getConnection();
            $stmt = $db->prepare("SELECT * FROM gallery_images ORDER BY status DESC,id DESC");
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            return false;
        }
    }

    public static function findById(int $id){
        try{
            $db = Database::getConnection();
            $stmt = $db->prepare("SELECT * FROM gallery_images WHERE id = :id");
            $stmt->execute([':id' => $id]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        }catch(PDOException $e){
            return false;
        }
    }
    public static function create($gallery_id,$name,$cover){
        try{
            $db = Database::getConnection();
            $stmt = $db->prepare("INSERT INTO gallery_images (gallery_id,name,cover) VALUES (:gallery_id,:name,:cover)");   
            $stmt->execute([
                ':gallery_id' => $gallery_id,
                ':name' => $name,
                ':cover' => $cover
            ]);
            return true;
        }catch(PDOException $e){
            return false;
        }
    }

    public static function findByGalleryId(int $gallery_id){
        try{
            $db = Database::getConnection();
            $stmt = $db->prepare("SELECT * FROM gallery_images WHERE gallery_id = :gallery_id ORDER BY cover DESC, id ASC");
            $stmt->execute([':gallery_id' => $gallery_id]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        }catch(PDOException $e){
            return false;
        }
    }

    public static function deleteByGalleryId(int $gallery_id)
    {
        try{
            $db = Database::getConnection();
            $stmt = $db->prepare("DELETE FROM gallery_images WHERE gallery_id = :gallery_id");
            $stmt->execute([':gallery_id' => $gallery_id]);
            return true;
        }catch(PDOException $e){
            return false;
        }
    }

    public static function update($id, $data){
        try{
            $db = Database::getConnection();
            $fields = [];
            $params = [':id'=>$id];
            $allowedFields = ['gallery_id','name','cover','status'];

            foreach($allowedFields as $field){
                if(isset($data[$field])){
                    $fields[] = $field . ' = :' . $field;
                    $params[':' . $field] = $data[$field];
                }
            }

            if(empty($fields)){
                return false;
            }

            $query = "UPDATE gallery_images SET " . implode(', ', $fields) . " WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->execute($params);
            return true;
        }catch(PDOException $e){
            return false;
        }
    }
}