<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

//settings & Authetication
use App\Models\UserAuthGroupModel;
use App\Models\UserAuthOtpModel;
use App\Models\AuthLoginModel;
use App\Models\UserAuthTokenModel;
use App\Models\UserActivateTokensModel;
use App\Models\UserActivationAttemptsModel;
use App\Models\UserResetsAttemptsModel;
use App\Models\UsersModel;
use App\Models\NotificationsModel;
use App\Models\EmailsModel;
use App\Models\CountryModel;
use App\Models\StateModel;
use App\Models\CityModel;
use App\Models\CountryStateCityModel;
use App\Models\CurrencyModel;
use Modules\Settings\Models\UserGroupsModel;
use Modules\Settings\Models\PermissionsModel;
use Modules\Settings\Models\UserPermissionsModel;
use Modules\Settings\Models\UserGroupPermissionsModel;
use Modules\Settings\Models\CompanySettingsModel;
use Modules\Settings\Models\PolicySettingsModel;
use Modules\Settings\Models\PaymentGatewaysModel;
use Modules\Settings\Models\PaymentMethodsModel;
use Modules\Settings\Models\ModuleSectionModel;

//Districts
use Modules\AdministrativeUnits\Models\DistrictModel;
use Modules\AdministrativeUnits\Models\VillageModel;
use Modules\AdministrativeUnits\Models\CountyModel;
use Modules\AdministrativeUnits\Models\SubcountyModel;
use Modules\AdministrativeUnits\Models\ParishModel;


//Posts & Pages
use Modules\Posts\Models\PostsModel;
use Modules\Posts\Models\PostsCategoryModel;
use Modules\Posts\Models\PostCommentsModel;
use Modules\Posts\Models\PostBlocksModel;
use Modules\Posts\Models\PostBlockItemsModel;
use Modules\Posts\Models\TagsModel;
use Modules\Posts\Models\PostTagsModel;

//REDD
use Modules\Redd\Models\ActivitiesModel;
use Modules\Redd\Models\CarbonPoolsModel;
use Modules\Redd\Models\ClientsModel;
use Modules\Redd\Models\EntityTypesModel;
use Modules\Redd\Models\MethodologiesModel;
use Modules\Redd\Models\GasesModel;
use Modules\Redd\Models\StatusModel;
use Modules\Redd\Models\TypesModel;
use Modules\Redd\Models\ForestsModel;
use Modules\Redd\Models\ProjectsModel;
use Modules\Redd\Models\ProjectGasesModel;
use Modules\Redd\Models\ProjectMethodologiesModel;
use Modules\Redd\Models\ProjectCarbonPoolsModel;
use Modules\Redd\Models\ProjectActivitiesModel;
use Modules\Redd\Models\ProjectStatusModel;
use Modules\Redd\Models\ProjectTypesModel;
use Modules\Redd\Models\ProjectCarbonDataModel;

//Menus
use Modules\Menu\Models\MenusModel;
use Modules\Menu\Models\MenusCategoryModel;

//sliders
use Modules\Sliders\Models\SlidersCategoryModel;
use Modules\Sliders\Models\SlidersModel;

//Team
use Modules\Team\Models\TeamModel;
use Modules\Team\Models\TeamCategoryModel;
use Modules\Team\Models\TeamMemberGalleryModel;


//Downlaods
use Modules\Downloads\Models\DownloadsCategoryModel;
use Modules\Downloads\Models\DownloadsModel;
use Modules\Downloads\Models\DownloadsTagsModel;

//ADs
use App\Models\BannersModel;

//Website
use App\Models\WebTrafficModel;

//Support
use CodeIgniter\I18n\Time;


/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 */
abstract class BaseController extends Controller
{
    /**
     * Instance of the main Request object.
     *
     * @var CLIRequest|IncomingRequest
     */
    protected $request;

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = [];
    protected $data = []; // Set default data array

