<?php

namespace App\Controllers;

use App\Libraries\UserAuth;
use App\Models\PurposeModel;
use App\Models\VisitorModel;
use App\Validation\VisitorValidation;
use Carbon\Carbon;
use CodeIgniter\Config\Services;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;

class VisitorController extends ResourceController
{
    protected $helpers = ['custom', 'form'];
    protected $model;
    protected PurposeModel $purposeModel;
    protected VisitorValidation $validation;

    public function __construct()
    {
        $this->model = new VisitorModel();
        $this->purposeModel = new PurposeModel();
        $this->validation = new VisitorValidation();
    }

    public function index()
    {
        $data = [
            'visitors' => $this->model->getVisitors(),
        ];

        return view("backend/visitors", $data);
    }

    /**
     * Create a new resource object, from "posted" parameters.
     *
     * @return ResponseInterface
     */
    public function create()
    {
        $validator = Services::validation($this->validation);
        $validator->setRuleGroup('validateVisitorOnCreation');

        if ($validator->withRequest($this->request)->run()) {
            $data = $validator->getValidated();
            $save = $this->model->save($data);

            if ($save) {
                return redirect('home')->with('success', 'Welcome to BetPawa, ' . join(' ', [$data['first_name'], $data['last_name']]));
            }
        }
        return redirect()->back()->withInput()->with('fail', 'Failed to save data. Try again');
    }

    public function signIn()
    {
        $purposes = ['' => '-- Select purpose of visit --'];
        $all_purposes = $this->purposeModel
            ->asObject()
            ->orderBy('purpose', 'asc')
            ->select(['id', 'purpose'])
            ->findAll();

        foreach ($all_purposes as $purpose) {
            $purposes[$purpose->id] = $purpose->purpose;
        }
        $data = [
            'purposes' => $purposes
        ];

        return view('frontend/sign_in', $data);
    }

    public function signout()
    {
        return view('frontend/sign_out');
    }
    public function search()
    {
        $html = '<div></div>';
        $request = $this->request->getPost();
        $visitors = $this->model->searchByLastName(trim($request['last_name']));
        if ($visitors) {
            $html = $this->buildHtml($visitors);
        }
        return $html;
    }
    public function buildHtml($visitors)
    {
        return view('frontend/search_results', ['visitors' => $visitors]);
    }

    public function visitorSignout($id = null)
    {
        $visitor = $this->model->asObject()->where('status', 'In')->find($id);
        if ($visitor) {
            $update = $this->model->update($id, ['status' => 'Out', 'signout_at' => Carbon::now()]);
            if ($update) {
                return redirect('home')->with('success', 'Signout was successful. Welcome again!');
            }
            return redirect()->back()->with('fail', 'Failed to signout. Please try again');
        }
        return redirect()->back()->with('fail', 'Something went wrong');
    }
    public function getNewVisitor()
    {

        $last_checked_time = UserAuth::getLastCheckedTime() ?: Carbon::now();

        $new_visitor = $this->model->getLatestVisitor($last_checked_time);

        UserAuth::setLastCheckedTime();

        if ($new_visitor) {
            $html = $this->buildNewVisitorHtml($new_visitor);
            return $html;
        }
    }
    public function buildNewVisitorHtml($visitor)
    {
        return view('backend/new_visitor_card', ['visitor' => $visitor]);
    }
}
