<?php

namespace Modules\Redd\Controllers;

use App\Controllers\Auth\AuthController;

class Redd extends AuthController
{

    public function initController($request, $response, $logger)
    {
            parent::initController($request, $response, $logger);
    }


    public function index()
    {
        $this->data['title'] = 'Clients';
        $this->data['bcrumb'] = 'Clients';

        $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();
     

        return View('Modules\Redd\Views\index', $this->data);
    }

    public function getClientsList()
    {
        $start = $this->request->getVar('start') ?? 0;
        $length = $this->request->getVar('length') ?? 10;
        $searchValue = $this->request->getVar('search')['value'] ?? '';

        // Fetch Events and total filtered count
        $memberData = $this->clientsModel->getAllClients($start, $length, $searchValue);
        $members = $memberData['data'];
        $totalFiltered = $memberData['recordsFiltered'];

        $data = [];
        foreach ($members as $client) {
            $data[] = [
                'id'                => $client->id,
                'fname'             => $client->fname,
                'lname'             => $client->lname,
                'email'             => $client->email,
                'phone'             => $client->phone,
                'photo'             => $client->photo,
                'entity_name'       => $client->entity_name,
                'entity_type_id'    =>$client->entity_type_id,
                'total_projects'     => $client->total_projects,
                'city_name'         => $client->city_name,
                'state_name'        => $client->state_name,
                'country_name'      => $client->country_name,
            ];
        }

        // Total records without filtering
        $totalRecords = $this->clientsModel->countAllClients();

        return $this->response->setJSON([
            'data' => $data,
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $totalFiltered,
        ]);
    }

    public function addClient()
    {
        $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'],
            ];

            //Check uploaded Image
            $photoRules = [
                'photo' => [
                    'label' => 'Image File',
                    'rules' => 'uploaded[photo]|is_image[photo]|mime_in[photo,image/jpg,image/jpeg,image/gif,image/png,image/webp]|max_size[photo,1024]',
                    'errors' => [
                        'uploaded' => 'You must select a file to upload.',
                        'is_image' => 'The file you uploaded is not a valid image file.',
                        'mime_in' => 'The file you uploaded is not a valid image file.',
                        'max_size' => 'The file you uploaded is too large. Maximum size is 1 MB.'
                    ]
                ],
            ];

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

            //Add Photo
            $photo = $this->request->getFile('photo');
            if ($photo->isValid() && !$photo->hasMoved()) {
                $newName4 = $photo->getRandomName();
                $photo->move(ROOTPATH . 'media/Redd/photos', $newName4);
                $nwn1 = base_url('media/Redd/photos/') . $newName4;
            } else {
                $nwn1 = null;
            }

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

