<?php

namespace Modules\Redd\Controllers;

use App\Controllers\Auth\AuthController;

class ReddSettings extends AuthController
{

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


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

        $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\settings\index', $this->data);
    }

/** =========================================================================================
 * FORESTS
*============================================================================================*/
    public function manageForests()
    {

        if ($this->request->getMethod() === 'POST') 
        {
            //Incase there is existing photo
            $id = $this->request->getPost('id');
            $existingPhoto = null;

            
            $rules = [
                'name' => ['label'=>'Forest Name', 'rules' => 'required|max_length[255]'],
                'size' => ['label'=>'Forest Size', 'rules' => 'required'],
            ];

            if (!$this->validate($rules)) {
                return $this->response->setJSON([
                    'success' => false,
                    'errors' => $this->validator->getErrors(),
                    'message' => 'Validation failed'
                ]);
            }

            $forestName = $this->request->getPost('name');
            $data = [
                'name'              => $forestName,
                'classification'    => $this->request->getPost('classification'),
                'size'              => $this->request->getPost('size'),
                'location_description' => $this->request->getPost('location_description'),
                'geo_lat'           => $this->request->getPost('geo_lat'),
                'geo_long'          => $this->request->getPost('geo_long'),
                'boundary_file'     => $this->request->getPost('boundary_file'),
                'description'       => $this->request->getPost('description'),
                'updated_at'        => date('Y-m-d H:i:s')
            ];

            if ($id = $this->request->getPost('id')) {

                // Update existing Forest
                $this->forestsModel->update($id, $data);
                $message = 'Forest '.$forestName.' updated successfully';
            } else {
                // Create new 
                $data['created_at'] = date('Y-m-d H:i:s');
                $this->forestsModel->insert($data);
                $message = 'Forest '.$forestName.' created successfully';
            }

            //Save Notification
                $ntype = 'redd';
                $createdBy = $this->userdata->user_id;
                $this->sendAdminNotifications($message, $ntype, $createdBy);

            if ($this->request->isAJAX()) {
                return $this->response->setJSON([
                    'success' => true,
                    'message' => $message,
                    'data' => $data
                ]);
            } else {
                session()->setFlashdata('success', $message);
                return redirect()->to('administrator/redd/settings');
            }
        }

        // GET request handling
        if ($id = $this->request->getGet('id')) {
            $forest = $this->forestsModel->find($id);
            return $this->response->setJSON([
                'data' => $forest ? $forest : null
            ]);  
        }

        return $this->response->setJSON([
            'success' => false,
            'message' => 'Invalid request'
        ]);
    }

    public function deleteForest($id)
    {
        $forest = $this->forestsModel->where('id', $id)->first($id);
        if($this->forestsModel->where('id', $id)->delete($id))
        {
        //For notifications
        $message  = 'Forest'.$forest['name'].' Deleted';
        $ntype    = 'Redd';
        $createdBy = $this->userdata->user_id;
        $this->sendAdminNotifications($message, $ntype, $createdBy);

        session()->setFlashdata('error', 'Forest'.$forest['name'].' Deleted', 3);
        return redirect()->to('administrator/redd/settings');
        }
        
    }
