<?php

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

class EntryController extends ResourceController
{
    public function GetEntries() {
        $db = Database::connect();
        $query = $db->table("entries")->select("*")->get();
        $responses = [];
        foreach ($query->getResult() as $row) {
            $responses[] = $row;
        }
        return $this->respond($responses, 200);
    }

    public function GetEntry($id = null) {
        $db = Database::connect();
        if (empty($id)) {
            return $this->fail(["error" => "Where data?"], 400);
        }
        $query = $db->query("CALL get_entry($id)");
        $responses = [];
        foreach ($query->getResult() as $row) {
            $responses[] = $row;
        }
        return $this->respond($responses, 200);
    }

    public function PostEntry($id = null) {
        $db = Database::connect();
        if (!empty($id)) {
            if (empty($this->request->getPost())) {
                return $this->fail(["error" => "Where data?"], 400);
            }
            $sendData = [
                "title" => htmlspecialchars($this->request->getPost("title")),
                "description" => htmlspecialchars($this->request->getPost("description")),
                "edited_at" => date("Y-m-d h:i:sa")
            ];
            $db->table("entries")->where("id", $id)->update($sendData);
            return $this->respond(["message" => "Updated successfully!"], 200);
        }
        else {
            if (empty($this->request->getPost())) {
                return $this->fail(["error" => "Where data?"], 400);
            }
            $sendData = [
                "user_id" => htmlspecialchars($this->request->getPost("user")),
                "title" => htmlspecialchars($this->request->getPost("title")),
                "description" => htmlspecialchars($this->request->getPost("description"))
            ];
            $db->table("entries")->insert($sendData);
            return $this->respond(["message" => "Created successfully!"], 201);
        }
    }

    public function DeleteEntry($id = null) {
        $db = Database::connect();
        if (empty($id)) {
            return $this->fail(["error" => "Where data?"], 400);
        }
        $db->table("entries")->where("id", $id)->delete();
        return $this->respond(["message" => "Deleted successfully!"], 200);
    }
}