            $clientData = [
                'fname'                 => $this->request->getVar('fname'),
                'lname'                 => $this->request->getVar('lname'),
                'alias'                 => $slug,
                'email'                 => $this->request->getVar('email'),
                'phone'                 => $this->request->getVar('phone'),
                'national_id'           => $this->request->getVar('national_id') ?: Null,
                'password'              => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT),
                'photo'                 => $nwn1,
                'address'               => $this->request->getVar('address'),
                'website'               => $this->request->getVar('website'),
                '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'           => $this->request->getVar('description'),
                'created_by'            => $this->userdata->user_id
            ];

            $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,
                    'boundary_file'        => $this->request->getVar('boundary_file'),
                    'project_validator'     => $this->request->getVar('project_validator'),
                    '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'           => $this->userdata->user_id
                ];
                $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      = $this->userdata->first_name.' '.$this->userdata->last_name; 
                    $message        = 'New Client  <strong>'.$clientName.'</strong> and Project has been created';
                    $notificationType = 'redd';
                    

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

                    session()->setFlashdata('success', 'Client created successfully');
                    return redirect()->to('administrator/redd');

                }

            }else{
                session()->setFlashdata('error', 'Client NOT saved, Try again');
                return redirect()->to('administrator/redd/add-client');
            }
        }

        return View('Modules\Redd\Views\add_member', $this->data);
    }

    public function editClient($id)
    {
        $member = $this->clientsModel->getSingleClient($id);
        echo json_encode($member);
    }
    
    public function updateClient()
    {
        $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'],
                'phone'    => ['label'=>'Phone Number', 'rules'=>'required'],
            ];

            //Check uploaded Image
            $photoRules = [
                'photo' => [
                    'label' => 'Image File',
                    'rules' => 'uploaded[photo]|is_image[photo]|mime_in[photo,image/jpg,image/jpeg,image/gif,image/png,image/webp]|max_size[photo,1024]',
                    'errors' => [
                        'uploaded' => 'You must select a file to upload.',
                        'is_image' => 'The file you uploaded is not a valid image file.',
                        'mime_in' => 'The file you uploaded is not a valid image file.',
                        'max_size' => 'The file you uploaded is too large. Maximum size is 1 MB.'
                    ]
                ],
            ];

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

            $id = $this->request->getPost('id');
            $member = $this->clientsModel->getSingleClient($id);
            //Add Photo
            $photo = $this->request->getFile('photo');
            if ($photo->isValid() && !$photo->hasMoved()) {
                $newName4 = $photo->getRandomName();
                $photo->move(ROOTPATH . 'media/Redd/photos', $newName4);
                $nwn1 = base_url('media/Redd/photos/') . $newName4;
            } else {
                $nwn1 = $member->photo;
            }

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

            $clientData = [
                'fname'                 => $this->request->getVar('fname'),
                'lname'                 => $this->request->getVar('lname'),
                'alias'                 => $slug,
                'email'                 => $this->request->getVar('email'),
                'phone'                 => $this->request->getVar('phone'),
                'photo'                 => $nwn1,
                'address'               => $this->request->getVar('address'),
                'website'               => $this->request->getVar('website'),
                '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'           => $this->request->getVar('description'),
                'updated_by'            => $this->userdata->user_id
            ];

            $savedClientData = $this->clientsModel->update($id, $clientData);
            if($savedClientData)
            {
                //save notification 
                $message        = 'Client  <strong>'.$clientName.'</strong> has been updated';
                $notificationType = 'redd';
                
                $this->sendAdminNotifications($message, $notificationType, $this->userdata->user_id);

                session()->setFlashdata('info', 'Client updated successfully');
                return redirect()->to('administrator/redd');
            }else{
                session()->setFlashdata('error', 'Client NOT updated, Try again');
                return redirect()->to('administrator/redd');
            }
        }
    }

    public function deleteClient($id)
    {
        $m = $this->clientsModel->getSingleClient($id);
        $memberName   = $m->fname.' '.$m->lname;

        if($this->clientsModel->where('id', $id)->delete($id))
        {
            //For notifications
            $message = 'Client '.$memberName.' DELETED successful';
            $notificationType = 'redd';
            $this->sendAdminNotifications($message, $notificationType, $this->userdata->user_id);

            session()->setFlashdata('error', 'Client deleted successfully', 3);
            return redirect()->to('administrator/redd');
        }else{
            session()->setFlashdata('error', 'Client Not deleted', 3);
            return redirect()->to('administrator/redd');
        }
    }

