<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Google\Cloud\Firestore\FirestoreClient;

class Template {

    protected $CI;

    public function __construct()
    {    
        $this->CI =& get_instance();
        $this->CI->load->library('session');
    }

    public function template_render($content, $data = NULL)
    {
        if (!$content) {
            return NULL;
        } else {
            $x = $this->CI->config->item('firebase_app_key');
            $firestore = new FirestoreClient([
                'projectId' => $this->CI->config->item('firebase_project_id'),
                'keyFile' => json_decode(file_get_contents($x), true)
            ]);
            $reportRef = $firestore->collection('Reports');
            $newReports = 0;
            $documents = $reportRef->documents();
            
            foreach ($documents as $document) {
                if ($document->exists()) {
                    $report = $document->data();
                    if ($report['isRead'] !== true) {
                        $newReports++;
                    }
                }
            }
            
            // Get user session data
            $session_data = $this->CI->session->userdata('session_data');
            $data['newReports'] = $newReports;
            $data['adminName'] = isset($session_data['name']) ? $session_data['name'] : 'Admin';
            $data['tailorType'] = isset($session_data['tailorType']) ? $session_data['tailorType'] : 'N/A';
            $data['profileImage'] = isset($session_data['u_image']) ? $session_data['u_image'] : base_url('assets/images/avatars/01.png');

            // Calculate Experience in Years
            if (isset($session_data['startDate']) && !empty($session_data['startDate'])) {
                $startDate = DateTime::createFromFormat('Y-m-d', $session_data['startDate']);
                $currentDate = new DateTime();
                $yearsExperience = $startDate ? $currentDate->diff($startDate)->y : 0;
            } else {
                $yearsExperience = 0;
            }
            $data['experienceYears'] = $yearsExperience;

            $this->template['header']  = $this->CI->load->view('header', $data, TRUE);
            $this->template['sidebar'] = $this->CI->load->view('sidebar', $data, TRUE);
            $this->template['topbar']  = $this->CI->load->view('topbar', $data, TRUE);
            $this->template['content'] = $this->CI->load->view($content, $data, TRUE);
            $this->template['footer']  = $this->CI->load->view('footer', $data, TRUE);
            
            return $this->CI->load->view('template', $this->template);
        }
    }
}
