<?php

namespace bin\php\Classes;
if (!defined('APP_INIT')) {
    exit;
}

class healthCheck
{
    public function __construct()
    {
        include_once $_SERVER['DOCUMENT_ROOT'] . '/bin/php/db_connect.php';
        include_once $_SERVER['DOCUMENT_ROOT'] . '/bin/php/globalFunctions.php';
    }

    public function healthCheck()
    {
        echo 'Checking and creating device data folders...';
        if ($this->checkDeviceDataFolders()) {
            echo 'Success creating device data folders';
        } else {
            echo 'something went wrong creating device data folders!';
        }

    }

    private function checkDeviceDataFolders()
    {
        try {
            $sql = "SELECT device_slugify FROM vc_devices";

            $stmt = $GLOBALS['conn']->prepare($sql);

            if ($stmt === false) {
                throw new Exception("Failed to prepare the SQL statement: " . $GLOBALS['conn']->error);
            }

            if (!$stmt->execute()) {
                throw new Exception("Failed to execute the SQL statement: " . $stmt->error);
            }

            $result = $stmt->get_result();

            while ($row = $result->fetch_assoc()) {
                $device_slugify = $row['device_slugify'];
                $dirsToCreate = array(
                    $_SERVER['DOCUMENT_ROOT'] . "/data/devices/" . $device_slugify,
                    $_SERVER['DOCUMENT_ROOT'] . "/data/devices/" . $device_slugify . "/firmware",
                    $_SERVER['DOCUMENT_ROOT'] . "/data/devices/" . $device_slugify . "/documents"
                );

                foreach ($dirsToCreate as $dir) {
                    if (!file_exists($dir)) {
                        if (!mkdir($dir)) {
                            throw new Exception("Failed to create the directory: " . $dir);
                        }
                    }
                }
            }

            $stmt->close();
        } catch (Exception $e) {
            return $e->getMessage();
        }

        return true;
    }
}