/**====================================================================
 *  SINGLE CLIENT
 *===================================================================*/
    public function singleClient($client)
    {
        $single = $this->clientsModel->getSingleClient($client);
        $this->data['title'] = $single->fname.''.$single->lname.' | UGA REDD+ Client';
        $this->data['bcrumb'] = $single->fname.''.$single->lname.' Profile';

        $this->data['singleMember'] = $single;
        $this->data['entity_types']     = $this->entitytypesModel->getAll();
        $this->data['clientProjects']    = $this->projectsModel->getSingleClientProjects($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();
        $this->data['singleCarbonData'] = $this->projectcarbondataModel->showLatestCarbonDataByClient($client);

        return View('Modules\Redd\Views\single\index', $this->data);
    }


    public function getItems($projectId, $type)
    {
        switch ($type) {
            case 'gases':
                $items = $this->projectgasesModel->getByProject($projectId);
                break;
            case 'activities':
                $items = $this->projectactivitiesModel->getByProject($projectId);
                break;
            case 'types':
                $items = $this->projecttypesModel->getByProject($projectId);
                break;
            case 'methodologies':
                $items = $this->projectmethodologiesModel->getByProject($projectId);
                break;
            case 'carbon-pools':
                $items = $this->projectcarbonpoolsModel->getByProject($projectId);
                break;
            default:
                $items = [];
        }

        $result = array_map(function ($i) {
            return [
                'id'   => $i->id ?? null,
                'name' => $i->name
                    ?? ($i->activity_name    ?? null)
                    ?? ($i->type_name        ?? null)
                    ?? ($i->gas_name         ?? null)
                    ?? ($i->methodology_name ?? null)
                    ?? ($i->pool_name        ?? null),
            ];
        }, $items);

        return $this->response->setJSON($result);
    }


    public function saveItems()
    {
        $projectId = $this->request->getPost('project_id');
        $type      = $this->request->getPost('type');

        switch ($type) {
            case 'gases':
                $model = $this->projectgasesModel;
                $ids   = $this->request->getPost('activity_id') ?? [];
                // clear existing
                $model->where('project_id', $projectId)->delete();
                foreach ($ids as $id) {
                    $model->insert(['project_id' => $projectId, 'gas_id' => $id]);
                }
                break;
            case 'activities':
                $model = $this->projectactivitiesModel;
                $ids   = $this->request->getPost('activity_id') ?? [];
                $model->where('project_id', $projectId)->delete();
                foreach ($ids as $id) {
                    $model->insert(['project_id' => $projectId, 'activity_id' => $id]);
                }
                break;
            case 'types':
                $model = $this->projecttypesModel;
                $ids   = $this->request->getPost('activity_id') ?? [];
                $model->where('project_id', $projectId)->delete();
                foreach ($ids as $id) {
                    $model->insert(['project_id' => $projectId, 'project_type_id' => $id]);
                }
                break;
            case 'methodologies':
                $model = $this->projectmethodologiesModel;
                $ids   = $this->request->getPost('activity_id') ?? [];
                $model->where('project_id', $projectId)->delete();
                foreach ($ids as $id) {
                    $model->insert(['project_id' => $projectId, 'methodology_id' => $id]);
                }
                break;
            case 'carbon-pools':
                $model = $this->projectcarbonpoolsModel;
                $ids   = $this->request->getPost('activity_id') ?? [];
                $model->where('project_id', $projectId)->delete();
                foreach ($ids as $id) {
                    $model->insert(['project_id' => $projectId, 'carbon_pool_id' => $id]);
                }
                break;
            case 'statuses':
                $model = $this->projectstatusModel;
                $staData = [
                    'project_id'        => $projectId,
                    'project_status_id' => $this->request->getPost('project_status_id'),
                    'description'       => $this->request->getPost('description'),
                ];
                $model->save($staData);
                session()->setFlashdata('success', 'Project Status Updated', 3);
                return redirect()->to(previous_url());
            default:
                return $this->response->setJSON(['status' => 'error', 'msg' => 'Invalid type']);
        }

        return $this->response->setJSON(['status' => 'success']);
    }

    public function deleteItem($type, $id)
    {
        switch ($type) {
            case 'gases':
                $model = $this->projectgasesModel;
                $model->where('id', $id)->delete($id);
                session()->setFlashdata('error', 'Project Gas Item Deleted', 3);
                return redirect()->to(previous_url());
                break;
            case 'activities':
                $model = $this->projectactivitiesModel;
                $model->where('id', $id)->delete($id);
                session()->setFlashdata('error', 'Project Activity Item Deleted', 3);
                return redirect()->to(previous_url());
                break;
            case 'types':
                $model = $this->projecttypesModel;
                $model->where('id', $id)->delete($id);
                session()->setFlashdata('error', 'Project Type Item Deleted', 3);
                return redirect()->to(previous_url());
                break;
            case 'methodologies':
                $model = $this->projectmethodologiesModel;
                $model->where('id', $id)->delete($id);
                session()->setFlashdata('error', 'Project Methodology Deleted', 3);
                return redirect()->to(previous_url());
                break;
            case 'carbon-pools':
                $model = $this->projectcarbonpoolsModel;
                $model->where('id', $id)->delete($id);
                session()->setFlashdata('error', 'Project Carbon Pool Item Deleted', 3);
                return redirect()->to(previous_url());
                break;
            case 'statuses':
                $model = $this->projectstatusModel;
                $model->where('id', $id)->delete($id);
                session()->setFlashdata('error', 'Project Status Item Deleted', 3);
                return redirect()->to(previous_url());
                break;
            default:
                return $this->response->setJSON(['status' => 'error', 'msg' => 'Invalid type']);
        }
    }

    public function editProject($id){
        $project = $this->projectsModel->getSingleProject($id);
        echo json_encode($project);
    }

    public function updateProject()
    {

        if($this->request->getMethod() == "POST")
        {
            $rules = [
                'name' => ['label'=>'Project Name', 'rules'=>'required'],
            ];

            $id = $this->request->getVar('id');
            $clientID = $this->request->getVar('client_id');

            //Update Project
            $projectData = [
                'client_id'            => $this->request->getVar('client_id'),
                'name'                 => $this->request->getVar('name'),
                'project_number'        => $this->request->getVar('project_number'),
                'size'                 => $this->request->getVar('size'),
                'geo_lat'              => $this->request->getVar('geo_lat') ?:Null,
                'geo_long'             => $this->request->getVar('geo_long') ?: Null,
                'boundary_file'        => $this->request->getVar('boundary_file'),
                'project_validator'     => $this->request->getVar('project_validator'),
                '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'),
                'updated_by'           => $this->userdata->user_id
            ];
            $updatedProject = $this->projectsModel->update($id, $projectData);
            if($updatedProject)
            {
                //save notification 
                $message        = 'Project <strong>'.$this->request->getVar('name').'</strong> has been updated';
                $notificationType = 'redd';
                
                $this->sendAdminNotifications($message, $notificationType, $this->userdata->user_id);

                session()->setFlashdata('info', 'Project updated successfully');
            }else{
                session()->setFlashdata('error', 'Project NOT updated, Try again');
            }
            return redirect()->to('administrator/redd/single-client/id='.$clientID);
        }
    }
    
