<?php

namespace api\classes;

use api\classes\API;
use api\classes\imageProcessor;
use JetBrains\PhpStorm\NoReturn;

require_once 'API.php';

class API_devices extends API
{

    public function getDevices($returnBoolean = false)
    {
        list($query, $types, $params) = $this->buildDynamicQuery('autop_devices');

        $items = $this->generalGetFunction($query, $types, $params, $returnBoolean, 'Device');

        return $items;
    }

    private function getDeviceSlugify()
    {
        $query = "SELECT * FROM autop_devices WHERE device_slugify = ?";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param("s", $this->data['device_slugify']);
        $this->executeStatement($stmt);
        return $stmt->get_result();
    }

    public function createDeviceImage($imageRestrictions)
    {
        try {
            # Main image
            $imageProcessor = new imageProcessor('device_image');
            $imageProcessor->imageRestrictions = $imageRestrictions;
            $imageProcessor->validateAndProcess();
            $ImageData = $imageProcessor->returnBase64image();
        } catch (\RuntimeException $e) {
            $this->apiOutput(401, ['error' => 'Error: ' . $e->getMessage()]);
        }

        return $ImageData;
    }

    #[NoReturn]
    public function createDevice()
    {

        if (isset($this->data['device_image'])) {
            $query = "INSERT INTO autop_devices (device_uuid, device_vendor_uuid, device_type, device_name, device_slugify, device_enabled, device_notes, device_eol, device_extensions, device_extra, device_create_timestamp, device_image, device_image_thumbnail) 
                        VALUES (UUID(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $this->prepareStatement($query);
            $stmt->bind_param("ssssisississ", $this->data['device_vendor_uuid'], $this->data['device_type'], $this->data['device_name'], $this->data['device_slugify'], $this->data['device_enabled'], $this->data['device_notes'], $this->data['device_eol'], $this->data['device_extensions'], $this->data['device_extra'], time(), $this->data['device_image'], $this->data['device_image_thumbnail']);
        } else {
            $query = "INSERT INTO autop_devices (device_uuid, device_vendor_uuid, device_type, device_name, device_slugify, device_enabled, device_notes, device_eol, device_extensions, device_extra, device_create_timestamp) 
                        VALUES (UUID(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $this->prepareStatement($query);
            $stmt->bind_param("ssssisissi", $this->data['device_vendor_uuid'], $this->data['device_type'], $this->data['device_name'], $this->data['device_slugify'], $this->data['device_enabled'], $this->data['device_notes'], $this->data['device_eol'], $this->data['device_extensions'], $this->data['device_extra'], time());
        }

        $this->executeStatement($stmt);

        $stmt->close();

        $result = $this->getDeviceSlugify();
        if ($result->num_rows === 0) {
            $this->apiOutput(500, ['error' => 'Something went wrong creating the device.'], 'error_contact_support');
        }

        $createDirsFailed = false;
        $dirsToCreate = array(
            $_SERVER['DOCUMENT_ROOT'] . "/data/devices/" . $this->data['device_slugify'],
            $_SERVER['DOCUMENT_ROOT'] . "/data/devices/" . $this->data['device_slugify'] . "/firmware",
            $_SERVER['DOCUMENT_ROOT'] . "/data/devices/" . $this->data['device_slugify'] . "/documents"
        );

        foreach ($dirsToCreate as $dir) {
            if (!file_exists($dir)) {
                if (!mkdir($dir)) {
                    $createDirsFailed = true;
                }
            }
        }

        if ($createDirsFailed) {
            $this->apiOutput(500, ['error' => 'Something went wrong creating the device on the server.'], 'error_contact_support');
        }

        $platform_data = $result->fetch_assoc();

        $this->apiOutput(200, ['success' => $platform_data], 'item_added');
    }

    public function updateDevice()
    {
        if (isset($this->data['device_image'])) {
            $query = "UPDATE autop_devices SET device_modified_timestamp = ?, device_vendor_uuid = ?, device_name = ?, device_enabled = ?, device_notes = ?, device_eol = ?, device_extensions = ?, device_extra = ?, device_image = ?, device_image_thumbnail = ? WHERE device_uuid = ?";
            $stmt = $this->prepareStatement($query);
            $stmt->bind_param("issisisssss", time(), $this->data['device_vendor_uuid'], $this->data['device_name'], $this->data['device_enabled'], $this->data['device_notes'], $this->data['device_eol'], $this->data['device_extensions'], $this->data['device_extra'], $this->data['device_image'], $this->data['device_image_thumbnail'], $this->data['device_uuid']);
        } else {
            $query = "UPDATE autop_devices SET device_modified_timestamp = ?, device_vendor_uuid = ?, device_name = ?, device_enabled = ?, device_notes = ?, device_eol = ?, device_extensions = ?, device_extra = ? WHERE device_uuid = ?";
            $stmt = $this->prepareStatement($query);
            $stmt->bind_param("issisisss", time(), $this->data['device_vendor_uuid'], $this->data['device_name'], $this->data['device_enabled'], $this->data['device_notes'], $this->data['device_eol'], $this->data['device_extensions'], $this->data['device_extra'], $this->data['device_uuid']);
        }

        if ($this->executeStatement($stmt)) {
            $this->apiOutput(200, ['success' => 'Device updated successfully.']);
        }
    }

    #[NoReturn]
    public function deleteDevice()
    {
        # check if the device exists
        $_GET['builder'] = [1 => ['where' => [0 => 'device_uuid', 1 => $this->data['device_uuid']]]];
        $device = $this->getDevices()[0];

        # remove from database
        $query = "DELETE FROM autop_devices WHERE device_uuid = ?";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param("s", $device['device_uuid']);

        $this->executeStatement($stmt);

        # Delete the device data folder.
        $dirsToDelete = $_SERVER['DOCUMENT_ROOT'] . "/data/devices/" . $device['device_slugify'];
        $this->RecursiveDeleteFolder($dirsToDelete);

        $this->apiOutput(200, ['success' => 'Device removed successfully.']);
    }
}