<?php

namespace App\Controllers;

// Ambil 3 Tabel BUGS, BUGS_COMMENT, USERS
use App\Models\BugsModel;
use App\Models\UsersModel;
use App\Models\BugCommentModel;

use CodeIgniter\Controller;

class Bugs extends Controller {
	
	protected array $data;
	
	function __construct() {
		$this->data['bugpriorities'] = array('0'=>'Low', '1'=> 'Medium', '2' => 'High');
	}

	// Melihat dan membuat Thread Bugs
	public function index() {
		$db = \Config\Database::connect();
		$sql = "SELECT b.bugid, b.bugtitle, b.bugstatus, b.reportdate, b.bugpriority, 
				u.firstname AS creator_firstname, u.lastname AS creator_lastname, 
				(SELECT MAX(logdate) FROM bugcomment WHERE bugid=b.bugid) as buglastcommentdate, 
				(select count(*) from bugcomment where bugid=b.bugid ) as bugcommentcount
			FROM bugs b 
			LEFT JOIN users u ON b.userid_creator = u.userid
			ORDER BY CASE 
				WHEN b.bugstatus='O' THEN 1 
				WHEN b.bugstatus='P' THEN 2
				WHEN b.bugstatus='S' THEN 3 
				WHEN b.bugstatus='A' THEN 4
				WHEN b.bugstatus='C' THEN 5
				ELSE 6 END, 
			b.bugpriority DESC, b.reportdate ASC, b.closedate DESC";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['bugs'] = $results;
		$data['bugpriorities'] = $this->data['bugpriorities'];
		return view('bugs_index', $data);
	}

	public function edit($bugid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM bugs WHERE bugid='$bugid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['bugs'] = $results;
		$data['bugpriorities'] = $this->data['bugpriorities'];
		if ($this->request->getMethod() === 'POST') {
			if ($this->request->getMethod() === 'POST') {
				$rules = [
					'bugtitle' => 'required',
					'bugdetail' => 'required',
				];
				$data['new_value'] = [
					'bugtitle' => $this->request->getVar('bugtitle'),
					'bugdetail'	=> $this->request->getVar('bugdetail'),
					'bugstatus'	=> $this->request->getVar('bugstatus'),
					'bugpriority' => $this->request->getVar('bugpriority'),
				];

				if($this->validate($rules)){
					$bugsModel = new BugsModel();
					$bugsModel->update($bugid, $data['new_value']);
					return view('form_success');
				} else {
					$data['validation'] = $this->validator;
					return view('bugs_edit', $data);
				}
			}
		}
		return view('bugs_edit', $data);
	}