/**====================================================================
 *  CARBON DATA
 *===================================================================*/
 
    public function showCarbonData()
    {
        $this->data['title'] = 'Carbon Data | UGA REDD+';
        $this->data['bcrumb'] = 'Carbon Data List';


        $this->data['carbondata'] = $this->projectcarbondataModel->getAll();
        $this->data['entity_types']     = $this->entitytypesModel->getAll();
        $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();
       

        return View('Modules\Redd\Views\carbondata-list', $this->data);
    }

    public function getCarbonData()
    {
        if($this->request->getMethod() == "POST")
        {
            $rules = [
                'estimated_er' => ['label'=>'Estimated ER', 'rules'=>'required'],
                'buffer_credit' => ['label'=>'Buffer Credit', 'rules'=>'required'],
            ];

            $projectID = $this->request->getPost('project_id');
            $project = $this->projectsModel->getSingleProject($projectID);

            $carbonData = [
                'project_id'                => $projectID,
                'estimated_er'              => $this->request->getVar('estimated_er'),
                'buffer_credit'             => $this->request->getVar('buffer_credit'),
                'reff_period_start'         => $this->request->getVar('reff_period_start') ?: null,
                'reff_period_end'           => $this->request->getVar('reff_period_end') ?: null,
                'credit_period_start'       => $this->request->getVar('credit_period_start'),
                'credit_period_end'         => $this->request->getVar('credit_period_end'),
                'uncertainty'               => $this->request->getVar('uncertainty'),
                'registry'                  => $this->request->getVar('registry'),
                'description'               => $this->request->getVar('description'),
                'created_by'                => $this->userdata->user_id
            ];

            if($this->projectcarbondataModel->save($carbonData))
            {
                //save notification 
                $message        = 'Carbon Data for Project <strong>'.$project->name.'</strong> saved successfully';
                $notificationType = 'redd';
                
                $this->sendAdminNotifications($message, $notificationType, $this->userdata->user_id);

                session()->setFlashdata('success', 'Carbon Data saved successfully');
            }else{
                session()->setFlashdata('error', 'Carbon Data NOT saved, Try again');
            }

            return redirect()->to('administrator/redd/single-client/id='.$project->client_id);
        }
    }
    
    public function editCarbonData($id)
    {
        $carbon = $this->projectcarbondataModel->where('id', $id)->first($id);
        echo json_encode($carbon);
    }
    
    public function updateCarbonData()
    {
        if($this->request->getMethod() == "POST")
        {
            $rules = [
                'estimated_er' => ['label'=>'Estimated ER', 'rules'=>'required'],
                'buffer_credit' => ['label'=>'Buffer Credit', 'rules'=>'required'],
            ];

            $id = $this->request->getPost('id');
            $projectID = $this->request->getPost('project_id');
            $project = $this->projectsModel->getSingleProject($projectID);

            $carbonData = [
                'project_id'                => $projectID,
                'estimated_er'              => $this->request->getVar('estimated_er'),
                'buffer_credit'             => $this->request->getVar('buffer_credit'),
                'reff_period_start'         => $this->request->getVar('reff_period_start') ?: null,
                'reff_period_end'          => $this->request->getVar('reff_period_end') ?: null,
                'credit_period_start'       => $this->request->getVar('credit_period_start'),
                'credit_period_end'         => $this->request->getVar('credit_period_end'),
                'uncertainty'               => $this->request->getVar('uncertainty'),
                'registry'                  => $this->request->getVar('registry'),
                'description'               => $this->request->getVar('description'),
                'updated_by'                => $this->userdata->user_id
            ];

            if($this->projectcarbondataModel->update($id, $carbonData))
            {
                //save notification 
                $message        = 'Carbon Data for Project <strong>'.$project->name.'</strong> updated successfully';
                $notificationType = 'redd';
                
                $this->sendAdminNotifications($message, $notificationType, $this->userdata->user_id);

                session()->setFlashdata('info', 'Carbon Data updated successfully');
            }else{
                session()->setFlashdata('error', 'Carbon Data NOT updated, Try again');
            }

            return redirect()->to('administrator/redd/single-client/id='.$project->client_id);
        }
    }

/**====================================================================
 *  PROJECTS
 *===================================================================*/
    public function projects()
    {
        $this->data['title'] = 'Projects | UGA REDD+';
        $this->data['bcrumb'] = 'Projects List';


        $this->data['projects']         = $this->projectsModel->getAllProjects();
        $this->data['entity_types']     = $this->entitytypesModel->getAll();
        $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();
        $this->data['singleCarbonData'] = $this->projectcarbondataModel->getAll();

        return View('Modules\Redd\Views\projects-list', $this->data);
    }
    

 
}
