<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\GuestModel;
use App\Models\SessionModel;
use App\Models\CheckinModel;
use App\Models\SeatingModel;
use App\Models\StageModel;
use App\Models\ReplacementModel;

class Guest extends BaseController {

	private $model, $sessionmodel;
	private $custom_config;

	function __construct() {
		parent::__construct();
		$this->model = new GuestModel();	
		$this->sessionmodel	= new SessionModel();
		$this->checkinmodel	= new CheckinModel();
		$this->seatingmodel	= new SeatingModel();
		$this->stagemodel	= new StageModel();
		$this->replacementmodel	= new ReplacementModel();
		$this->custom_config = new \Config\Custom();
	}

	public function bulk_upload() {
	    $this->data['events'] = $this->sessionmodel->get()->getResultArray();
		echo view('guest/bulk_upload', $this->data);
	}

	public function perform_bulk_upload() {

		$bulk_file = $this->request->getFile('upload');
      	if ($bulk_file->isValid()) {
      		$file_name = $bulk_file->getTempName();
      		$event = $this->request->getVar('event');
      		$handle = fopen($file_name, "r");
      		$header = array();
      		$first = true;
      		$added = $skipped = 0;
      		while (($row = fgetcsv($handle, 10000, ",")) != FALSE) {
      			if($first) {
      				$header = $row;
      				$first = false;
      				continue;
      			}
      			$result = array_combine($header, $row);

      			if(isset($result['id']))
      				unset($result['id']);

      			if(isset($result['created_at']))
      				unset($result['created_at']);
      				
      			if(isset($result['event']))
      				$result['event'] = $event;
      		$is_exist = $this->model->where(['title' => $result['title'],'name' => $result['name'], 'surname' => $result['surname'], 'designation' => $result['designation'], 'event' => $event, 'event_category' => $result['event_category']])->get();

      		if($is_exist->resultID->num_rows == 0) {
      			$this->model->save($result);
      			$added++;
      		} else {
      			$skipped++;
      		}

      		$this->session->setFlashdata('msg', "Records Added: " . $added . " Records Skipped: " . $skipped);
		        
		    }
		    return redirect()->to('/guests-list');
		}
	}

	public function reports_form() {
		helper(['form']);

		$this->data['countries'] = $this->custom_config->countries;
		$this->data['category'] = $this->custom_config->category;
		$this->data['event_category'] = $this->custom_config->event_category;
		$this->data['sessions']  = $this->sessionmodel->findAll();

		echo view('guest/reports', $this->data);
	}


	public function generate_report() {
		helper('download');
		$data = [
			'date_from' => $this->request->getVar('date_from'),
			'date_to' => $this->request->getVar('date_to'),
            'designation'    => $this->request->getVar('designation'),
            'country'    => $this->request->getVar('country'),
            'category'    => $this->request->getVar('category'),
            'event_category'    => $this->request->getVar('event_category'),
            'session_id'         => $this->request->getVar('session_id'),
            'seating'            => "",
            'stage'              => ''
        ];

        $result = $this->model->generate_report($data);
        $header = $this->model->getFieldNames('guest');
        $header[] = 'checkin_status';
        $header[] = 'seating';
        $header[] = 'stage';

        $filename = 'guests_'.date('Ymd').'.csv'; 
	    header("Content-Description: File Transfer"); 
	    header("Content-Disposition: attachment; filename=$filename"); 
	    header("Content-Type: application/csv; ");

	     // file creation 
	     $file = fopen('php://output', 'w');
	     fputcsv($file, $header);
	     foreach ($result as $key => $line){ 
	     	switch($line['checkin_status']) {
	     		case null:
	     			$line['checkin_status'] = "NOT INVITED";
	     			break;
	     		case '0':
	     			$line['checkin_status'] = "NOT REPONDED";
	     			break;
	     		case '1':
	     			$line['checkin_status'] = "ACCEPTED";
	     			break;
	     		case '2':
	     			$line['checkin_status'] = "DECLINED";	     				     			
	     			break;
	     	}
	        fputcsv($file,$line); 
	     }
	     fclose($file); 
	     exit; 
	}

	public function pub_add_guest_form($id = null) {
		helper(['form']);
		$this->data['id'] = $id;
		if($id) {
			$this->data['data'] = $this->model->find($id);
		}
		$this->data['countries'] = $this->custom_config->countries;
		$this->data['category'] = $this->custom_config->category;
		$this->data['event_category'] = $this->custom_config->event_category;
		$this->data['title'] = "Add Guest";
		$this->data['css_file'] = "add-guest.css";
		$this->data['template'] = "guest/add_guest";
		$this->data['pub'] = 1;
		echo view('layout_pub', $this->data);
		exit;
	}

	public function pub_thankyou($id = null) {
		helper(['form']);
		$this->data['id'] = $id;
		if($id) {
			$this->data['data'] = $this->model->find($id);
		}
		
		$this->data['title'] = "Guest Added - Thankyou";
		$this->data['css_file'] = "";
		$this->data['template'] = "guest/pub/thankyou";

		echo view('layout_pub', $this->data);
		exit;
	}