	// Fungsi Membuat Thread Bugs Baru pada Jendela Baru
	public function create() {
		$data['bugpriorities'] = $this->data['bugpriorities'];
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'bugtitle' => 'required',
				'bugdetail' => 'required',
			];
			$data['new_value'] = [
				'bugtitle' => $this->request->getVar('bugtitle'),
				'bugdetail'  => $this->request->getVar('bugdetail'),
				'bugstatus' => $this->request->getVar('bugstatus'),
				'bugpriority' => $this->request->getVar('bugpriority'),
				'userid_creator'  => $this->request->getVar('userid_creator'),		
			];
			if($this->validate($rules)){
				$bugsModel = new BugsModel();
				$bugsModel->set('reportdate', 'NOW()', FALSE);
				$bugsModel->insert($data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('bugs_create', $data);
			}
		}
		return view('bugs_create', $data);
	}

	// Fungsi Untuk melihat Thread Bugs dan Melihat/Memberi Komentar pada suatu Threads
	public function view($bugid = null) {
		$data = array();

		//Connect Data base
		$db = \Config\Database::connect();

		// Get BUGS
		$sql = "SELECT b.*, u.firstname, u.lastname, u.userid
			FROM bugs b
			JOIN users u
			ON b.userid_creator = u.userid
			WHERE bugid=$bugid";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['bugs'] = $results;

		// Get Comments BUGS
		$sql = "SELECT bc.*, u.firstname, u.lastname, u.userid
			FROM bugcomment bc
			JOIN users u
			ON bc.userid = u.userid
			WHERE bc.bugid=$bugid";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['bugcomment'] = $results;

		// Button send Comment
		if( isset($_POST['send_comment']) ) {
			if ($this->request->getMethod() === 'POST') {

				$rules = [
					'bugcommenttext' => 'required'
				];
				$data['new_value'] = [
					'bugcommenttext' => $this->request->getVar('bugcommenttext'),
					'bugid' => $this->request->getVar('bugid'),
					'userid' => $this->request->getVar('userid'),
				];
				
				if($this->validate($rules)){
					$bugCommentModel = new BugCommentModel();
					$bugCommentModel->set('logdate', 'NOW()', FALSE);
					$bugCommentModel->insert($data['new_value']);
					return redirect()->to('/bugs/view/'.$bugid);
				} else {
					$data['validation'] = $this->validator;
					return view('bugs_view',$data);
				}
			}

		// Button send Comment and mark as done
		} else if ( isset($_POST['send_comment_and_done']) ) {

			if ($this->request->getMethod() === 'POST') {

				$rules = [
					'bugcommenttext' => 'required'
				];
				$data['new_value'] = [
					'bugcommenttext' => $this->request->getVar('bugcommenttext'),
					'bugid' => $this->request->getVar('bugid'),
					'userid' => $this->request->getVar('userid'),
				];
				
				if($this->validate($rules)){
				
					// Bugs Comment Insert
					$bugCommentModel = new BugCommentModel();
					$bugCommentModel->set('logdate', 'NOW()', FALSE);
					$bugCommentModel->insert($data['new_value']);

					// Bugs Update
					$bugsModel = new BugsModel();
					$bugsModel->set('bugstatus', 'C');
					$bugsModel->set('userid_closer', $_SESSION['userid']);
					$bugsModel->set('closedate', 'NOW()', FALSE);
					$bugsModel->where('bugid', $bugid);
					$bugsModel->update();

					echo "<script>window.close();</script>";

				} else {
					$data['validation'] = $this->validator;
					return view('bugs_view',$data);
				}
			}
		}

		return view('bugs_view', $data);
	}

	// Fungsi Untuk Delete Pada BUGS
	// public function delete($bugid = 0) {

	// 	$db = \Config\Database::connect();
	// 	$sql = "DELETE FROM bugs 
	// 			WHERE bugid = '$bugid'";
	// 	if($db->query($sql)) { 
	// 		return view('form_success'); 
	// 		// return redirect()->to('/bugs');
	// 	} else { 
	// 		return view('form_fail'); 
	// 	}		
	// }

	// Fungsi Untuk Mark As Done Pada BUGS
	public function toggle_close($bugid = 0) {

		$userid = $_SESSION['userid'];

		$db = \Config\Database::connect();
		$sql = "UPDATE bugs SET 
				bugstatus = 'C', 
				userid_closer = '$userid', 
				closedate = NOW() 
				WHERE bugid = '$bugid'";
		if($db->query($sql)) { 
			return view('form_success'); 
			// return redirect()->to('/bugs');
		} else { 
			return view('form_fail'); 
		}		
	}

	public function toggle_pending($bugid = 0) {

		$userid = $_SESSION['userid'];

		$db = \Config\Database::connect();
		$sql = "UPDATE bugs SET 
				bugstatus = 'P'
				WHERE bugid = '$bugid'";
		if($db->query($sql)) { 
			return view('form_success'); 
			// return redirect()->to('/bugs');
		} else { 
			return view('form_fail'); 
		}		
	}

	public function toggle_reopen($bugid = 0) {

		$userid = $_SESSION['userid'];

		$db = \Config\Database::connect();
		$sql = "UPDATE bugs SET 
				bugstatus = 'O', 
				userid_closer = NULL, 
				closedate = NULL 
				WHERE bugid = '$bugid'";
		if($db->query($sql)) { 
			return view('form_success'); 
			// return redirect()->to('/bugs');
		} else { 
			return view('form_fail'); 
		}		
	}

	public function toggle_suspend($bugid = 0) {

		$userid = $_SESSION['userid'];

		$db = \Config\Database::connect();
		$sql = "UPDATE bugs SET 
				bugstatus = 'S'
				WHERE bugid = '$bugid'";
		if($db->query($sql)) { 
			return view('form_success'); 
			// return redirect()->to('/bugs');
		} else { 
			return view('form_fail'); 
		}		
	}

	public function toggle_archive($bugid = 0) {

		$userid = $_SESSION['userid'];

		$db = \Config\Database::connect();
		$sql = "UPDATE bugs SET 
				bugstatus = 'A', 
				userid_closer = NULL, 
				closedate = NULL 
				WHERE bugid = '$bugid'";
		if($db->query($sql)) { 
			return view('form_success'); 
			// return redirect()->to('/bugs');
		} else { 
			return view('form_fail'); 
		}		
	}

	public function count(){
		$db = \Config\Database::connect();
		$data = array();
		if ($this->request->getMethod() === 'POST') {
			$startdate = $this->request->getPost('startdate');
			$enddate = $this->request->getPost('enddate');
			$sql = "select u.`userid`, u.firstname, u.lastname,
				(select count(bugid) from bugs where userid_creator=u.userid and reportdate between '$startdate 00:00' and '$enddate 23:59') as bugopen,
				(SELECT COUNT(bugid) FROM bugs WHERE userid_creator=u.userid and bugstatus='C' AND reportdate between '$startdate 00:00' and '$enddate 23:59') as bugclose,
				(SELECT COUNT(bugid) FROM bugs WHERE userid_closer=u.userid AND reportdate between '$startdate 00:00' and '$enddate 23:59') as bugcloser,
				( SELECT COUNT(bugcommentid) FROM bugcomment bc 
					left join bugs b on bc.bugid=b.bugid and b.reportdate between '$startdate 00:00' and '$enddate 23:59'
					WHERE bc.userid=u.userid ) 
					as bugcomment
				from users u";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['count'] = $results;
        }
		return view('bugs_count', $data);
	}
}