/** =========================================================================================
 * ACTIVITY
*============================================================================================*/    
    public function manageActivities()
  {

      if ($this->request->getMethod() === 'POST') 
      {
        //Incase there is existing photo
        $id = $this->request->getPost('id');
        $name = $this->request->getVar('name');
        $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($name)));
        $existingPhoto = null;

        
          $rules = [
              'name' => 'required|max_length[255]',
          ];
          $photoRules = [
            'photo' => [
                  'uploaded[photo]',
                  'mime_in[photo,image/jpg,image/jpeg,image/png]',
                  'max_size[photo,2048]'
              ]
          ];

          if (!$this->validate($rules)) {
            return $this->response->setJSON([
                  'success' => false,
                  'errors' => $this->validator->getErrors(),
                  'message' => 'Validation failed'
            ]);
          }
          if (!$this->validate($photoRules)) {
            // Get existing photo if updating
            if ($id) {
                $existingActivity = $this->activitiesModel->find($id);
                $existingPhoto = $existingActivity['photo'] ?? null;
            }else{
              return $this->response->setJSON([
                  'success' => false,
                  'errors' => $this->validator->getErrors(),
                  'message' => 'Validation failed'
              ]);
            } 
          }

          // Handle file upload
          $photoPath = $existingPhoto; // Keep existing by default
          $photo = $this->request->getFile('photo');
          if ($photo->isValid() && !$photo->hasMoved()) {
              $newName = $photo->getRandomName();
              $photo->move(ROOTPATH . 'media/redd/photos', $newName);
              $photoPath = base_url('media/redd/photos/')  . $newName;
          }

          $data = [
              'name'          => $this->request->getPost('name'),
              'alias'         => $slug,
              'description'   => $this->request->getPost('description'),
              'photo'         => $photoPath,
              'updated_at'    => date('Y-m-d H:i:s')
          ];

          if ($id = $this->request->getPost('id')) {
              $this->activitiesModel->update($id, $data);
              $message = 'Activity '.$name.' updated successfully';
          } else {
              // Create new policy
              $data['created_at'] = date('Y-m-d H:i:s');
              $this->activitiesModel->insert($data);
              $message = 'Activity '.$name.' created successfully';
          }

          //Save Notification
            $ntype = 'redd';
            $createdBy = $this->userdata->user_id;
            $this->sendAdminNotifications($message, $ntype, $createdBy);

          if ($this->request->isAJAX()) {
              return $this->response->setJSON([
                  'success' => true,
                  'message' => $message,
                  'data' => $data
              ]);
          } else {
              session()->setFlashdata('success', $message);
              return redirect()->to('administrator/redd/settings');
          }
      }

      // GET request handling
      if ($id = $this->request->getGet('id')) {
          $activity = $this->activitiesModel->find($id);
          return $this->response->setJSON([
              'data' => $activity ? $activity : null
          ]);  
      }

      return $this->response->setJSON([
          'success' => false,
          'message' => 'Invalid request'
      ]);
  }

  public function deleteActivity($id)
  {
    $activity = $this->activitiesModel->where('id', $id)->first($id);
    if($this->activitiesModel->where('id', $id)->delete($id))
    {
      //For notifications
      $message  = 'Activity '.$activity['name'].' Deleted';
      $ntype    = 'redd';
      $createdBy = $this->userdata->user_id;
      $this->sendAdminNotifications($message, $ntype, $createdBy);

      session()->setFlashdata('error', 'Activity '.$policy['name'].' Deleted', 3);
      return redirect()->to('administrator/redd/settings');
    }
    
  }

/** =========================================================================================
 * METHODOLOGY
*============================================================================================*/    
    public function manageMethodologies()
  {

      if ($this->request->getMethod() === 'POST') 
      {
        
        $id = $this->request->getPost('id');
        $name = $this->request->getVar('name');
        
          $rules = [
              'name' => 'required|max_length[255]',
          ];

          if (!$this->validate($rules)) {
            return $this->response->setJSON([
                  'success' => false,
                  'errors' => $this->validator->getErrors(),
                  'message' => 'Validation failed'
            ]);
          }

          $data = [
              'name'          => $this->request->getPost('name'),
              'reference_link' => $this->request->getPost('reference_link'),
              'description'   => $this->request->getPost('description'),
              'updated_at'    => date('Y-m-d H:i:s')
          ];

          if ($id = $this->request->getPost('id')) {
              $this->methodologiesModel->update($id, $data);
              $message = 'Methodology '.$name.' updated successfully';
          } else {
              // Create new policy
              $data['created_at'] = date('Y-m-d H:i:s');
              $this->methodologiesModel->insert($data);
              $message = 'Methodology '.$name.' created successfully';
          }

          //Save Notification
            $ntype = 'redd';
            $createdBy = $this->userdata->user_id;
            $this->sendAdminNotifications($message, $ntype, $createdBy);

          if ($this->request->isAJAX()) {
              return $this->response->setJSON([
                  'success' => true,
                  'message' => $message,
                  'data' => $data
              ]);
          } else {
              session()->setFlashdata('success', $message);
              return redirect()->to('administrator/redd/settings');
          }
      }

      // GET request handling
      if ($id = $this->request->getGet('id')) {
          $activity = $this->methodologiesModel->find($id);
          return $this->response->setJSON([
              'data' => $activity ? $activity : null
          ]);  
      }

      return $this->response->setJSON([
          'success' => false,
          'message' => 'Invalid request'
      ]);
  }

  public function deleteMethodology($id)
  {
    $methodology = $this->methodologiesModel->where('id', $id)->first($id);
    if($this->methodologiesModel->where('id', $id)->delete($id))
    {
      //For notifications
      $message  = 'Methodology '.$methodology['name'].' Deleted';
      $ntype    = 'redd';
      $createdBy = $this->userdata->user_id;
      $this->sendAdminNotifications($message, $ntype, $createdBy);

      session()->setFlashdata('error', 'Methodology '.$methodology['name'].' Deleted', 3);
      return redirect()->to('administrator/redd/settings');
    }
  }

