<?php

namespace App\Controllers;
use Config\Database;
use CodeIgniter\RESTful\ResourceController;
use App\Controllers\TransferController;

class PermissionController extends ResourceController
{
    /*
        Created: 2026-04-16
        Author: Kārlis Grīnvalds
        Last edited: 2026-05-06
        Edited by: Kārlis Grīnvalds
    */

    // Returns user permissions
    public function GetUserPermissions($topic) {
        $session = service("session");
        $sessionData = ["hasSession" => false, "id" => 0];
        if ($session->has("userdata")) {
            $sessionData["hasSession"] = true;
            $sessionData["id"] = $session->get("userdata")->id;
        }
        $session->close();
        $db = Database::connect();
        $query = $db->query('CALL get_permissions('.$db->escape($topic).', '.$db->escape($sessionData["id"]).')')->getResult();
        if (!empty($query)) {
            return [
                "owner" => ($query[0]->owner == $sessionData["id"]) ? true : false,
                "create" => ($query[0]->create == 1 || $query[0]->owner == $sessionData["id"]) ? true : false,
                "upload" => ($query[0]->upload == 1 || $query[0]->owner == $sessionData["id"]) ? true : false,
                "edit_entries" => ($query[0]->edit_entries == 1 || $query[0]->owner == $sessionData["id"]) ? true : false,
                "edit_files" => ($query[0]->edit_files == 1 || $query[0]->owner == $sessionData["id"]) ? true : false,
                "edit_topic" => ($query[0]->edit_topic == 1 || $query[0]->owner == $sessionData["id"]) ? true : false,
                "delete_entries" => ($query[0]->delete_entries == 1 || $query[0]->owner == $sessionData["id"]) ? true : false,
                "delete_files" => ($query[0]->delete_files == 1 || $query[0]->owner == $sessionData["id"]) ? true : false,
            ];
        }
        return [];
    }

    function GetTopicPerms() {
        $topic = $this->request->getGet("topic");
        // Checks permissions
        $test = new TransferController();
        if ($test->CheckUserReadPermissions($topic) == false) {
            return $this->fail(["error" => "Not found!"], 404);
        }
        $db = Database::connect();
        $query = $db->query('CALL get_permissions_topic('.$db->escape($topic).')')->getResult();
        if (empty($query)) {
            return $this->respond([], 200);
        }
        return $this->respond($query[0], 200);
    }

    function UpdateTopicPerms() {
        if (empty($this->request->getRawInput())) {
            return $this->fail(["error" => "Not found!", "csrfHash" => csrf_hash()], 404);
        }
        // Checks permissions
        $perms = $this->GetUserPermissions($this->request->getRawInput()["topic"]);
        if (empty($perms)) {
            return $this->fail(["error" => "Not found!", "csrfHash" => csrf_hash()], 404);
        }
        if ($perms["owner"] == false) {
            return $this->fail(["error" => "You don't have the permission to do this!", "csrfHash" => csrf_hash()], 403);
        }
        // Checks data
        $db = Database::connect();
        $topic_id = $db->query('CALL get_topic_id('.$db->escape($this->request->getRawInput()["topic"]).')')->getResult();
        if (empty($topic_id)) {
            return $this->fail(["error" => "Not found!", "csrfHash" => csrf_hash()], 404);
        }
        $topic_id = $topic_id[0]->id;
        $perms = $this->request->getRawInput()["perms"];
        $sendData = [
            "public" => $this->request->getRawInput()["public"],
            "rd" => $perms[0],
            "crt" => $perms[1],
            "up" => $perms[2],
            "e_en" => $perms[3],
            "e_f" => $perms[4],
            "e_t" => $perms[5],
            "d_en" => $perms[6],
            "d_f" => $perms[7]
        ];
        $db->query('CALL put_topic_permissions('.$db->escape($topic_id).', '.$db->escape(json_encode($sendData)).')');
        return $this->respond(["message" => "Topic settings saved!", "csrfHash" => csrf_hash()], 200);
    }