	public function add_guest_form($id = null, $replace = null, $session = null) {
		if($id === "null") $id = null;
		helper(['form']);
		$this->data['id'] = $id;
		if($id) {
			$this->data['data'] = $this->model->find($id);
		}

		if($replace) {
			$this->data['replace'] = $replace;
			$this->data['session'] = $session;

			if($this->checkinmodel->where(['session_id' => $session, 'guest_id' => $replace])->get()->getNumRows() <= 0) {
				$this->session->setFlashdata('error', 'The guest is not attached to the session!');
				return redirect()->to('session/checkin/spot/' . $session);
			}
		}
		$this->data['countries'] = $this->custom_config->countries;
		$this->data['category'] = $this->custom_config->category;
		$this->data['event_category'] = $this->custom_config->event_category;
		$this->data['events'] = $this->sessionmodel->get()->getResultArray();
		$this->data['title'] = "Add Guest";
		$this->data['css_file'] = "add-guest.css";
		$this->data['template'] = "guest/add_guest";

		echo view('layout', $this->data);
	}

	public function remove_guest($id) {
		$this->model->delete($id);
        $this->session->setFlashdata('msg', 'Guest Removed!');
        return redirect()->to('/guests-list');
	}
	public function guests_list() {
		helper(['form']);
		if($this->request->getVar('search') == "1") {
			$country = $this->request->getVar('country');
			$category = $this->request->getVar('category');
			$checkedIn = $this->request->getVar('checkedIn');

			if($country != "")
				$this->model->where('country', $country);

			if($category != "")
				$this->model->where('category', $category);

			if($checkedIn != "")
				$this->model->where('checked_in',$checkedIn);
		}
		
		$this->data['guests_list'] = $this->model->orderBy('id', 'ASC')->get()->getResultArray();
		
		$this->data['countries'] = $this->custom_config->countries;
		$this->data['category'] = $this->custom_config->category;
		$this->data['event_category'] = $this->custom_config->event_category;

		echo view('guest/guests_list', $this->data);
	}
	

	public function save() {
		 //include helper form
        helper(['form', 'functions']);

        $data = [
            'title'    => $this->request->getVar('title'),
            'name'     => $this->request->getVar('name'),
            'surname'    => $this->request->getVar('surname'),
            'email'    => $this->request->getVar('email'),
            'phone'    => $this->request->getVar('phone'),
            'designation'    => $this->request->getVar('designation'),
            'country'    => $this->request->getVar('country'),
            'company'    => $this->request->getVar('company'),
            'category'    => $this->request->getVar('category'),
            'event_category'    => $this->request->getVar('event_category'),
            'club'    => $this->request->getVar('club'),
            'event'    => $this->request->getVar('event'),
            'special_note'    => $this->request->getVar('special_note'),
            'lang'    => $this->request->getVar('lang'),
        ];


        $profile_image = $this->request->getFile('profile_image');
      	if ($profile_image->isValid()) {
			$name = session('id') . "_" . $profile_image->getRandomName();
			$profile_image->move( WRITEPATH . '../public/assets/images/profiles', $name);
			$data['profile_image'] = $name;
		}

        $id = $this->request->getVar('id');
        if(isset($id))
        	$this->model->update($id, $data);
      	else
      		$id = $this->model->insert($data);

      	$this->session->setFlashdata('msg', 'Guest added/updated!');
      	$redirect = "guests-list";
        
        if($this->request->getVar('submit_assign')) {
            $key = bin2hex(random_bytes(32));
            $uuid = guidv4();
			$this->checkinmodel->save(["session_id" => $this->request->getVar('event'), "guest_id" => $id, "uuid" => $uuid, "status" => 1, "checked_in" => 1, 'checked_in_date' => date('d-m-y h:i:s'), "secret_key" => $key]);
			$this->session->setFlashdata('msg', 'New guest added and checkedin!');
        }
        
      	if($this->request->getVar('pub'))
      		$redirect = "pub/guest/thankyou";
      	if($replace_id = $this->request->getVar('replace')) {
      		$session_id = $this->request->getVar('session');
      		$where = ['session_id' => $session_id, 'guest_id' => $replace_id];
      		$set = ['guest_id' => $id];
      		
      		$this->seatingmodel->where($where)->set($set)->update();
      		$this->stagemodel->where($where)->set($set)->update();
      		
      		if($this->request->getVar('submit_checkin'))
      			$set['checked_in'] = 1;

      		$this->checkinmodel->where($where)->set($set)->update();
      		$this->replacementmodel->save(['replaced' => $replace_id, 'replacing' => $id]);

      		$this->session->setFlashdata('msg', 'New guest added and the existing guest replaced!');
      		$redirect = "session/checkin/spot/" . $session_id;

      	}
        return redirect()->to($redirect);
	}

	public function check_in($id) {
		$data = [
			'checked_in' => "1", 
			'checked_in_date' => date('d-m-y h:i:s')
		];
		$this->model->update($id, $data);
		$this->session->setFlashdata('msg', 'Selected guest marked checked in!');
		return redirect()->to('/guests-list');
	}
}