<?php

namespace Modules\Settings\Controllers;

use App\Controllers\Auth\AuthController;

class CompanySettings extends AuthController
{

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

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

    $this->data['gateways'] = $this->paymentgatewaysModel->getAll();
    $this->data['company']  = $this->companysettingsModel->getCompanyDetails();
    $this->data['policies'] = $this->policysettingsModel->getAll();


    return view('Modules\Settings\Views\company\index', $this->data);
  }

  public function setCompany()
  {
      if ($this->request->getMethod() === 'POST') {
          $id = $this->request->getPost('id');
          
          $rules = [
              'name'      => ['label' => 'Company Name', 'rules' => 'required|max_length[100]'],
              'email'     => ['label' => 'Company Email', 'rules' => 'required|valid_email'],
              'tel'       => ['label' => 'Company Phone', 'rules' => 'required'],
              'address_1' => ['label' => 'Address', 'rules' => 'required'],
              'country_id' => ['label' => 'Country', 'rules' => 'required|numeric']
          ];

          // Custom error messages
          $messages = [
              'photo' => [
                  'uploaded' => 'Please upload a valid company logo',
                  'mime_in' => 'Only JPG, PNG images are allowed',
                  'max_size' => 'Image size should not exceed 2MB'
              ]
          ];
          
          if (!$this->validate($rules, $messages))
          {
            if ($this->request->isAJAX()) {
                    return $this->response->setJSON([
                        'success' => false,
                        'errors' => $this->validator->getErrors(),
                        'message' => 'Validation failed'
                    ]);
            } else {
                    $validation = \Config\Services::validation();
                    $errors = $validation->getErrors();
                    
                    $errorMessage = implode('<br>', $errors);
                    session()->setFlashdata('error', $errorMessage, 5);
                    return redirect()->to('administrator/settings/site');
            }
        }
          // Handle file upload
          $logo = $this->request->getFile('photo');
          $logoUrl = null;
          
          if ($logo->isValid() && !$logo->hasMoved()) {
              $newName = $logo->getRandomName();
              $logo->move(ROOTPATH . 'media/company/photos', $newName);
              $logoUrl = base_url('media/company/photos/') . $newName;
          }

          $data = [
              'name'          => $this->request->getPost('name'),
              'email'         => $this->request->getPost('email'),
              'tel'           => $this->request->getPost('tel'),
              'vision'        => $this->request->getPost('vision'),
              'mission'       => $this->request->getPost('mission'),
              'core_values'   => $this->request->getPost('core_values'),
              'objectives'    => $this->request->getPost('objectives'),
              'address_1'     => $this->request->getPost('address_1'),
              'address_2'     => $this->request->getPost('address_2'),
              'tax_id'        => $this->request->getPost('tax_id'),
              'default_currency_id' => $this->request->getPost('default_currency_id'),
              'area_code'     => $this->request->getPost('area_code'),
              'country_id'    => $this->request->getPost('country_id'),
              'state_id'      => $this->request->getPost('state_id'),
              'city_id'       => $this->request->getPost('city_id'),
              'description'   => $this->request->getPost('description'),
              'website'       => $this->request->getPost('website'),
              'facebook'      => $this->request->getPost('facebook'),
              'twitter'       => $this->request->getPost('twitter'),
              'linkedin'      => $this->request->getPost('linkedin'),
              'instagram'     => $this->request->getPost('instagram'),
              'whatsapp'      => $this->request->getPost('whatsapp'),
              'updated_by'    => $this->userdata->user_id,
              'updated_at'    => date('Y-m-d H:i:s')
          ];

          // Only update photo if new one was uploaded
          if ($logoUrl) {
              $data['photo'] = $logoUrl;
          }

          if ($id) {
              // Update existing company
              $this->companysettingsModel->update($id, $data);
              $message = 'Company details updated successfully';
          } else {
              // Create new company
              $data['created_by'] = $this->userdata->user_id;
              $this->companysettingsModel->insert($data);
              $message = 'Company details created successfully';
          }

          //Save Notification
            $ntype = 'setting';
            $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/settings/site');
          }
      }

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

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

  /***
   *  Policy
   */

  public function managePolicies()
  {

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

        
          $rules = [
              'title' => 'required|max_length[255]',
              'policy_type' => 'required|in_list[privacy_policy,terms_of_use,cookie_policy,refund_policy,data_protection,other]',
              'description' => 'required',
              'photo' => [
                  'uploaded[photo]',
                  'mime_in[photo,image/jpg,image/jpeg,image/png]',
                  'max_size[photo,2048]'
              ]
          ];

          if (!$this->validate($rules)) {
            // Get existing photo if updating
            if ($id) {
                $existingPolicy = $this->policysettingsModel->find($id);
                $existingPhoto = $existingPolicy['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/company/photos', $newName);
              $photoPath = base_url('media/company/photos/')  . $newName;
          }

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

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

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

          //Save Notification
            $ntype = 'setting';
            $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/settings/site');
          }
      }

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

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

  public function deletePolicy($id)
  {
    $policy = $this->policysettingsModel->where('id', $id)->first($id);
    if($this->policysettingsModel->where('id', $id)->delete($id))
    {
      //For notifications
      $message  = 'Company Policy '.$policy['title'].' Deleted';
      $ntype    = 'settings';
      $createdBy = $this->userdata->user_id;
      $this->sendAdminNotifications($message, $ntype, $createdBy);

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


}