<?php

namespace App\Controllers\Front;

use CodeIgniter\Controller;
use App\Controllers\BaseController;


class Register extends BaseController
{
    public function initController($request, $response, $logger)
    {
        parent::initController($request, $response, $logger);
        
    }
    
    public function registerClient()
    {
        $this->data['title'] = 'Add Client';
        $this->data['bcrumb'] = 'Add Client';

        $this->data['activities']       = $this->activitiesModel->getAll();
        $this->data['carbon_pools']     = $this->carbonpoolsModel->getAll();
        $this->data['entity_types']     = $this->entitytypesModel->getAll();
        $this->data['methodologies']    = $this->methodologiesModel->getAll();
        $this->data['gases']            = $this->gasesModel->getAll();
        $this->data['forests']          = $this->forestsModel->getAll();
        $this->data['types']            = $this->typesModel->getAll();
        $this->data['statuses']         = $this->statusModel->getAll();

        if($this->request->getMethod() == "POST")
        {
            $rules = [
                'fname'     => ['label'=>'First Name', 'rules'=>'required'],
                'lname'     => ['label'=>'Last Name', 'rules'=>'required'],
                'email'     => ['label' => 'Email', 'rules' => 'required|min_length[5]|max_length[150]|valid_email|is_unique[redd_clients.email]'],
                'phone'    => ['label'=>'Phone Number', 'rules'=>'required'],
                'project_name'      => ['label'=>'Project Name', 'rules'=>'required'],
            ];

            if (!$this->validate($rules))
            {
                $validation = \Config\Services::validation();
                $errors = $validation->getErrors(); 
                $errorMessage = implode('<br>', $errors);
                session()->setFlashdata('error', $errorMessage, 5);
                return redirect()->to('online-registration');
            }

            $code =  bin2hex(random_bytes(24));
            $clientName = $this->request->getVar('fname').' '.$this->request->getVar('lname');
            $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($clientName)));
            $clientStatus = 0;

