<?php

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

class TopicController extends ResourceController
{
    /*
        Created: 2025-09-16
        Author: Kārlis Grīnvalds
        Last edited: 2025-11-26
        Edited by: Kārlis Grīnvalds
    */

    // Retrieves a certain topic, function parameter is topic name
    public function GetTopic($name = null) {
        $db = Database::connect();
        if (empty($name)) {
            return $this->fail(["error" => "Where data?"], 400);
        }
        $query = $db->query('CALL get_topic_by_name('.$db->escape($name).')');
        if (empty($query)) {
            return $this->fail(["error" => "Not found!"], 404);
        }
        $responses = [];
        foreach ($query->getResult() as $row) {
            $responses[] = [
                "id" => $row->id,
                "title" => $row->title,
                "content" => $row->content,
                "created_at" => $row->created_at,
                "edited_at" => $row->edited_at,
            ];
        }
        return $this->respond($responses, 200);
    }

    // Updates topic, function parameter is topic name
    public function UpdateTopic($name = null) {
        $db = Database::connect();
        if (empty($name)) {
            return $this->fail(["error" => "Topic name not given!"], 400);
        }
        $item = [];
        $session = service("session");
        if ($session->has("userdata")) {
            $item = $session->get("userdata")->id;
            $session->close();
        }
        else {
            $session->close();
            return $this->fail(["error" => "User not found!"], 404);
        }
        // Checks if posted data exists
        if (empty($this->request->getPost())) {
            return $this->fail(["error" => "Input fields are empty!"], 400);
        }
        $query = $db->query('CALL get_topic_for_put('.$db->escape($name).')');
        if (empty($query)) {
            return $this->fail(["error" => "Topic not found!"], 404);
        }
        $query = $query->getResult()[0];
        if ($item != $query->owner) {
            return $this->fail(["error" => "You can't use this!"], 404);
        }
        // Prepares data for updating
        $sendData = [
            "title" => $this->request->getPost("title"),
            "content" => $this->request->getPost("content")
        ];
        // Checks if the title isn't empty
        if (strlen($sendData["title"]) == 0) {
            return $this->fail(["error" => "Title was found empty! Do not use any HTML tags!"], 406);
        }
        $db->query('CALL put_topic('.$db->escape(json_encode($sendData)).', '.$db->escape($query->id).')');
        return $this->respond(["message" => "Updated successfully!"], 200);
    }
}