    /**
     * Be sure to declare properties for any property fetch you initialized.
     * The creation of dynamic property is deprecated in PHP 8.2.
     */
    // protected $session;
    public $emailsModel;
    public $currencyModel;
    public $registerModel;
    public $usersModel;
    public $userauthgroupModel;
    public $authloginModel;
    public $userauthotpModel;
    public $userauthtokenModel;
    public $userresetsattemptsModel;
    public $useractivationattemptsModel;
	public $permissionsModel;
    public $usergroupsModel;
	public $userpermissionsModel;
	public $usergrouppermissionsModel;
    public $paymentgatewaysModel;
    public $paymentmethodsModel;
    public $policysettingsModel;
    public $companysettingsModel;
    public $modulesectionModel;
	public $departmentModel;
	public $countryModel;
	public $stateModel;
	public $cityModel;
	public $notificationsModel;
	public $productModel;
	public $productcategoryModel;
	public $customerModel;

    public $activitiesModel;
    public $carbonpoolsModel;
    public $clientsModel;
    public $entitytypesModel;
    public $methodologiesModel;
    public $projectsModel;
    public $gasesModel;
    public $statusModel;
    public $typesModel;
    public $forestsModel;
    public $projecttypesModel;
    public $projectgasesModel;
    public $projectmethodologiesModel;
    public $projectcarbonPoolsModel;
    public $projectactivitiesModel;
    public $projectstatusModel;
    public $projectcarbondataModel;

    public $districtModel;
    public $villageModel;
    public $countyModel;
    public $subcountyModel;
    public $parishModel;

    public $menuscategoryModel;
    public $menusModel;

    public $downloadscategoryModel;
    public $downloadsModel;
    public $downloadstagsModel;

    public $postscategoryModel;
    public $postsModel;
    public $postblocksModel;
    public $postblockitemsModel;
    public $tagsModel;
    public $posttagsModel;
    public $postcommentsModel;
	
    public $sliderscategoryModel;
    public $slidersModel;
    public $bannersModel;



    /**
     * @return void
     */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        // Preload any models, libraries, etc, here.

        // E.g.: $this->session = \Config\Services::session();
        $this->validation 				= \Config\Services::validation();
		$this->session 					= \Config\Services::session();
		$this->pager 				 	= \Config\Services::pager();
        $this->usersModel               = new UsersModel();
		$this->userauthgroupModel       = new UserAuthGroupModel();
        $this->authloginModel           = new AuthLoginModel();
        $this->userauthotpModel         = new UserAuthOtpModel();
        $this->userauthtokenModel       = new UserAuthTokenModel();
        $this->useractivationattemptsModel = new UserActivationAttemptsModel();
        $this->userresetsattemptsModel  = new UserResetsAttemptsModel();
		$this->notificationsModel		= new NotificationsModel();
		$this->emailsModel				= new EmailsModel();
		$this->countryModel 			= new CountryModel();
		$this->stateModel				= new StateModel();
		$this->cityModel				= new CityModel();
        $this->currencyModel 			= new CurrencyModel();

        $this->districtModel 			= new DistrictModel();
        $this->countyModel 				= new CountyModel();
        $this->subcountyModel 			= new SubcountyModel();
        $this->parishModel 				= new ParishModel();
        $this->villageModel 			= new VillageModel();

        $this->permissionsModel			= new PermissionsModel();
        $this->usergroupsModel          = new UserGroupsModel();
        $this->userpermissionsModel		= new UserPermissionsModel();
        $this->usergrouppermissionsModel = new UserGroupPermissionsModel();
        $this->paymentgatewaysModel     = new PaymentGatewaysModel();
        $this->paymentmethodsModel	    = new PaymentMethodsModel();
        $this->policysettingsModel	    = new PolicySettingsModel();
        $this->companysettingsModel	    = new CompanySettingsModel();
        $this->modulesectionModel       = new ModuleSectionModel();

