<?php

use api\classes\API_devices;

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

$API_devices = new API_devices();

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

    # GET the devices

    $API_devices->checkPermissions('admin-devices', 'RO');

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

    # create a new device

    $API_devices->checkPermissions('admin-devices', 'RW');

    $ImageData = $API_devices->createDeviceImage(['min_width' => 500, 'max_width' => 1000, 'min_height' => 500, 'max_height' => 1000, 'square' => true, 'allowed_types' => ['image/png'], 'max_size_kb' => 1024, 'transparent' => true]);
    $ImageDataThumbnail = $API_devices->createDeviceImage(['min_width' => 64, 'max_width' => 64, 'min_height' => 64, 'max_height' => 64, 'square' => true, 'allowed_types' => ['image/png'], 'max_size_kb' => 1024, 'transparent' => true]);
    $API_devices->postedData['device_eol'] = $_POST['device_eol'] !== ''
        ? DateTime::createFromFormat('d/m/Y', $_POST['device_eol'])?->getTimestamp()
        : null;
    $API_devices->postedData['device_extensions'] = isset($_POST['device_extensions']) ? json_encode($_POST['device_extensions']) : '[""]';
    $API_devices->postedData['device_extra'] = preg_replace('/\s+/', '', str_replace(["\r", "\n"], '', $_POST['device_extra'] ?? '{}'));

    if ($ImageData) {
        $API_devices->postedData['device_image'] = $ImageData;
    }
    if ($ImageDataThumbnail) {
        $API_devices->postedData['device_image_thumbnail'] = $ImageDataThumbnail;
    }

    $requiredFields = [
        'device_vendor_uuid' => ['type' => 'uuid'],
        'device_type' => ['type' => 'enum', 'values' => ['base', 'handset', 'module', 'phone']],
        'device_name' => ['type' => 'string'],
        'device_slugify' => ['type' => 'slugify'],
        'device_enabled' => ['type' => 'boolean'],
        'device_notes' => ['type' => 'string'],
        'device_eol' => ['type' => 'timestamp'],
        'device_extensions' => ['type' => 'json'],
        'device_extra' => ['type' => 'string'],
    ];

    $optionalFields = [
        'device_image' => ['type' => 'base64'],
        'device_image_thumbnail' => ['type' => 'base64']
    ];

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

    $API_devices->createDevice();

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

    # Edit the device
    $API_devices->checkPermissions('admin-devices', 'RW');

    # process the posted image (if any)
    $ImageData = $API_devices->createDeviceImage(['min_width' => 500, 'max_width' => 1000, 'min_height' => 500, 'max_height' => 1000, 'square' => true, 'allowed_types' => ['image/png'], 'max_size_kb' => 1024, 'transparent' => true]);
    $ImageDataThumbnail = $API_devices->createDeviceImage(['min_width' => 64, 'max_width' => 64, 'min_height' => 64, 'max_height' => 64, 'square' => true, 'allowed_types' => ['image/png'], 'max_size_kb' => 1024, 'transparent' => true]);
    $API_devices->postedData['device_eol'] = $_POST['device_eol'] !== ''
        ? DateTime::createFromFormat('d/m/Y', $_POST['device_eol'])?->getTimestamp()
        : null;
    $API_devices->postedData['device_extensions'] = isset($_POST['device_extensions']) ? json_encode($_POST['device_extensions']) : '[""]';
    $API_devices->postedData['device_extra'] = preg_replace('/\s+/', '', str_replace(["\r", "\n"], '', $_POST['device_extra'] ?? '{}'));

    if ($ImageData) {
        $API_devices->postedData['device_image'] = $ImageData;
    }
    if ($ImageDataThumbnail) {
        $API_devices->postedData['device_image_thumbnail'] = $ImageDataThumbnail;
    }

    $requiredFields = [
        'device_uuid' => ['type' => 'uuid'],
        'device_vendor_uuid' => ['type' => 'uuid'],
        'device_name' => ['type' => 'string'],
        'device_enabled' => ['type' => 'boolean'],
        'device_notes' => ['type' => 'string'],
        'device_eol' => ['type' => 'timestamp'],
        'device_extensions' => ['type' => 'json'],
        'device_extra' => ['type' => 'string'],
    ];

    $optionalFields = [
        'device_image' => ['type' => 'base64'],
        'device_image_thumbnail' => ['type' => 'base64']
    ];

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

    $_GET['builder'] = [1 => ['where' => [0 => 'device_uuid', 1 => $API_devices->data['device_uuid']]]];
    $API_devices->getDevices();

    $API_devices->updateDevice();

} elseif ($API_devices->request_method === 'DELETE') {

    # delete an device

    $API_devices->checkPermissions('admin-devices', 'RW');

    # when called from the frontend will not be forwarding to a url since when it's called from the frontend it doesn't need a redirection
    $API_devices->return_url = false;

    $requiredFields = ['device_uuid' => ['type' => 'uuid']];
    $API_devices->validateData($requiredFields);

    # check if the device exists
    $_GET['builder'] = [1 => ['where' => [0 => 'device_uuid', 1 => $API_devices->data['device_uuid']]]];

    # Delete the device from the database.
    $API_devices->deleteDevice();
}