<?php
require_once __DIR__ . '/../../infrastructure/Database.php';
class Gallery
{
    public static function all()
    {
        try {
            $db = Database::getConnection();
            $stmt = $db->prepare("SELECT g.*,gi.id AS gallery_image_id,gi.cover,gi.name AS img, gi.cover
            FROM galleries g
            JOIN gallery_images gi ON g.id = gi.gallery_id
            WHERE gi.cover = 1
            ORDER BY gi.cover DESC, g.status DESC, g.id DESC;");
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            return false;
        }
    }
    
    public static function findRecent(){
        try{
            $db = Database::getConnection();
            $stmt = $db->prepare("SELECT g.*,gi.id AS gallery_image_id,gi.cover,gi.name AS img, gi.cover
            FROM galleries g
            JOIN gallery_images gi ON g.id = gi.gallery_id
            WHERE gi.cover = 1 AND g.status = 1
            ORDER BY gi.cover DESC, g.status DESC, g.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 galleries WHERE id = :id");
            $stmt->execute([':id' => $id]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        }catch(PDOException $e){
            return false;
        }
    }

    public static function create($name,$place,$date){
        try{
            $db = Database::getConnection();
            $stmt = $db->prepare("INSERT INTO galleries (name,place,date) VALUES (:name,:place,:date)");
            $stmt->execute([
                ':name' => $name,
                ':place' => $place,
                ':date' => $date
            ]);
            return $db->lastInsertId();
        }catch(PDOException $e){
            return false;
        }
    }

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

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

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

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