            $clientData = [
                'fname'                 => $this->request->getVar('fname'),
                'lname'                 => $this->request->getVar('lname'),
                'alias'                 => $slug,
                'email'                 => $this->request->getVar('email'),
                'phone'                 => $this->request->getVar('phone'),
                'password'              => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT),
                'address'               => $this->request->getVar('address'),
                'entity_type_id'        => $this->request->getVar('entity_type_id'),
                'country_id'            => $this->request->getVar('country_id'),
                'state_id'              => $this->request->getVar('state_id'),
                'city_id'               => $this->request->getVar('city_id'),
                'description'           => 'Registered from Website',
                'status'                => $clientStatus
            ];

            $savedClientData = $this->clientsModel->save($clientData);
            if($savedClientData)
            {
                $clientID = $this->clientsModel->getInsertID();
                
               
                //Assign a Group - Users or Customer 
                $groupData = [
                    'user_id' => $clientID,
                    'group_id' => 7,
                    'user_type' => 'client',
                ];
                $this->userauthgroupModel->save($groupData);
                
                //Add Project
                $projectData = [
                    'client_id'            => $clientID,
                    'name'                 => $this->request->getVar('project_name'),
                    'size'                 => $this->request->getVar('size'),
                    'geo_lat'              => $this->request->getVar('geo_lat') ?:Null,
                    'geo_long'             => $this->request->getVar('geo_long') ?: Null,
                    'location_description' => $this->request->getVar('location_description'),
                    'district_id'          => $this->request->getVar('district_id'),
                    'county_id'            => $this->request->getVar('county_id'),
                    'subcounty_id'         => $this->request->getVar('subcounty_id'),
                    'parish_id'            => $this->request->getVar('parish_id'),
                    'village_id'           => $this->request->getVar('village_id'),
                    'description'          => $this->request->getVar('project_description'),
                    'created_by'           => $clientID
                ];
                $savedProject = $this->projectsModel->save($projectData);
                if($savedProject)
                {
                    //Get Project ID
                    $projectID = $this->projectsModel->getInsertID();

                    //Add Project Status
                    $staData = [
                        'project_id'             => $projectID,
                        'project_status_id'      => $this->request->getVar('project_status_id'),
                    ];
                    $this->projectstatusModel->save($staData);

                    //Add Project Types
                    $projectType = $this->request->getVar('project_type_id');
                    $tcount = is_array($projectType) ? count($projectType) : 0;
                    for($i=0; $i < $tcount; $i++)
                    {
                        $typeData = [
                            'project_id'              => $projectID,
                            'project_type_id'         => $projectType[$i],
                        ];
                        $this->projecttypesModel->save($typeData);
                    }

                    //Add Project Activity
                    $projectActivity = $this->request->getVar('activity_id');
                    $acount = is_array($projectActivity) ? count($projectActivity) : 0;
                    for($i=0; $i < $acount; $i++)
                    {
                        $actData = [
                            'project_id'              => $projectID,
                            'activity_id'             => $projectActivity[$i],
                        ];
                        $this->projectactivitiesModel->save($actData);
                    }

                    //Add Project Methodology
                    $projectMetho = $this->request->getVar('methodology_id');
                    $metho_count = is_array($projectMetho) ? count($projectMetho) : 0;
                    for($i=0; $i < $metho_count; $i++)
                    {
                        $metData = [
                            'project_id'              => $projectID,
                            'methodology_id'             => $projectMetho[$i],
                        ];
                        $this->projectmethodologiesModel->save($metData);
                    }

                    //Add Carbon Pool
                    $carbonPool = $this->request->getVar('carbon_pool_id');
                    $carbon_count = is_array($carbonPool) ? count($carbonPool) : 0;
                    for($i=0; $i < $carbon_count; $i++)
                    {
                        $poolData = [
                            'project_id'              => $projectID,
                            'carbon_pool_id'          => $carbonPool[$i],
                        ];
                        $this->projectcarbonpoolsModel->save($poolData);
                    }

                    //Add Gases
                    $gas = $this->request->getVar('gas_id');
                    $gas_count = is_array($gas) ? count($gas) : 0;
                    for($i=0; $i < $gas_count; $i++)
                    {
                        $gasData = [
                            'project_id'      => $projectID,
                            'gas_id'          => $gas[$i],
                        ];
                        $this->projectgasesModel->save($gasData);
                    }

                    //save notification
                    $typeEntry      = 'Member';
                    $clientEmail  = $this->request->getPost('email');
                    $createdAt      = date('Y-m-d H:i:s');
                    $createdBy      = $clientName; 
                    $message        = 'New Client  <strong>'.$clientName.'</strong> and Project has been created by CLIENT';
                    $notificationType = 'redd';
                    $admin = 1;

                    $this->sendNewMemberEmail($clientName, $clientEmail); //Confirmation to New Member
                    $this->emailAdminAboutNewMember($clientName, $clientEmail); //Notification to Admin
                    $this->sendAdminNotifications($message, $notificationType, $admin);

                    session()->setFlashdata('success', 'Your information has been submitted successfully');
                    return redirect()->to('registration-received='.$code);

                }

            }else{
                session()->setFlashdata('error', 'We failed to capture your registration, Contact REDD+ Team for Help');
                return redirect()->to('online-registration');
            }
        }

        return View('website/pages/register', $this->data);
    }
    
    public function successRegistration($code)
    {
        $title = 'Successful Application - UGA REDD+ Registry Data Management System (DMS)';
        $description = 'UGA REDD+ Registry Data Management System (DMS), the official platform for tracking and managing REDD+ projects and emission reductions in Uganda. This system serves as a vital tool to ensure transparency, prevent double counting, and facilitate results-based payments for forest conservation efforts.';
        $keywords = 'Uganda REDD+, REDD Registry, Carbon Credits, Forest Conservation, Emission Reductions, Data Management System, DMS, Climate Change, UN-REDD, Deforestation Monitoring, NFMS, Carbon Finance';

        $data = [
            'title'             => $title,
            'description'       => $description,
            'keywords'          => $keywords,
        ];
        
        log_hit($this->request, $this); 
        return view('website/pages/success-registration', $data);
    }
}