        $this->activitiesModel          = new ActivitiesModel();
        $this->carbonpoolsModel         = new CarbonPoolsModel();
        $this->clientsModel             = new ClientsModel();
        $this->entitytypesModel         = new EntityTypesModel();
        $this->methodologiesModel       = new MethodologiesModel();
        $this->projectsModel            = new ProjectsModel();
        $this->gasesModel               = new GasesModel();
        $this->statusModel              = new StatusModel();
        $this->typesModel               = new TypesModel();
        $this->projecttypesModel        = new ProjectTypesModel();
        $this->projectgasesModel        = new ProjectGasesModel();
        $this->projectmethodologiesModel = new ProjectMethodologiesModel();
        $this->projectcarbonpoolsModel  = new ProjectCarbonPoolsModel();
        $this->projectactivitiesModel   = new ProjectActivitiesModel();
        $this->forestsModel             = new ForestsModel();
        $this->projectstatusModel       = new ProjectStatusModel();
        $this->projectcarbondataModel   = new ProjectCarbonDataModel();

        $this->menusModel               = new MenusModel();
        $this->menuscategoryModel       = new MenusCategoryModel();      
		
		$this->postsModel               = new PostsModel();
        $this->postscategoryModel       = new PostsCategoryModel();
        $this->tagsModel                = new TagsModel();
        $this->posttagsModel            = new PostTagsModel();
        $this->postcommentsModel        = new PostcommentsModel();
        $this->postblocksModel          = new PostBlocksModel();
        $this->postblockitemsModel      =  new PostBlockItemsModel();

        $this->downloadscategoryModel     = new DownloadsCategoryModel();
        $this->downloadsModel             = new DownloadsModel();
        $this->downloadstagsModel         = new DownloadsTagsModel();

        $this->sliderscategoryModel     = new SlidersCategoryModel();
        $this->slidersModel             = new SlidersModel();
        $this->bannersModel             = new BannersModel();

        $this->teamModel                = new TeamModel();
        $this->teamcategoryModel        = new TeamCategoryModel();
	    $this->teammembergalleryModel   = new TeamMemberGalleryModel();

        $this->webtrafficModel          = new WebTrafficModel();

