<?php

use api\classes\API_vendors;
use api\classes\imageProcessor;

session_start();
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_vendors.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/imageProcessor.php";

$API_vendors = new API_vendors();

if ($API_vendors->request_method === 'GET') {

    # get all the vendor

    $API_vendors->checkPermissions('admin-vendors', 'RO');

} elseif ($API_vendors->request_method === 'POST') {

    # create a new vendor

    $API_vendors->checkPermissions('admin-vendors', 'RW');

    try {
        $imageProcessor = new imageProcessor('vendor_image');
        $imageProcessor->imageRestrictions = [
            'min_width' => 200,
            'max_width' => 200,
            'min_height' => 200,
            'max_height' => 200,
            'square' => true,
            'allowed_types' => ['image/png'],
            'max_size_kb' => 1024
        ];
        $imageProcessor->validateAndProcess();
        $finalImageData = $imageProcessor->returnBase64image();
    } catch (Exception $e) {
        $API_vendors->apiOutput(401, ['error' => 'Error: ' . $e->getMessage()]);
    }

    $API_vendors->postedData['vendor_image'] = $finalImageData;

    $requiredFields = [
        'vendor_name' => ['type' => 'string'],
        'vendor_slugify' => ['type' => 'slugify'],
        'vendor_enabled' => ['type' => 'boolean'],
        'vendor_description' => ['type' => 'string'],
    ];
    $optionalFields = ['vendor_image' => ['type' => 'string']];

    $API_vendors->validateData($requiredFields, $optionalFields);

    $API_vendors->createVendor();

} elseif ($API_vendors->request_method === 'PUT') {

    # edit a vendor

    $API_vendors->checkPermissions('admin-vendors', 'RW');

    try {
        $imageProcessor = new imageProcessor('vendor_image');
        $imageProcessor->imageRestrictions = [
            'min_width' => 200,
            'max_width' => 200,
            'min_height' => 200,
            'max_height' => 200,
            'square' => true,
            'allowed_types' => ['image/png'],
            'max_size_kb' => 1024
        ];
        $imageProcessor->validateAndProcess();
        $finalImageData = $imageProcessor->returnBase64image();
    } catch (Exception $e) {
        $API_vendors->apiOutput(401, ['error' => 'Error: ' . $e->getMessage()]);
    }

    if ($finalImageData) {
        $API_vendors->postedData['vendor_image'] = $finalImageData;
    }

    $requiredFields = [
        'vendor_name' => ['type' => 'string'],
        'vendor_uuid' => ['type' => 'slugify'],
        'vendor_enabled' => ['type' => 'boolean'],
        'vendor_description' => ['type' => 'string'],
    ];
    $optionalFields = ['vendor_image' => ['type' => 'string']];

    $API_vendors->validateData($requiredFields, $optionalFields);

    $_GET['builder'] = [1 => ['where' => [0 => 'vendor_uuid', 1 => $API_vendors->data['vendor_uuid']]]];
    $API_vendors->getVendors();

    $API_vendors->editVendor();
}