/** =========================================================================================
 * GAS
*============================================================================================*/    
    public function manageGases()
  {

      if ($this->request->getMethod() === 'POST') 
      {
        
        $id     = $this->request->getPost('id');
        $name   = $this->request->getVar('name');
        
          $rules = [
              'name' => ['label'=>'Gas Name', 'rules' => 'required'],
              'symbol' => ['label'=>'Symbol', 'rules' => 'required'],
          ];

          if (!$this->validate($rules)) {
            return $this->response->setJSON([
                  'success' => false,
                  'errors' => $this->validator->getErrors(),
                  'message' => 'Validation failed'
            ]);
          }

          $data = [
              'name'            => $this->request->getPost('name'),
              'symbol'          => $this->request->getPost('symbol'),
              'atomic_number'   => $this->request->getPost('atomic_number'),
              'atomic_mass'     => $this->request->getPost('atomic_mass'),
              'global_warming_potential' => $this->request->getPost('global_warming_potential'),
              'gas_group'       => $this->request->getPost('gas_group'),
              'period'          => $this->request->getPost('period'),
              'updated_at'      => date('Y-m-d H:i:s')
          ];

          if ($id = $this->request->getPost('id')) {
              $this->gasesModel->update($id, $data);
              $message = 'Gas '.$name.' updated successfully';
          } else {
              // Create new policy
              $data['created_at'] = date('Y-m-d H:i:s');
              $this->gasesModel->insert($data);
              $message = 'Gas '.$name.' created successfully';
          }

          //Save Notification
            $ntype = 'redd';
            $createdBy = $this->userdata->user_id;
            $this->sendAdminNotifications($message, $ntype, $createdBy);

          if ($this->request->isAJAX()) {
              return $this->response->setJSON([
                  'success' => true,
                  'message' => $message,
                  'data' => $data
              ]);
          } else {
              session()->setFlashdata('success', $message);
              return redirect()->to('administrator/redd/settings');
          }
      }

      // GET request handling
      if ($id = $this->request->getGet('id')) {
          $gas = $this->gasesModel->find($id);
          return $this->response->setJSON([
              'data' => $gas ? $gas : null
          ]);  
      }

      return $this->response->setJSON([
          'success' => false,
          'message' => 'Invalid request'
      ]);
  }

  public function deleteGas($id)
  {
    $gas = $this->gasesModel->where('id', $id)->first($id);
    if($this->gasesModel->where('id', $id)->delete($id))
    {
      //For notifications
      $message  = 'Gas '.$gas['name'].' Deleted';
      $ntype    = 'redd';
      $createdBy = $this->userdata->user_id;
      $this->sendAdminNotifications($message, $ntype, $createdBy);

      session()->setFlashdata('error', 'Gas '.$gas['name'].' Deleted', 3);
      return redirect()->to('administrator/redd/settings');
    }
  }