        $this->data['districts']    = $this->districtModel->findAll();
    }
    
	//Generating Unique ID Number
    function generateUniqueId() {
        $uniqueId = '';
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $dashPositions = array(8, 13, 18, 23);
        
        for ($i = 0; $i < 32; $i++) {
          $uniqueId .= $characters[rand(0, strlen($characters) - 1)];
        }
        
        foreach ($dashPositions as $pos) {
          $uniqueId = substr_replace($uniqueId, '-', $pos, 0);
        }
        
        return $uniqueId;
    }

	function GUID()
	{
        if (function_exists('com_create_guid') === true)
        {
            return trim(com_create_guid(), '{}');
        }

        return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
	}

    function generatePassword($length = 15) {
        $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $password = "";
        $charsetLength = strlen($charset);
    
        for ($i = 0; $i < $length; $i++) {
            $randomIndex = rand(0, $charsetLength - 1);
            $password .= $charset[$randomIndex];
        }
    
        return $password;
    }

     
    
    //Email Successful Login
    function successfulLogin($id, $browser, $ip)
    {
        $email = \Config\Services::email();
        $checkUser = $this->usersModel->where('id', $id)->first($id);
        $clientName =  $checkUser['first_name'].' '.$checkUser['last_name'];

        //Sending Email
        $emailTemplate = view('email_templates/login_notification_template', [
            'clientName'    => $clientName,
            'browser'       => $browser,
            'ip'            => $ip,
        ]);
        $email->setMailType('html');
        $email->setFrom('no-reply@lukhwells.com', 'UGA REDD+');
        $email->setTo($checkUser['email']);
        $email->setSubject( 'New login on your UGA REDD+ account');
        $email->setMessage($emailTemplate);
        if ($email->send()) {
            return true;
        } else {
            return false;
        }
    }

    //Get Browser details
    function getBrowser()
    {
        $u_agent = $_SERVER['HTTP_USER_AGENT'];
        $bname = 'Unknown';
        $platform = 'Unknown';
        $version= "";

        if (preg_match('/linux/i', $u_agent)) {
            $platform = 'linux';
        } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
            $platform = 'mac';
        } elseif (preg_match('/windows|win32/i', $u_agent)) {
            $platform = 'windows';
        }

        if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) 
        { 
            $bname = 'Internet Explorer'; 
            $ub = "MSIE"; 
        } 
        elseif(preg_match('/Firefox/i',$u_agent)) 
        { 
            $bname = 'Mozilla Firefox'; 
            $ub = "Firefox"; 
        } 
        elseif(preg_match('/Chrome/i',$u_agent)) 
        { 
            $bname = 'Google Chrome'; 
            $ub = "Chrome"; 
        } 
        elseif(preg_match('/Safari/i',$u_agent)) 
        { 
            $bname = 'Apple Safari'; 
            $ub = "Safari"; 
        } 
        elseif(preg_match('/Opera/i',$u_agent)) 
        { 
            $bname = 'Opera'; 
            $ub = "Opera"; 
        } 
        elseif(preg_match('/Netscape/i',$u_agent)) 
        { 
            $bname = 'Netscape'; 
            $ub = "Netscape"; 
        } 
        
        return $bname;
    }

    //Get IP Address Location
    function getLocationFromIP($ip)
    {
        $apiKey = env('IPGEO_API_KEY');
        if (!$apiKey) {
            return '';
        }

        $url = "https://api.ipgeolocation.io/ipgeo?apiKey={$apiKey}&ip=" . urlencode((string) $ip);

        // Use a short timeout to avoid blocking requests
        $context = stream_context_create([
            'http' => [
                'method'  => 'GET',
                'timeout' => 3,
            ],
            'ssl' => [
                'verify_peer'      => true,
                'verify_peer_name' => true,
            ],
        ]);

        $response = @file_get_contents($url, false, $context);
        if ($response === false) {
            return '';
        }

        $data = json_decode($response, true);
        if (!is_array($data)) {
            return '';
        }

        $country = $data['country_name'] ?? '';
        $state   = $data['state_prov'] ?? '';
        return trim($country . (strlen($country) && strlen($state) ? ', ' : '') . $state);
    }

    
    //Email Token for Account Activation
    function sendTokenEmail($clientEmail, $token)
    {
        $email = \Config\Services::email();
        $checkUser = $this->usersModel->where('email', $clientEmail)->first($clientEmail);
        $clientName =  $checkUser['first_name'].' '.$checkUser['last_name'];

        //Sending Email
        $emailTemplate = view('email_templates/account_activation_template', [
            'clientName'    => $clientName,
            'clientEmail'   => $clientEmail,
            'tokenUrl'      => base_url('account/activation/'.$token),
        ]);
        $email->setMailType('html');
        $email->setFrom('no-reply@lukhwells.com', 'UGA REDD+ Administrator');
        $email->setTo($clientEmail);
        $email->setSubject( 'Account Activation Link - UGA REDD+');
        $email->setMessage($emailTemplate);
        if ($email->send()) {
            return true;
        } else {
            return false;
        }
    }

    //Email OTP
    function sendOtpEmail($clientEmail, $otp)
    {
        $email = \Config\Services::email();
        $checkUser = $this->usersModel->verifyEmail($clientEmail);
        // Support both array and object shapes
        if (is_array($checkUser)) {
            $first = $checkUser['first_name'] ?? '';
            $last  = $checkUser['last_name'] ?? '';
        } elseif (is_object($checkUser)) {
            $first = $checkUser->first_name ?? '';
            $last  = $checkUser->last_name ?? '';
        } else {
            $first = $last = '';
        }
        $clientName = trim($first . ' ' . $last);

        //Sending Email
        $emailTemplate = view('email_templates/otp_login_template', [
            'clientName'    => $clientName,
            'otp'           => $otp,
        ]);
        $email->setMailType('html');
        $email->setFrom('no-reply@lukhwells.com', 'UGA REDD+ Administrator');
        $email->setTo($clientEmail);
        $email->setSubject( 'Your One-time password (OTP) Login Code');
        $email->setMessage($emailTemplate);
        if ($email->send()) {
            return true;
        } else {
            return false;
        }
    }

    // Helper function to send notifications to admins
	public function sendAdminNotifications($message, $notificationType, $created_by)
	{
		$admins = $this->usersModel->getAdminUsers();
		foreach ($admins as $admin) {
			$this->notificationsModel->save([
				'message'           => $message,
				'receiver_id'       => $admin->id,
				'notification_type' => $notificationType,
				'created_by'        => $created_by,
			]);
		}
	}

    //Uzer Notification 
    function sendUserNotifications($message, $notificationType, $created_by)
    {
        $this->notificationsModel->save([
			'message'           => $message,
			'receiver_id'       => $created_by,
			'notification_type' => $notificationType,
			'receiver_type'		=> 'client',
			'created_by'        => $created_by,
		]);
    } 
    //Email for New data Entry can be Event, Member or any Other to Admin
    function sendNewEntryEmail($typeEntry, $activityName, $createdAt, $createdBy)
    {
        $email = \Config\Services::email();

        //Sending Email
        $emailTemplate = view('email_templates/new_event_activity_template', [
			'typeEntry'		  => $typeEntry,
            'activityName'    => $activityName,
            'createdAt'       => $createdAt,
            'createdBy'       => $createdBy, 
        ]);
        $email->setMailType('html');
        $email->setFrom(env('EMAIL_FROM_ADDRESS'), env('EMAIL_FROM_NAME'));
        $email->setTo(explode(',', env('EMAIL_TO_ADDRESSES')));
        $email->setSubject( '['.date('jS/m/Y', strtotime($createdAt)).'] New '.$typeEntry.' Created - Your ICT Magazine System');
        $email->setMessage($emailTemplate);
        if ($email->send()) {
            return true;
        } else {
            return false;
        }
    }
    
    function sendNewMemberEmail($memberName, $memberEmail)
    {
        $loginLink = 'https://lukhwells.com/member/login';
        $registrationDate = date('Y-m-d H:i:s');

        $email = \Config\Services::email();

        //Sending Email - USER
        $emailTemplate = view('email_templates/new_member_email_template', [
			'memberName'        => $memberName,
            'loginLink'         => $loginLink,
        ]);
        $email->setMailType('html');
        $email->setFrom(env('EMAIL_FROM_ADDRESS'), env('EMAIL_FROM_NAME'));
        $email->setTo($memberEmail);
        $email->setSubject( 'Your UGA REDD+ Registration is Pending Approval');
        $email->setMessage($emailTemplate);
        if ($email->send()) {
            return true;
        } else {
            return false;
        }

    }
    function emailAdminAboutNewMember($memberName, $memberEmail)
    {
        $loginLink = 'https://lukhwells.com/member/login';
        $registrationDate = date('Y-m-d H:i:s');

        //$email = \Config\Services::email();
        $adminEmail = \Config\Services::email();
        //Admin Email
        $adminEmailTemplate = view('email_templates/new_member_admin_email_template', [
			'memberName'        => $memberName,
            'memberEmail'       => $memberEmail,
            'registrationDate'  => $registrationDate
        ]);
        $adminEmail->setMailType('html');
        $adminEmail->setFrom(env('EMAIL_FROM_ADDRESS'), env('EMAIL_FROM_NAME'));
        $adminEmail->setTo(env('EMAIL_TO_ADDRESSES'));
        $adminEmail->setSubject( 'New Client Registration - UGA REDD+');
        $adminEmail->setMessage($adminEmailTemplate);
        if ($adminEmail->send()) {
            return true;
        } else {
            return false;
        }
    }
    //Email for New data Entry can be Event, Member or any Other to Admin
    function sendNewMemberEntryEmail($memberName, $eventName, $eventStartDate, $amountPaid, $memberEmail)
    {
        $email = \Config\Services::email();

        //Sending Email
        $emailTemplate = view('email_templates/new_member_registered_template', [
			'memberName'        => $memberName,
            'eventName'         => $eventName,
            'eventStartDate'    => $eventStartDate,
            'amountPaid'        => $amountPaid, 
        ]);
        $email->setMailType('html');
        $email->setFrom(env('EMAIL_FROM_ADDRESS'), env('EMAIL_FROM_NAME'));
        $email->setTo($memberEmail);
        $email->setSubject( 'Event Registration Confirmation – '. $eventName);
        $email->setMessage($emailTemplate);
        if ($email->send()) {
            return true;
        } else {
            return false;
        }
    }



}
