<?php

namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use App\Controllers\BaseController;
use App\Models\SalesExecutiveModel;
use App\Models\AgentModel;
use App\Models\AgentIncentiveFileModel;

class SalesExecutive extends ResourceController
{

    protected $salesExecutiveModel;

    public function __construct()
    {
        $this->salesExecutiveModel = new SalesExecutiveModel();
    }

    // LIST of all sales executive
    public function salesExecutiveList()
    {
        try{

            $id = $this->request->getGet('manager_id');

            $data = $this->salesExecutiveModel->where('manager_id' , $id )->findAll();

            return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200);

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
        }
       
    }

    // Find a sales executive
    public function findSalesExecutive()
    {
        try{

            $id = $this->request->getGet('id');

            $record = $this->salesExecutiveModel->find((int)$id);

            if (!$record) {
                return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
            }

            return $this->respond(['status' => 'success', 'code' => 200, 'data' => $record], 200);

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
        }
    }

    // CREATE sales executive
    public function createSalesExecutive()
    {
        try{
            $data = $this->request->getJSON(true);

            $email  = (!empty($data['email'])) ? $data['email'] : null;
            $mobile = (!empty($data['mobile'])) ? $data['mobile'] : null;

            if ($email === null && $mobile === null) {
                return $this->respond(['status' => 'failed', 'code' => 500, 'data' => 'Email or Mobile is required'], 500);
            }
           
            $insertData = [
                'name'                  => $data['name'],
                'email'                 => $email,  
                'mobile'                => $mobile,
                'address'               => $data['address'],
                'manager_id'            => $data['manager_id'],
                'created_by'            => $data['created_by'],
                'is_active'             => $data['is_active'] ?? 1,
            ];

            $this->salesExecutiveModel->insert($insertData);

            return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);

        } catch (\Exception $e) {
            // return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
                $message = $e->getMessage();
                if (strpos($message, '1062') !== false || strpos($message, 'Duplicate entry') !== false) {
                    if (strpos($message, 'sales_executive_unique_mobile') !== false) {
                        $message = 'Mobile number already exists';
                    } elseif (strpos($message, 'sales_executive_email') !== false) {
                        $message = 'Email already exists';
                    } else {
                        $message = 'Duplicate record found';
                    }
                }
                return $this->respond(['status' => 'failed', 'code'   => 500, 'data'   => $message], 500);
        }
    }

   // UPDATE sales executive
   public function updateSalesExecutivedetails()
   {
        try{
            // echo "rechecked";die;
            $data = $this->request->getJSON(true);
            if (!isset($data['id'])) {
                    return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'ID Required'], 200);
                }

            $id = $data['id'];

            // check if Sales Executive exists
            $salesExecutive = $this->salesExecutiveModel->find((int)$id);
            if (!$salesExecutive) {
                return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'Date Not Found'], 200);
            }
            $email  = (!empty($data['email'])) ? $data['email'] : null;
            $mobile = (!empty($data['mobile'])) ? $data['mobile'] : null;

            if ($email === null && $mobile === null) {
                return $this->respond(['status' => 'failed', 'code' => 500, 'data' => 'Either Email or Mobile must be provided'], 500);
            }

            $updateData = [
                'name'    => $data['name'] ?? null,
                'email'   => $email,
                'mobile'  => $mobile,
                'address' => $data['address'] ?? null,
                'updated_by' => $data['updated_by'] ?? null,
            ];

            $this->salesExecutiveModel->update($id, $updateData);

            return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);

        } catch (\Exception $e) {
            // return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
                $message = $e->getMessage();
                if (strpos($message, '1062') !== false || strpos($message, 'Duplicate entry') !== false) {
                    if (strpos($message, 'sales_executive_unique_mobile') !== false) {
                        $message = 'Mobile number already exists';
                    } elseif (strpos($message, 'sales_executive_email') !== false) {
                        $message = 'Email already exists';
                    } else {
                        $message = 'Duplicate record found';
                    }
                }
                return $this->respond(['status' => 'failed', 'code'   => 500, 'data'   => $message], 500);
        }
   }

    // Soft Delete (ACTIVATE / DEACTIVATE) sales executive
    public function changeSalesExecutiveStatus()
    {
        try {
            $data = $this->request->getJSON(true);

            // validate inputs
            if (!isset($data['id']) || !isset($data['is_active'])) {
                return $this->respond(['status' => 'failed', 'code'   => 200,'data'   => 'ID and Status are required'], 200);
            }

            $id     = $data['id'];
            $is_active = (int) $data['is_active']; // 0 or 1

            $status = ($is_active == 1) ? 0 : 1;

            // check if agent exists
            $agent = $this->salesExecutiveModel->find((int)$id);
            if (!$agent) {
                return $this->respond(['status' => 'failed','code'   => 200, 'data'   => 'Agent not found'], 200);
            }

            // update status
            $this->salesExecutiveModel->update($id, ['is_active' => $status]);

            return $this->respond([
                'status'  => 'success', 'code'    => 200,'data'   => "Agent status updated"], 200);

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed','code'   => 500,'data'   => $e->getMessage()], 500);
        }
    }

}