<?php

namespace App\Controllers;

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


class Checkin extends BaseController {

	private $model, $guestmodel, $sessionmodel;

	function __construct() {
		parent::__construct();
		$this->model = new CheckinModel();
		$this->guestmodel = new GuestModel();
		$this->sessionmodel = new SessionModel();
		$this->replacementmodel = new ReplacementModel();
		helper(['functions', 'twilio']);
	}

	public function guestSessionList($session_id) {
// 		$guests = $this->guestmodel->listAss("id", $session_id);  // Uncomment to take event-specific user functionality back
		$guests = $this->guestmodel->listAss("id"); // Comment to take event-specific user functionality back
		$checkin = $this->model->listAss($session_id, "guest_id");

		$result = array(
			"uninvited" => array(),
			"invited"   => array(),
			"accepted"  => array(),
			"rejected"  => array()
		);
		foreach($guests as $guest):
			if(!isset($checkin[$guest['id']]))
				$result['uninvited'][] = $guest['id'];
			elseif($checkin[$guest['id']]['status'] == "0")
				$result['invited'][] = $guest['id'];
			elseif($checkin[$guest['id']]['status'] == "1")
				$result['accepted'][] = $guest['id'];
			elseif($checkin[$guest['id']]['status'] == "2")
				$result['rejected'][] = $guest['id'];

		endforeach;
		$result['guests'] = $guests;
		$result['checkins'] = $checkin;
		return $result;
	}
	public function list($session_id) {

		$this->data['title'] = "Event - Checkin";
		$this->data['template'] = "checkin/list";
		$this->data['css_file'] = "session.css";

		$this->data['session_id'] = $session_id;
		
		$this->data['data'] = $this->guestSessionList($session_id);
		$this->data['replacement'] = $this->replacementmodel->findAll();	
		if($this->data['replacement'] == null) $this->data['replacement'] = array();


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

	public function checkin($session_id, $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('session/checkin/' . $session_id);
	}

	public function checkin_spot($session_id, $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('session/checkin/spot/' . $session_id);
	}
    
    public function checkinajax($session_id, $guest_id) {
		$data = [
			'checked_in' => "1", 
			'checked_in_date' => date('d-m-y h:i:s')
		];
		$this->model->where(['session_id' => $session_id, 'guest_id' => $guest_id])->set($data)->update();
		echo 0;
		exit;
	}
	public function checkoutajax($session_id, $guest_id) {
		$data = [
			'checked_in' => 0, 
			'checked_in_date' => null
		];
		$this->model->where(['session_id' => $session_id, 'guest_id' => $guest_id])->set($data)->update();
		echo 0;
		exit;
	}
    	
	public function remove($session_id, $guest_id) {
        $this->model->where(['session_id' => $session_id, 'guest_id' => $guest_id])->delete();
        $this->session->setFlashdata('msg', 'The status changed!');
        return redirect()->to('session/checkin/' . $session_id);
    }

    public function editstatus($session_id, $guest_id, $status) {
        $this->model->where(['session_id' => $session_id, 'guest_id' => $guest_id])->set(['status' => $status])->update();
        $this->session->setFlashdata('msg', 'The status changed!');
        return redirect()->to('session/checkin/' . $session_id);
    }

	public function acceptall($session_id) {
	    $this->model->where('session_id', $session_id)->set(['status' => 1])->update();

	    $checkins = $this->model->where('session_id', $session_id)->get()->getResultArray();
	    $existing = array_column($checkins, "guest_id");
	   // $guests = $this->guestmodel->where('event', $session_id)->get()->getResultArray();
	    $guests = $this->guestmodel->get()->getResultArray();
	    
	    foreach($guests as $guest) {
	    	if(!in_array($guest['id'], $existing)) {
		        $data = [
		            'session_id' => $session_id,
		            'guest_id'   => $guest['id'],
		            'status'     => 1,
		            'uuid'       => guidv4()
		        ];
		        $this->model->save($data);
		    }
	    }
		$this->session->setFlashdata('msg', 'All guests confirmed for this event.');
		return redirect()->to('session/checkin/' . $session_id);
	}

	public function accept($key, $id) {
		$checkin = $this->model->find($id);
		if($checkin != null && $key == $checkin['secret_key']) {
			$guest = $this->guestmodel->find($checkin['guest_id']);
				$data = [];
				if($checkin['status'] == 0) {
					$data['status'] = 1;
					$this->model->update($id, $data); 
				}
				$this->data['accept'] = true;
			$this->data['qr_uuid'] = uuid_qr($checkin['uuid']);
			echo view('checkin/response_' . $guest['lang'], $this->data);
		}
		exit;
	}
	public function reject($key, $id) {
		$checkin = $this->model->where(["id" => $id, "secret_key" => $key])->first();
		if($checkin != null) {
			$this->model->update($id, ['status' => 2, 'secret_key' => '']);
			$this->data['reject'] = true;
		} else {
			$this->data['expire'] = true;	
		}
		$this->data['qr_uuid'] = uuid_qr($checkin['uuid']);
		echo view('checkin/response', $this->data);
		exit;
	}
    
    public function inviteall($session_id) {
	    $this->model->where('session_id', $session_id)->delete();
	    $guests = $this->guestmodel->get()->getResultArray();
	    foreach($guests as $guest) {
	        $this->invite($session_id, $guest['id'], false);
	    }
		$this->session->setFlashdata('msg', 'All guests have been invited.');
		return redirect()->to('session/checkin/' . $session_id);
	}

	public function inviteselect($session_id, $status) {
		$guests = $this->request->getVar('invite');
		$guests = $guests[$status];

	    $this->model->where('session_id', $session_id)->whereIn('guest_id', $guests)->delete();
	    foreach($guests as $guest) {
	        $this->invite($session_id, $guest, false);
	    }
		$this->session->setFlashdata('msg', 'Selected guests have been invited.');
		return redirect()->to('session/checkin/' . $session_id);
	}
    
	public function invite($session_id, $guest_id, $redirect = true) { exit('Came In');
		$guest   = $this->guestmodel->find($guest_id);
		if(!filter_var($guest['email'], FILTER_VALIDATE_EMAIL)) {
			$this->session->setFlashdata('error', 'Invalid Email! The record skipped.');
		}
		if($guest == null) {

			$this->session->setFlashdata('error', 'The guest doesn\'t exist!');
        	return redirect()->to('session/' . $session_id);

		}


		$session = $this->sessionmodel->find($session_id);
		if($session == null) {

			$this->session->setFlashdata('error', 'The session doesn\'t exist!');
        	return redirect()->to('guests-list');

		}

		$checkin = $this->model->where(["session_id" => $session_id, "guest_id" => $guest_id])->first();
		$id = null;
		$key = bin2hex(random_bytes(32));
		$email = $error = false;

		$uuid = "";
		

		if($checkin == null) {
			$uuid = guidv4();
			$this->model->save(["session_id" => $session_id, "guest_id" => $guest_id, "uuid" => $uuid, "secret_key" => $key]);
			$id = $this->model->getInsertID();
			$email = true;
		} elseif($checkin['status'] != "1") {
			$uuid = $checkin['uuid'];
			$this->model->where(["session_id" => $session_id, "guest_id" => $guest_id])->set(["secret_key" => $key, "status" => 0])->update();
			$id = $checkin['id'];
			$email = true;
		}
        $qr_uuid = uuid_qr($uuid);
<<<<<<< HEAD
    
=======
>>>>>>> 87d1ac8f7909fc4a385638bd3d39089db3c456af
if ($email && $guest['email'] != "") {
	$guest['email'] = strtolower(trim($guest['email']));
    
    $img_path = 'assets/images/emails/';
   if($guest['category'] == 'VIP'){
   	$img_path .= 'vip/';
	} else {
	    $img_path .= 'normal/';
	}
	$img_path .= $guest['lang'] . '/';

    // Create an email object
    $email = new \SendGrid\Mail\Mail();

    // Set the sender's email and name
    $email->setFrom(getenv('SENDGRID_FROM'), getenv('SENDGRID_FROM_NAME'));
    $email->setReplyTo(getenv('SENDGRID_FROM'));

    // Set the recipient's email and name
    $email->addTo($guest['email'], $guest['name']);

    // Set the email subject
    $email->setSubject(getenv('SENDGRID_SUBJECT_' . $guest['lang']));

    // Set the email body (assuming you are using HTML content)
    $email->addContent("text/html", view("checkin/invite_email.php", array('id' => $id, 'key' => $key, "session" => $session, "guest" => $guest, "img_path" => $img_path, "qr_uuid" => $qr_uuid )));

    // 0000 c           

    if($guest['category'] != "VIP") {
	    $inline_attach = new \SendGrid\Mail\Attachment();
	    $inline_attach->setContent(base64_encode(file_get_contents(FCPATH . 'assets/images/invitation.png')));
	    $inline_attach->setType("image/png");
	    $inline_attach->setFilename("inviation_inline.png");
	    $inline_attach->setDisposition("inline");
	    $inline_attach->setContentId("invitation_normal");
	    $email->addAttachment($inline_attach);
	    

	    $attachment = new \SendGrid\Mail\Attachment();
	    $attachment->setContent($qr_uuid);
	    $attachment->setType("image/png");
	    $attachment->setFilename("qr2.png");
	    $attachment->setDisposition("attachment");
	    $email->addAttachment($attachment);
	    
	    
	    $attachment2 = new \SendGrid\Mail\Attachment();
	    $attachment2->setContent(base64_encode(file_get_contents(FCPATH . 'assets/images/invitation.png')));
	    $attachment2->setType("image/png");
	    $attachment2->setFilename("invitation.png");
	    $attachment2->setDisposition("attachment");
	    $email->addAttachment($attachment2);
	    
	    $attachment3 = new \SendGrid\Mail\Attachment();
	    $attachment3->setContent(base64_encode(file_get_contents(FCPATH . 'assets/images/invitation-arabic.png')));
	    $attachment3->setType("image/png");
	    $attachment3->setFilename("invitationarabic.png");
	    $attachment3->setDisposition("attachment");
	    $email->addAttachment($attachment3);
    }
    // Create a SendGrid client and send the email
    try {

        $sendGrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
        $response = $sendGrid->send($email);
    // print $response->statusCode() . "\n";
    // echo "<pre>"; print_r($response->headers()); echo "</pre>";
    // print $response->body() . "\n"; exit;

        if ($response->statusCode() == 202) {
            $this->session->setFlashdata('msg', 'Invitation sent!');
        } else {
            $this->session->setFlashdata('error', 'Email could not be sent. Status Code: ' . $response->statusCode());
        }
    } catch (Exception $e) {
        $this->session->setFlashdata('error', 'Email could not be sent. Error: ' . $e->getMessage());
    }
}



        $to = "whatsapp:+97477631967"; // Customer's WhatsApp number
        $body = <<<MSG
        You are cordially invited to the 2024 graduation ceremony of the Community College of Qatar.

        "يُسعدنا دعوتكم لحضور حفل تخرج كلية المجتمع في قطر لعام 2024."
MSG;
        $urls = array(
                 array('url' => 'https://graduation.zoomarts.com/public/assets/images/invitation.png', 'body' => 'You are cordially invited to the 2024 graduation ceremony of the Community College of Qatar.'),
                 array('url' => 'https://graduation.zoomarts.com/public/assets/images/invitation-arabic.png', 'body' => 'يُسعدنا دعوتكم لحضور حفل تخرج كلية المجتمع في قطر لعام 2024.'),
                 array('url' => 'https://quickchart.io/qr?text=' . $uuid, 'body' => 'Please use this QR Code to access the venue.')
             );

        // Send WhatsApp message
        echo "Guest: " . $guest['phone'] . "<br>";
        $message_sid = send_whatsapp_message($guest['phone'], $body, $urls);

        // if ($message_sid) {
        //     echo "WhatsApp message sent successfully. SID: " . $message_sid;
        // } else {
        //     echo "Failed to send WhatsApp message.";
        // } 

		if($redirect)
		    return redirect()->to('session/checkin/' . $session_id);
		
	}

	function qr_download($id) {

		$session_checkin = $this->model->find($id);

		if($session_checkin) {
			$qr_uuid = uuid_qr_bare($session_checkin['uuid']);
			$filename = "qr_" . $session_checkin['session_id'] . '_' . $session_checkin['guest_id'] . ".png";
			return $this->response->download($filename, $qr_uuid);
		}

	}

	function spot($session_id) {
		$this->data['session'] = $this->sessionmodel->find($session_id);
		$this->data['title'] = "Event: '" . $this->data['session']['title'] . "' - Checkin Spot";
		$this->data['template'] = "checkin/spot";
		$this->data['css_file'] = "session.css";

		$this->data['session_id'] = $session_id;
		
		if($uuid = $this->request->getVar('uuid')) {
			$checkin = $this->model->where('uuid', $uuid)->first();

			if($checkin) {
				$this->data['checkin'] = $checkin;
				$this->data['guest']   = $this->guestmodel->find($checkin['guest_id']);
			}
			else
				$this->data['error'] = "The UUID entered isn't valid.";
		}

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