<?php

require_once dirname(__DIR__) . '/../assets/helpers/headers.inc.php';

require_once dirname(__DIR__) . '/../../vendor/autoload.php';
require_once dirname(__DIR__) . '/../assets/helpers/ErrorHandler.php';
require_once dirname(__DIR__) . '/../assets/controllers/Utils.php';
require_once dirname(__DIR__) . '/../assets/controllers/BlogController.php';
require_once dirname(__DIR__) . '/../assets/config/Database.php';

// Load the .env file
$dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__, 2) . '/assets/controllers');
$dotenv->load();

// Set up error handling
set_error_handler('ErrorHandler::handleError');
set_exception_handler('ErrorHandler::handleException');

$config = require dirname(__DIR__, 2) . '/assets/config/config.php';

$db = new Database($config['database']);

// Check if the request method is POST
// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json', true, 405); // Set the content type and status code
    echo json_encode([
        'status' => false,
        'message' => 'Method Not Allowed. Please use POST.'
    ]);
    exit; // Stop further execution
}

if (Utils::checkAuthorization($config)) {
    // Check if the file is uploaded
    if (!isset($_FILES['media_url']) || $_FILES['media_url']['error'] !== UPLOAD_ERR_OK) {
        header('Content-Type: application/json', true, 400); // Set the content type and status code
        echo json_encode([
            'status' => false,
            'message' => 'File upload failed.',
            'data' => $_FILES['media_url']
        ]);
        exit; // Stop further execution
    }

    // Access form data from $_POST
    $data = $_POST; // This will contain all the form fields

    // Create an instance of BlogController
    $blogController = new BlogController($db);

    // Pass the uploaded file along with the data
    $response = $blogController->createBlog($data, $_FILES['media_url']);

    // echo json_encode($response);
}