<?php

namespace api\classes;

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

require_once 'API.php';

class API_permissions extends API
{
    public function getPermission($returnBoolean = false)
    {
        list($query, $types, $params) = $this->buildDynamicQuery('system_permissions');

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

        return $items;
    }

    public function deletePermission()
    {
        $query = "DELETE FROM system_permissions WHERE permission_uuid = ?";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param('s', $this->data['permission_uuid']);
        if ($this->executeStatement($stmt)) {
            $this->apiOutput(200, ['success' => 'Permission deleted successfully.']);
        }
    }

    #[NoReturn]
    public function createPermission()
    {
        # Check if permission slugify already exists
        $result = $this->getPermissionSlugify();
        if ($result->num_rows > 0) {
            $this->apiOutput(409, ['error' => 'Permission slugify already exists'], 'item_already_exists!');
        }

        $query = "INSERT INTO system_permissions (permission_uuid, permission_name, permission_slugify, permission_description, permission_create_timestamp, module_uuid) VALUES (UUID(), ?, ?, ?, ?, ?)";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param('sssis', $this->data['permission_name'], $this->data['permission_slugify'], $this->data['permission_description'], time(), $this->data['module_uuid']);
        $this->executeStatement($stmt);
        $stmt->close();

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

        $permission_data = $result->fetch_assoc();

        # Get all the groups so we can create the permissions for the group
        $user_groups = array();
        $sql = "SELECT * FROM system_user_groups";
        $stmt = $this->conn->query($sql);
        while ($user_group = $stmt->fetch_assoc()) {
            $user_groups[] = $user_group;
        }

        # Update all the groups with the newly added permission
        foreach ($user_groups as $user_group) {
            $query = "INSERT INTO system_user_group_permissions (permission_uuid, user_group_uuid, permission_value) VALUES (?, ?, ?)";
            $permission_value = 'NA';
            if ($user_group['user_group_name'] == 'superuser') {
                $permission_value = 'RW';
            }
            $stmt = $this->prepareStatement($query);
            $stmt->bind_param("sss", $permission_data['permission_uuid'], $user_group['user_group_uuid'], $permission_value);
            $this->executeStatement($stmt);
            $stmt->close();
        }

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

    public function getPermissionSlugify()
    {
        $query = "SELECT * FROM system_permissions WHERE permission_slugify = ?";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param("s", $this->data['permission_slugify']);
        $this->executeStatement($stmt);
        return $stmt->get_result();
    }

    public function updatePermission()
    {
        $query = "UPDATE system_permissions SET permission_name = ?, permission_description = ?, permission_modified_timestamp = ?, module_uuid = ? WHERE permission_uuid = ?";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param('ssiss', $this->data['permission_name'], $this->data['permission_description'], time(), $this->data['module_uuid'], $this->data['permission_uuid']);
        if ($this->executeStatement($stmt)) {
            $this->apiOutput(200, ['success' => 'Permission updated successfully.']);
        }
    }

    public function updateAccessRights()
    {
        $query = "UPDATE system_user_group_permissions SET permission_value = ? WHERE permission_uuid = ? AND user_group_uuid = ?";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param('sss', $this->data['permission_value'], $this->data['permission_uuid'], $this->data['user_group_uuid']);
        if ($this->executeStatement($stmt)) {
            $this->apiOutput(200, ['success' => 'Access rights changed successfully.']);
        }
    }

    public function getPermissionRights()
    {
        $query = "SELECT * FROM system_permissions 
                    INNER JOIN system_user_group_permissions ON system_permissions.permission_uuid = system_user_group_permissions.permission_uuid
                    INNER JOIN system_user_groups ON system_user_group_permissions.user_group_uuid = system_user_groups.user_group_uuid
                    WHERE system_permissions.permission_uuid = ? ORDER BY system_user_groups.user_group_weight ASC";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param('s', $this->data['permission_uuid']);
        $this->executeStatement($stmt);

        $result = $stmt->get_result();
        $access_rights = [];

        while ($row = $result->fetch_assoc()) {
            $access_rights[] = $row;
        }

        return $access_rights;
    }

    public function getUserGroupPermissions()
    {
        list($query, $types, $params) = $this->buildDynamicQuery('system_user_group_permissions');

        $items = $this->generalGetFunction($query, $types, $params, false, 'userGroupPermissions');

        return ($items);
    }
}