<?php

require_once dirname(__DIR__) . '/../assets/models/Blog.php';
require_once dirname(__DIR__) . '/../assets/controllers/Utils.php';

class BlogController
{

    private Database $db;

    public function __construct(Database $db)
    {
        $this->db = $db;
    }

    // Method to validate profile data
    public function validateBlozgData(array $data): array
    {
        $errors = [];

        // List of common required fields
        $requiredFields = [
            'usertoken',
            'title',
            'excerpts',
            'content',
            // 'media_url',
            'media_type',
            'category_id'
        ];

        // Check each required field
        foreach ($requiredFields as $field) {
            if (empty($data[$field])) {
                $errors[] = "$field cannot be empty.";

            }
        }

        // Check if media_url is provided
        if (!isset($_FILES['media_url']) || $_FILES['media_url']['error'] !== UPLOAD_ERR_OK) {
            $errors[] = "media_url cannot be empty.";
        }

        return $errors;
    }

    public function fetchAllBlogs(): array
    {
        $blogModel = new Blog($this->db, []);

        $blogs = $blogModel->getAllBlogs();

        // Check if no blogs exist
        if (empty($blogs)) {
            return Utils::returnData(false, 'No blog available', null, false);
        }


        return [
            'status' => true,
            'message' => 'Blogs fetched successfully.',
            'data' => $blogs
        ];
    }

    public function fetchBlogsByExcerpts($excerpts): array
    {
        $blogModel = new Blog($this->db, []);

        $blogs = $blogModel->getBlogByExcerpts($excerpts);

        // Check if no blogs exist
        if (empty($blogs)) {
            return Utils::returnData(false, 'No blog available', null, false);
        }


        return [
            'status' => true,
            'message' => 'Blogs fetched successfully.',
            'data' => $blogs
        ];
    }



    public function createBlog(array $data, $file)
    {
        $errors = $this->validateBlozgData($data);
        if (!empty($errors)) {
            return Utils::returnData(false, 'Validation errors', $errors, true);
        }

        // Extract the token from the data
        $usertoken = $data['usertoken'];

        // Pass both the usertoken and the file to the Blog model
        $blog = new Blog($this->db, $data);

        if ($blog->createBlog($usertoken, $file)) {
            return Utils::returnData(true, 'Blog created successfully.', null, false);
        }

        if (!$blog->createBlog($usertoken, $file)) {
            return Utils::returnData(false, 'Failed to create blog', null, true);
        }
    }

}
