<?php

namespace App\Controllers;
use Config\Database;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Files\File;

class FilesController extends ResourceController
{
    /*
        Created: 2025-09-17
        Author: Kārlis Grīnvalds
        Last edited: 2025-11-05
        Edited by: Kārlis Grīnvalds
    */

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

    public function GetFile($topic = null, $fileName = null) {
        $db = Database::connect();
        if (empty($topic)) {
            return $this->fail(["error" => "Where data?"], 400);
        }
        $topic_id = $db->query('CALL get_topic_id('.$db->escape($topic).')')->getResult();
        if (empty($topic_id)) {
            return $this->fail(["error" => "Not found!"], 404);
        }
        $filePath = WRITEPATH."uploads/".$fileName;
        if (!is_file($filePath)) {
            return $this->fail(["error" => "Not found!"], 404);
        }
        return $this->response
                ->setHeader("Content-Type", mime_content_type($filePath))
                ->setHeader("Content-Length", filesize($filePath))
                ->setBody(file_get_contents($filePath));
    }

    public function GetFileInformation($fileName = null) {
        $db = Database::connect();
        if (empty($fileName)) {
            return $this->fail(["error" => "Where data?"], 400);
        }
        $query = $db->query('CALL get_topic_file('.$db->escape($fileName).')');
        $responses = [];
        if (!empty($query)) {
            foreach ($query->getResult() as $row) {
                $responses[] = [
                    "id" => $row->id,
                    "username" => $row->username,
                    "title" => $row->display_name,
                    "description" => $row->description,
                    "created_at" => $row->created_at,
                    "edited_at" => $row->edited_at,
                ];
            }
        }
        // Returns file data
        return $this->respond($responses, 200);
    }

    public function UploadFile() {
        $db = Database::connect();
        $item = []; // To get the user's id from session data
        // Checks if the user is logged in. If not, then this function doesn't continue
        $session = service("session");
        if ($session->has("userdata")) {
            $item = $session->get("userdata")->id;
            $session->close();
        }
        else {
            $session->close();
            return $this->fail(["error" => "Not found!"], 404);
        }
        // Checks if posted data exists
        if (empty($this->request->getPost())) {
            return $this->fail(["error" => "Where data?"], 400);
        }
        if (empty($this->request->GetFile("file"))) {
            return $this->fail(["error" => "Where file?"], 400);
        }
        
        $query = $db->query('CALL get_topic_id('.$db->escape($this->request->getPost("topic")).')')->getResult()[0];
        if (empty($query)) {
            return $this->fail(["error" => "Not found!"], 404);
        }
        $file = $this->request->GetFile("file");
        $newName = "";
        if ($file->isValid() && $file->getSize() > 0 && !$file->hasMoved()) {
            $newName = $file->getRandomName();
            $file->move(WRITEPATH."uploads", $newName);
        }
        else {
            return $this->fail(["error" => "Invalid file!"], 406);
        }
        $query = $db->query('CALL get_topic_id('.$db->escape($this->request->getPost("topic")).')')->getResult()[0];
        if (empty($query)) {
            return $this->fail(["error" => "Not found!"], 404);
        }
        // Prepares data for row insert
        $sendData = [
            "topic_id" => $query->id,
            "user_id" => $item,
            "file_name" => $newName,
            "display_name" => $this->request->getPost("name"),
            "description" => $this->request->getPost("description")
        ];
        $db->query('CALL post_file('.$db->escape(json_encode($sendData)).')');
        return $this->respond(["message" => "Uploaded successfully!"], 201);
    }

    public function UpdateFile() {
        // WIP
    }
}