<?php
require_once __DIR__ . '/../models/Blog.php';
header('Content-Type: application/json');   
class BlogController
{
    public static function index($status){
        $blogs = Blog::all($status);
        echo json_encode([
            'success' => true,
            'message' => '¡Blogs obtenidos con exito!',
            'blogs' => $blogs
        ]);
    }

    public static function show($id){
        $blog = Blog::findById($id);
        echo json_encode([
            'success' => true,
            'message' => 'Blog encontrado correctamente',
            'blog' => $blog
        ]);
    }

    public static function store($title,$description,$img){
        if(Blog::create($title,$description,$img)){
            echo json_encode([
                'success' => true,
                'message' => 'Blog creado correctamente!',
            ]);
        }else{
            echo json_encode([
                'success' => false,
                'message' => '¡Error al crear el evento!'
            ]);
        }
    }
    public static function update(int $id,$title,$description,$img,$status)
    {
        $blog = Blog::findById($id);
        $img_old = $blog['img'];
        if($img_old != $img){
            self::deleteImg($img_old);
        }
        if(Blog::update($id,['title'=>$title, 'description'=>$description, 'img'=>$img, 'status'=>$status])){
            echo json_encode([
                'success' => true,
                'message' => 'Blog actualizado correctamente!',
            ]);
        }else{
            echo json_encode([
                'success' => false,
                'message' => '¡Error al actualizar el blog!'
            ]);
        }
    }

    public static function status(int $id, $status)
    {
        if(Blog::update($id,['status'=>$status])){
            echo json_encode([
                'success' => true,
                'message' => 'Blog actualizado correctamente!',
            ]);
        }else{
            echo json_encode([
                'success' => false,
                'message' => '¡Error al actualizar el blog!'
            ]);
        }
    }

    public static function uploadImg($file){
        $uploadDir  = __DIR__ . '/../../resources/images/blogs/';
        if(!is_dir($uploadDir)){
            mkdir($uploadDir, 0777, true);
        }
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $safeName = uniqid('img_',true).'.'.$ext;
        $uploadFile = $uploadDir . $safeName;
        if(move_uploaded_file($file['tmp_name'], $uploadFile)){
            echo $safeName;
        }
    }
    public static function deleteImg($filename){
        $uploadDir  = __DIR__ . '/../../resources/images/blogs/';
        $file = $uploadDir . $filename;
        if(file_exists($file)){
            unlink($file);
        }
    }

}