/** =========================================================================================
 * CARBON POOLs
*============================================================================================*/    
    public function manageCarbonPools()
  {

      if ($this->request->getMethod() === 'POST') 
      {
        
        $id     = $this->request->getPost('id');
        $name   = $this->request->getVar('name');
        
          $rules = [
              'name' => ['label'=>'Carbon Pool Name', 'rules' => 'required'],
          ];

          if (!$this->validate($rules)) {
            return $this->response->setJSON([
                  'success' => false,
                  'errors' => $this->validator->getErrors(),
                  'message' => 'Validation failed'
            ]);
          }

          $data = [
              'name'            => $this->request->getPost('name'),
              'description'          => $this->request->getPost('description'),
              'updated_at'      => date('Y-m-d H:i:s')
          ];

          if ($id = $this->request->getPost('id')) {
              $this->carbonpoolsModel->update($id, $data);
              $message = 'Carbon Pool '.$name.' updated successfully';
          } else {
              // Create new policy
              $data['created_at'] = date('Y-m-d H:i:s');
              $this->carbonpoolsModel->insert($data);
              $message = 'Carbon Pool '.$name.' created successfully';
          }

          //Save Notification
            $ntype = 'redd';
            $createdBy = $this->userdata->user_id;
            $this->sendAdminNotifications($message, $ntype, $createdBy);

          if ($this->request->isAJAX()) {
              return $this->response->setJSON([
                  'success' => true,
                  'message' => $message,
                  'data' => $data
              ]);
          } else {
              session()->setFlashdata('success', $message);
              return redirect()->to('administrator/redd/settings');
          }
      }

      // GET request handling
      if ($id = $this->request->getGet('id')) {
          $gas = $this->carbonpoolsModel->find($id);
          return $this->response->setJSON([
              'data' => $gas ? $gas : null
          ]);  
      }

      return $this->response->setJSON([
          'success' => false,
          'message' => 'Invalid request'
      ]);
  }

  public function deleteCarbonPool($id)
  {
    $gas = $this->carbonpoolsModel->where('id', $id)->first($id);
    if($this->carbonpoolsModel->where('id', $id)->delete($id))
    {
      //For notifications
      $message  = 'Carbon Pool '.$gas['name'].' Deleted';
      $ntype    = 'redd';
      $createdBy = $this->userdata->user_id;
      $this->sendAdminNotifications($message, $ntype, $createdBy);

      session()->setFlashdata('error', 'Carbon Pool '.$gas['name'].' Deleted', 3);
      return redirect()->to('administrator/redd/settings');
    }
  }

/** =========================================================================================
 * Entity Types
*============================================================================================*/    
    public function manageEntityTypes()
  {

      if ($this->request->getMethod() === 'POST') 
      {
        
        $id     = $this->request->getPost('id');
        $name   = $this->request->getVar('name');
        
          $rules = [
              'name' => ['label'=>'Entity Type Name', 'rules' => 'required'],
          ];

          if (!$this->validate($rules)) {
            return $this->response->setJSON([
                  'success' => false,
                  'errors' => $this->validator->getErrors(),
                  'message' => 'Validation failed'
            ]);
          }

          $data = [
              'name'            => $this->request->getPost('name'),
              'description'          => $this->request->getPost('description'),
              'updated_at'      => date('Y-m-d H:i:s')
          ];

          if ($id = $this->request->getPost('id')) {
              $this->entitytypesModel->update($id, $data);
              $message = 'Entity Type '.$name.' updated successfully';
          } else {
              // Create new policy
              $data['created_at'] = date('Y-m-d H:i:s');
              $this->entitytypesModel->insert($data);
              $message = 'Entity Type '.$name.' created successfully';
          }

          //Save Notification
            $ntype = 'redd';
            $createdBy = $this->userdata->user_id;
            $this->sendAdminNotifications($message, $ntype, $createdBy);

          if ($this->request->isAJAX()) {
              return $this->response->setJSON([
                  'success' => true,
                  'message' => $message,
                  'data' => $data
              ]);
          } else {
              session()->setFlashdata('success', $message);
              return redirect()->to('administrator/redd/settings');
          }
      }

      // GET request handling
      if ($id = $this->request->getGet('id')) {
          $entity = $this->entitytypesModel->find($id);
          return $this->response->setJSON([
              'data' => $entity ? $entity : null
          ]);  
      }

      return $this->response->setJSON([
          'success' => false,
          'message' => 'Invalid request'
      ]);
  }

  public function deleteEntityType($id)
  {
    $gas = $this->entitytypesModel->where('id', $id)->first($id);
    if($this->entitytypesModel->where('id', $id)->delete($id))
    {
      //For notifications
      $message  = 'Entity Type '.$gas['name'].' Deleted';
      $ntype    = 'redd';
      $createdBy = $this->userdata->user_id;
      $this->sendAdminNotifications($message, $ntype, $createdBy);

      session()->setFlashdata('error', 'Entity Type '.$gas['name'].' Deleted', 3);
      return redirect()->to('administrator/redd/settings');
    }
  }

