<?php

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


class Blog
{
    private $connection;

    private $table = 'blogs';

    public readonly string $author;

    public readonly string $category_name;

    private array $data;

    public function __construct($db, array $data = [])
    {
        $this->connection = $db;

        $this->data = !empty($data) ? [
            'title' => htmlspecialchars(strip_tags($data['title'] ?? '')),
            'excerpts' => htmlspecialchars(strip_tags($data['excerpts'] ?? '')),
            'content' => htmlspecialchars($data['content'] ?? ''),
            'category_id' => htmlspecialchars(strip_tags($data['category_id'] ?? '')),
            'media_url' => htmlspecialchars(strip_tags($data['media_url'] ?? '')),
            'media_type' => htmlspecialchars(strip_tags($data['media_type'] ?? '')),
        ] : [];
    }

    // Method to verify user token and retrieve user_id
    private function getUserIdFromToken($usertoken)
    {
        $query = "SELECT id, isAdmin 
            FROM users 
            WHERE usertoken = :usertoken";
        $statement = $this->connection->query($query, ['usertoken' => $usertoken]);

        return $statement->find(); // This returns the user ID or null
    }

    function handleFileUpload($file)
    {
        $uploadDirectory = dirname(__DIR__) . '/../media/';
        $uploadFilePath = $uploadDirectory . basename($file['name']);

        // Check if the media directory exists, if not, create it
        if (!file_exists($uploadDirectory)) {
            mkdir($uploadDirectory, 0777, true); // Create the directory with proper permissions (0777)
        }

        // Check if the file is an image/video
        $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'video/mp4', 'video/avi'];
        if (!in_array($file['type'], $allowedTypes)) {
            return Utils::returnData(false, 'Invalid file type.', null, true);
        }

        // Move the uploaded file to the server
        if (move_uploaded_file($file['tmp_name'], $uploadFilePath)) {
            // Return the file URL
            return 'https://api.qlsportsonline.com/v1.0/src/media/' . basename($file['name']);
        }

        return Utils::returnData(false, 'Failed to upload file.', null, true);
    }

    public function getAllBlogs(): array
    {
        $query = "SELECT 
            c.name as category_name, 
            u.name as author,
            b.id,
            b.category_id,
            b.author_id,
            b.title,
            b.excerpts,
            b.content,
            b.media_url,
            b.media_type,
            b.create_time   
        FROM {$this->table} b
        LEFT JOIN categories c ON b.category_id = c.id
        LEFT JOIN users u ON b.author_id = u.id
        ORDER BY b.create_time DESC";
        $statement = $this->connection->query($query);

        $blog = $statement->getAll();

        if (!$blog) {
            return false;
        }

        return $blog;
    }

    public function getBlogByExcerpts($excerpts): array
    {
        // Sanitize input excerpts to prevent SQL injection
        $excerpts = htmlspecialchars(strip_tags($excerpts));

        $query = "SELECT 
        c.name as category_name, 
        u.name as author,
        b.id,
        b.category_id,
        b.author_id,
        b.title,
        b.content,
        b.media_url,
        b.media_type,
        b.create_time   
    FROM {$this->table} b
    LEFT JOIN categories c ON b.category_id = c.id
    LEFT JOIN users u ON b.author_id = u.id
    WHERE b.excerpts = :excerpts
    LIMIT 1";  // Limit to a single result since you're looking for one blog by excerpts

        $statement = $this->connection->query($query, ['excerpts' => $excerpts]);

        $blog = $statement->find();

        if (!$blog) {
            return false;
        }

        return $blog;
    }


    public function createBlog($usertoken, $file)
    {
        // Verify and get user_id from the token
        $user = $this->getUserIdFromToken($usertoken);

        if (!$user || $user['isAdmin'] !== 1) {
            return Utils::returnData(false, 'Access denied: invalid or missing token.', null, true);
        }

        // Handle file upload and get the file URL
        $mediaUrl = $this->handleFileUpload($file);

        if (isset($mediaUrl['error'])) {
            return $mediaUrl;  // Return an error if the file upload failed
        }

        // Update the media_url in data array
        $this->data['media_url'] = $mediaUrl;

        // Update user_id in data array
        $this->data['author_id'] = $user['id'];

        // Insert blog into the database
        $query = "INSERT INTO {$this->table} (title, excerpts, content, media_url, media_type, author_id, category_id) 
              VALUE (:title, :excerpts, :content, :media_url, :media_type, :author_id, :category_id)";

        $statement = $this->connection->query($query, $this->data);

        if ($statement) {
            return true;
        }

        // Print error if something goes wrong
        printf("Error: %s.\n", $this->connection->statement->errorInfo()[2]); // Print the actual error message

        return false;
    }


    public function updateBlog($usertoken)
    {
        // Verify and get user_id from the token
        $user = $this->getUserIdFromToken($usertoken);

        if (!$user || $user['isAdmin'] !== 1) {
            return Utils::returnData(false, 'Access denied: invalid or missing token.', null, true);
        }

        // Update user_id in data array
        $this->data['author_id'] = $user['id'];

        $query = "UPDATE {$this->table} SET 
            title = :title, 
            excerpts = :excerpts, 
            content = :content, 
            media_url = :media_url, 
            media_type = :media_type, 
            category_id = :category_id 
            WHERE author_id = :author_id"
        ;

        $statement = $this->connection->query($query, $this->data);

        if ($statement) {
            return true;
        }

        // Print error if something goes wrong
        printf("Error: %s.\n", $this->connection->statement->errorInfo()[2]); // Print the actual error message

        return false;
    }

    public function deleteBlog($usertoken)
    {
        // Verify and get user_id from the token
        $user = $this->getUserIdFromToken($usertoken);

        if (!$user || $user['isAdmin'] !== 1) {
            return Utils::returnData(false, 'Access denied: invalid or missing token.', null, true);
        }


        // Prepare the delete query
        $query = "DELETE FROM {$this->table} WHERE author_id = :author_id";

        // Execute the delete query
        $statement = $this->connection->query($query, ['author_id' => $user['id']]);

        if ($statement) {
            return true;
        }

        // Print error if something goes wrong
        printf("Error: %s.\n", $this->connection->statement->errorInfo()[2]); // Print the actual error message

        return false;
    }

}
