<?php

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

class MainController extends ResourceController
{
    public function GoToPage($name = null) {
        return view($name.'.html');
    }

    public function GoToTicket() {
        return view('ticket_edit.html');
    }

    public function CheckSession() {
        /* session_start();
        if (!isset($_SESSION["user"])) {
            log_message("info", $_SESSION["user"]);
        }
        else {
            log_message("info", "nah");
        } */
    }

    public function LoggingIn() {
        $db = Database::connect();
        $query = $db->table("users")->select("*")->where("user", $this->request->getPost("user"))->where("pass", $this->request->getPost("pass"))->get()->getResult();
        if (!empty($query)) {
            /* session_start();
            $_SESSION["user"] = $query[0]->user;
            log_message("info", $_SESSION["user"]); */
            return "1";
        }
        else {
            return "0";
        }
    }

    public function ShowTickets($id = null, $user = null) {
        $db = Database::connect();
        $builder = $db->table("tickets");
        if ($id != 0) {
            $builder->select("*")->where("id", $id);
        }
        if ($user != 0) {
            $builder->select("id, name, status, created_at")->where("user_id", $id);
        }
        if ($user == 0 && $id == 0) {
            $builder->select("id, name, status, created_at");
        }
        $query = $builder->get();
        $response = [];
        foreach ($query->getResult() as $row) {
            $response[] = $row;
        }
        return $this->respond($response, 200);
    }

    public function SearchTickets() {
        $db = Database::connect();
        $query = $db->table("tickets")->select("id, name")->get()->getResult();
        $input = explode(" ", $this->request->getPost("input"));
        $foundTickets = [];
        foreach ($query as $row) {
            foreach(explode(" ", $row->name) as $part) {
                foreach($input as $word) {
                    if ($part == $word) {
                        $foundTickets[] = $row->name;
                    }
                }
            }
        }
        return $this->respond($foundTickets, 200);
    }

    public function CreateTicket() {
        $db = Database::connect();
        $builder = $db->table("tickets")->insert($this->request->getPost());
        return $this->respond("Ticket created succesfully!", 200);
    }

    public function UpdateTicket($id = null) {
        $db = Database::connect();
        $builder = $db->table("tickets")->where("id", $id)->update($this->request->getPost());
        return $this->respond("Ticket updated succesfully!", 200);
    }
}