    function GetUsers() {
        $topic = $this->request->getGet("topic");
        // Checks permissions
        $test = new TransferController();
        if ($test->CheckUserReadPermissions($topic) == false) {
            return $this->fail(["error" => "Not found!"], 404);
        }
        $db = Database::connect();
        $query = $db->query('CALL get_permissions_users('.$db->escape($topic).')')->getResult();
        $response = [];
        foreach ($query as $row) {
            $response[] = [
                "id" => $row->id,
                "username" => $row->username,
                "permissions" => [
                    "read" => ($row->read == 1) ? "Can visit the topic" : "",
                    "create" => ($row->create == 1) ? "Can create entries" : "",
                    "upload" => ($row->upload == 1) ? "Can upload files" : "",
                    "edit_entries" => ($row->edit_entries == 1) ? "Can edit entries" : "",
                    "edit_files" => ($row->edit_files == 1) ? "Can edit uploaded files" : "",
                    "edit_topic" => ($row->edit_topic == 1) ? "Can edit topic's main page" : "",
                    "delete_entries" => ($row->delete_entries == 1) ? "Can delete entries" : "",
                    "delete_files" => ($row->delete_files == 1) ? "Can delete uploaded files" : "",
                ]
            ];
        }
        return $this->respond($response, 200);
    }

    function PostUser() {
        if (empty($this->request->getPost())) {
            return $this->fail(["error" => "Where data?", "csrfHash" => csrf_hash()], 400);
        }
        // Checks permissions
        $perms = $this->GetUserPermissions($this->request->getPost("topic"));
        if (empty($perms)) {
            return $this->fail(["error" => "Not found!", "csrfHash" => csrf_hash()], 404);
        }
        if ($perms["owner"] == false) {
            return $this->fail(["error" => "You don't have the permission to do this!", "csrfHash" => csrf_hash()], 403);
        }
        // Checks data
        $db = Database::connect();
        $user_id = $db->query('CALL find_user_by_name('.$db->escape($this->request->getPost("user")).')')->getResult();
        if (empty($user_id)) {
            return $this->fail(["error" => "Username not found!", "csrfHash" => csrf_hash()], 404);
        }
        $topic_id = $db->query('CALL get_topic_id('.$db->escape($this->request->getPost("topic")).')')->getResult();
        if (empty($topic_id)) {
            return $this->fail(["error" => "Not found!", "csrfHash" => csrf_hash()], 404);
        }
        $perms = $this->request->getPost("perms");
        $sendData = [
            "topic_id" => $topic_id[0]->id,
            "user_id" => $user_id[0]->id,
            "rd" => $perms[0],
            "crt" => $perms[1],
            "up" => $perms[2],
            "e_en" => $perms[3],
            "e_f" => $perms[4],
            "e_t" => $perms[5],
            "d_en" => $perms[6],
            "d_f" => $perms[7]
        ];
        $db->query('CALL post_permissions('.$db->escape(json_encode($sendData)).')');
        return $this->respond(["message" => "Permissions given to the user!", "csrfHash" => csrf_hash()], 201);
    }

    function PutUser($perm_id) {
        if (empty($this->request->getRawInput())) {
            return $this->fail(["error" => "Where data?", "csrfHash" => csrf_hash()], 400);
        }
        $topic = $this->request->getRawInput()["topic"];
        // Checks permissions
        $perms = $this->GetUserPermissions($topic);
        if (empty($perms)) {
            return $this->fail(["error" => "Not found!", "csrfHash" => csrf_hash()], 404);
        }
        if ($perms["owner"] == false) {
            return $this->fail(["error" => "You don't have the permission to do this!", "csrfHash" => csrf_hash()], 403);
        }
        $perms = $this->request->getRawInput()["perms"];
        $sendData = [
            "rd" => $perms[0],
            "crt" => $perms[1],
            "up" => $perms[2],
            "e_en" => $perms[3],
            "e_f" => $perms[4],
            "e_t" => $perms[5],
            "d_en" => $perms[6],
            "d_f" => $perms[7]
        ];
        $db = Database::connect();
        $db->query('CALL put_permissions('.$db->escape($perm_id).', '.$db->escape(json_encode($sendData)).')');
        return $this->respond(["message" => "User permissions updated!", "csrfHash" => csrf_hash()], 200);
    }

    function DeleteUser($perm_id) {
        // Checks given data
        if (empty($perm_id)) {
            return $this->fail(["error" => "Where data?", "csrfHash" => csrf_hash()], 400);
        }
        // Checks permissions
        $perms = $this->GetUserPermissions($this->request->getRawInput()["topic"]);
        if (!empty($perms)) {
            if ($perms["owner"] == true) {
                // Deletes permission
                $db = Database::connect();
                $db->query('CALL delete_permissions('.$db->escape($perm_id).')');
                return $this->respond(["message" => "Removed successfully!", "csrfHash" => csrf_hash()], 200);
            }
        }
        return $this->fail(["error" => "You don't have the permission to do this!", "csrfHash" => csrf_hash()], 403);
    }
}