/** =========================================================================================
 * Diffirrent Types
*============================================================================================*/    
    public function manageProjectTypes()
  {

      if ($this->request->getMethod() === 'POST') 
      {
        
        $id     = $this->request->getPost('id');
        $name   = $this->request->getVar('name');
        
          $rules = [
              'name' => ['label'=>'Type Name', 'rules' => 'required'],
          ];

          if (!$this->validate($rules)) {
            return $this->response->setJSON([
                  'success' => false,
                  'errors' => $this->validator->getErrors(),
                  'message' => 'Validation failed'
            ]);
          }

          $data = [
              'name'            => $this->request->getPost('name'),
              'description'     => $this->request->getPost('description'),
              'updated_at'      => date('Y-m-d H:i:s')
          ];

          if ($id = $this->request->getPost('id')) {
              $this->typesModel->update($id, $data);
              $message = 'Type '.$name.' updated successfully';
          } else {
              // Create new 
              $data['created_at'] = date('Y-m-d H:i:s');
              $this->typesModel->insert($data);
              $message = 'Type '.$name.' created successfully';
          }

          //Save Notification
            $ntype = 'redd';
            $createdBy = $this->userdata->user_id;
            $this->sendAdminNotifications($message, $ntype, $createdBy);

          if ($this->request->isAJAX()) {
              return $this->response->setJSON([
                  'success' => true,
                  'message' => $message,
                  'data' => $data
              ]);
          } else {
              session()->setFlashdata('success', $message);
              return redirect()->to('administrator/redd/settings');
          }
      }

      // GET request handling
      if ($id = $this->request->getGet('id')) {
          $entity = $this->typesModel->find($id);
          return $this->response->setJSON([
              'data' => $entity ? $entity : null
          ]);  
      }

      return $this->response->setJSON([
          'success' => false,
          'message' => 'Invalid request'
      ]);
  }

  public function deleteProjectType($id)
  {
    $gas = $this->typesModel->where('id', $id)->first($id);
    if($this->typesModel->where('id', $id)->delete($id))
    {
      //For notifications
      $message  = 'Type '.$gas['name'].' Deleted';
      $ntype    = 'redd';
      $createdBy = $this->userdata->user_id;
      $this->sendAdminNotifications($message, $ntype, $createdBy);

      session()->setFlashdata('error', 'Type '.$gas['name'].' Deleted', 3);
      return redirect()->to('administrator/redd/settings');
    }
  }
/** =========================================================================================
 * STATUSES
*============================================================================================*/    
    public function manageProjectStatuses()
  {

      if ($this->request->getMethod() === 'POST') 
      {
        
        $id     = $this->request->getPost('id');
        $name   = $this->request->getVar('name');
        
          $rules = [
              'name' => ['label'=>'Status Name', 'rules' => 'required'],
          ];

          if (!$this->validate($rules)) {
            return $this->response->setJSON([
                  'success' => false,
                  'errors' => $this->validator->getErrors(),
                  'message' => 'Validation failed'
            ]);
          }

          $data = [
              'name'            => $this->request->getPost('name'),
              'icon'            => $this->request->getPost('icon'),
              'color'            => $this->request->getPost('color'),
              'description'          => $this->request->getPost('description'),
              'updated_at'      => date('Y-m-d H:i:s')
          ];

          if ($id = $this->request->getPost('id')) {
              $this->statusModel->update($id, $data);
              $message = 'Status '.$name.' updated successfully';
          } else {
              // Create new 
              $data['created_at'] = date('Y-m-d H:i:s');
              $this->statusModel->insert($data);
              $message = 'Status '.$name.' created successfully';
          }

          //Save Notification
            $ntype = 'redd';
            $createdBy = $this->userdata->user_id;
            $this->sendAdminNotifications($message, $ntype, $createdBy);

          if ($this->request->isAJAX()) {
              return $this->response->setJSON([
                  'success' => true,
                  'message' => $message,
                  'data' => $data
              ]);
          } else {
              session()->setFlashdata('success', $message);
              return redirect()->to('administrator/redd/settings');
          }
      }

      // GET request handling
      if ($id = $this->request->getGet('id')) {
          $entity = $this->statusModel->find($id);
          return $this->response->setJSON([
              'data' => $entity ? $entity : null
          ]);  
      }

      return $this->response->setJSON([
          'success' => false,
          'message' => 'Invalid request'
      ]);
  }

  public function deleteProjectStatus($id)
  {
    $gas = $this->statusModel->where('id', $id)->first($id);
    if($this->statusModel->where('id', $id)->delete($id))
    {
      //For notifications
      $message  = 'Status '.$gas['name'].' Deleted';
      $ntype    = 'redd';
      $createdBy = $this->userdata->user_id;
      $this->sendAdminNotifications($message, $ntype, $createdBy);

      session()->setFlashdata('error', 'Status '.$gas['name'].' Deleted', 3);
      return redirect()->to('administrator/redd/settings');
    }
  }

}