<?php

namespace App\Controllers\Admin;

use App\Core\Service\Logger;
use App\Core\Library\Mailer;
use App\Library\Utilities;
use App\Controllers\BaseController;
use App\Model\AdminModel;
use App\Model\AdminUserModel;
use App\Model\AdminClientModel;
use App\Model\AdminTemplateModel;
use App\Config\Main;

class MasterController extends BaseController
{
    private $AdminModel;
    private $AdminUserModel;
    private $AdminTemplateModel;
    private $AdminClientModel;
    private $Mailer;
    public function __construct()
    {
        parent::__construct();
        $this->AdminModel = new AdminModel();
        $this->AdminUserModel = new AdminUserModel();
        $this->AdminTemplateModel = new AdminTemplateModel();
        $this->AdminClientModel = new AdminClientModel();
        $this->Mailer = new Mailer();
    }

    public function getMasterList()
    {
        try {
            Logger::error(json_encode($this->input), []);
            $rules = ['master' => array("rules" => 'required|max_length[100]', 'label' => "Master Name")];
            $validation = $this->validateReqData($rules, $this->input);
            if (empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            if (!$validation['valid']) {
                $this->sendResponse(array('code' => 400, 'message' => $this->getFirstValidationError(), 'data' => $validation['validation_error']));
            }
            switch (strtolower($this->input['master'])) {
                case 'client':
                    $rsp = $this->AdminClientModel->getClientMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'plan_log':
                    $rsp = $this->AdminClientModel->getClientPlanLogs($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'payment_log':
                    $rsp = $this->AdminClientModel->getClientPaymentLogs($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'plan':
                    $rsp = $this->AdminModel->getPlanMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'menu':
                    $rsp = $this->AdminModel->getMenuMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'client-menus':
                    $rsp = $this->AdminModel->getClientMenuMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'user':
                    $rsp = $this->AdminUserModel->getUserMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type'], $this->logged_user->id);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'template':
                    $rsp = $this->AdminTemplateModel->getTemplateMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'template_assign':
                    $rsp = $this->AdminTemplateModel->getTemplateAssignedList("1=1", $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'notification':
                    $rsp = $this->AdminModel->getNotificationLogList($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'country':
                    $rsp = $this->AdminModel->getCountryMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'state':
                    $rsp = $this->AdminModel->getStateMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'courier-master':
                    $rsp = $this->AdminModel->getCourierMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'payment-gateway':
                    $rsp = $this->AdminModel->getPaymentGatewayMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                case 'api-provider':
                    $rsp = $this->AdminModel->getApiProviderMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));

                case 'whatsapp-provider':
                    $rsp = $this->AdminModel->getWhatsAppProviderMaster($this->input['search'], $this->input['page_no'], $this->input['limit'], $this->input['sort_by'], $this->input['sort_type']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data'], 'count' => $rsp['count']));
                default:
                    throw new \Exception("Invalid master name");
                    break;
            }
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function getMasterData()
    {
        try {
            $rules = [
                'master' => array("rules" => 'required|max_length[100]', 'label' => "Master Name"),
            ];
            $validation = $this->validateReqData($rules, $this->input);
            if (empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            if (!$validation['valid']) {
                $this->sendResponse(array('code' => 400, 'message' => 'Validation Error', 'data' => $validation['validation_error']));
            }
            switch (strtolower($this->input['master'])) {
                case 'client':
                case 'home':
                    $rsp = $this->AdminClientModel->getClientData($this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $rmkey = ['password'];
                    foreach ($rmkey as $key) {
                        unset($rsp['data'][$key]);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'plan':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_plan_master"], "id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'country':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_country_master"], "country_id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'state':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_state_master"], "state_id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'menu':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_menu_master"], "menu_id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'client-menus':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["client_menu_master"], "menu_id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'template':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables['admin_template'], "id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'template_assign':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables['admin_template_assign'], "id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'user':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_user_master"], "id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $rmkey = ['password', 'token', 'email_otp', 'otp_generation_time'];
                    foreach ($rmkey as $key) {
                        unset($rsp['data'][$key]);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'notification':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_email_sms_logs"], "id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'courier-master':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_courier_api_master"], "id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'payment-gateway':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_payment_gateway_master"], "id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'api-provider':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_lead_source_api_provider"], "id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'whatsapp-provider':
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["whatsapp_solution_providers"], "id=" . $this->input['id']);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    if(!empty($rsp['data'])) {
                        // $rsp['data']['template_message'] = !empty($rsp['data']['template_message']) ? json_encode(stripslashes($rsp['data']['template_message'])) : "";
                        // $rsp['data']['text_message'] = !empty($rsp['data']['text_message']) ? json_encode(stripslashes($rsp['data']['text_message'])) : "";
                        // $rsp['data']['attachment_message'] = !empty($rsp['data']['attachment_message']) ? json_encode(stripslashes($rsp['data']['attachment_message'])) : "";
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                default:
                    throw new \Exception("Invalid master name");
                    break;
            }
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function getOptionList()
    {
        try {
            $rules = [
                'master' => array("rules" => 'required|max_length[100]', 'label' => "Master Name"),
            ];
            $validation = $this->validateReqData($rules, $this->input);
            if (empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            if (!$validation['valid']) {
                $this->sendResponse(array('code' => 400, 'message' => 'Validation Error', 'data' => $validation['validation_error']));
            }
            switch (strtolower($this->input['master'])) {
                case 'plan':
                    $rsp = $this->AdminModel->getPlanList();
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'parent_menu':
                    $rsp = $this->AdminUserModel->getAdminParentMenuList(1, 0);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'client_parent_menu':
                    $rsp = $this->AdminModel->getClientParentMenuList();
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'managers':
                    $rsp = $this->AdminUserModel->getManagerList($this->logged_user->id);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'country':
                    $rsp = $this->AdminModel->getCountryList();
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'state':
                    $country_id = NULL;
                    if (!empty($this->input['filter'])) {
                        if (!empty($this->input['filter']['country_id'])) {
                            $country_id = $this->input['filter']['country_id'];
                        }
                    }
                    $rsp = $this->AdminModel->getStateList($country_id);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'template_type':
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => [["id" => "SMS", "name" => "SMS/WhatsApp"], ["id" => "Email", "name" => "Email"]]));
                case 'template_vars':
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $this->AdminTemplateModel->template_vars));
                case 'template_for':
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $this->AdminTemplateModel->template_for));
                case 'template':
                    $rsp = $this->AdminTemplateModel->getTemplateList();
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
                case 'validity_period':
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $this->AdminModel->validity_period));
                    break;
                case 'whatsapp_solution_provider':
                    $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $this->AdminModel->whatsapp_solution_provider));
                    break;
                default:
                    throw new \Exception("Invalid master name");
                    break;
            }
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function checkDuplicateRecord()
    {
        try {
            $rules = ['master' => array("rules" => 'required|max_length[100]', 'label' => "Master Name")];
            $validation = $this->validateReqData($rules, $this->input);
            if (empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            if (!$validation['valid']) {
                $error_msg = '';
                foreach ($validation['validation_error'] as $error) {
                    $error_msg = $error;
                    break;
                }
                $this->sendResponse(array('code' => 400, 'message' => $error_msg, 'data' => null));
            }
            $dedupeRs = $this->AdminModel->checkDuplicateData($this->input['master'], $this->input);
            if (empty($dedupeRs['status'])) {
                throw new \Exception($dedupeRs['error']);
            } else if($this->input['master'] == 'client') {
                $dedupeRs = $this->AdminModel->checkDuplicateData('client_users_master', $this->input);
                if(empty($dedupeRs['status'])) {
                    throw new \Exception($dedupeRs['error']);
                }    
            }
            if (!empty($dedupeRs['exist'])) {
                $this->sendResponse(array('code' => 409, 'message' => $dedupeRs['error'], 'data' => NULL));
            } else {
                $this->sendResponse(array('code' => 200, 'message' => 'Duplicate checked succssfully', 'data' => NULL));
            }
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function saveRecord()
    {
        try {
            $rules = ['master' => array("rules" => 'required|max_length[100]', 'label' => "Master Name")];
            $master_rules = $this->AdminModel->getRules($this->input['master'], $this->input);
            if (empty($master_rules['status'])) {
                throw new \Exception($master_rules['error']);
            }
            $rules  = array_merge($rules, $master_rules['rules']);
            $validation = $this->validateReqData($rules, $this->input);
            if (empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            if (!$validation['valid']) {
                $error_msg = '';
                foreach ($validation['validation_error'] as $error) {
                    $error_msg = $error;
                    break;
                }
                $this->sendResponse(array('code' => 400, 'message' => $error_msg, 'data' => null));
            }
            $data = $this->input;
            unset($data['master']);

            $dedupeRs = $this->AdminModel->checkDuplicateData($this->input['master'], $data);
            if (empty($dedupeRs['status'])) {
                throw new \Exception($dedupeRs['error']);
            }

            if ($this->input['master'] == 'client') {
                $resp = $this->AdminClientModel->saveClientData($data);
                if (empty($resp['status'])) {
                    throw new \Exception($resp['error']);
                }
                $this->sendResponse(array('code' => 200, 'message' => 'Record saved succssfully', 'data' => $resp['data']));
            } else if ($this->input['master'] == 'notification') {
                $data['body'] = $this->input['message_body'];
                $resp = $this->AdminModel->saveMasterData($this->input['master'], $data);
                if (empty($resp['status'])) {
                    throw new \Exception($resp['error']);
                }
                $this->Kafkam->sendMessage("sanordo_send_admin_notifications", ['log_id'=>$resp['insert_id']]);
                // $worker_file = __DIR__ . "/../../Worker/notification.php";
                // Logger::debug('worker_file::' . $worker_file, []);
                // $cmd = 'php ' . $worker_file . ' "' . $resp['insert_id'] . '" > /dev/null 2>&1 &';
                // exec($cmd);
                // Logger::debug('worker_file_command::' . $cmd, []);
                $this->sendResponse(array('code' => 200, 'message' => 'Record saved succssfully', 'data' => $resp['insert_id']));
            } else {
                $resp = $this->AdminModel->saveMasterData($this->input['master'], $data);
                if (empty($resp['status'])) {
                    throw new \Exception($resp['error']);
                }
                $this->sendResponse(array('code' => 200, 'message' => 'Record saved succssfully', 'data' => ['id' => $resp['insert_id']]));
            }
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function updateRecord()
    {
        try {
            $rules = ['master' => array("rules" => 'required|max_length[100]', 'label' => "Master Name")];
            $master_rules = $this->AdminModel->getRules($this->input['master'], $this->input);
            if (empty($master_rules['status'])) {
                throw new \Exception($master_rules['error']);
            }
            $rules  = array_merge($rules, $master_rules['rules']);
            $validation = $this->validateReqData($rules, $this->input);
            if (empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            if (!$validation['valid']) {
                $this->sendResponse(array('code' => 400, 'message' => 'Validation Error', 'data' => $validation['validation_error']));
            }
            $data = $this->input;
            unset($data['master']);

            $dedupeRs = $this->AdminModel->checkDuplicateData($this->input['master'], $data);
            if (empty($dedupeRs['status'])) {
                throw new \Exception($validation['error']);
            }

            if ($this->input['master'] == 'client') {
                $resp = $this->AdminClientModel->updateClientData($data);
                if (empty($resp['status'])) {
                    throw new \Exception($resp['error']);
                }
                $this->sendResponse(array('code' => 200, 'message' => 'Record updated succssfully', 'data' => $resp['data']));
            } else {
                $cond = $this->AdminModel->getUpdateCondition($this->input['master'], $data);
                if (empty($cond['status'])) {
                    throw new \Exception($cond['error']);
                }
                $resp = $this->AdminModel->updateMasterData($this->input['master'], $data, $cond['data']);
                if (empty($resp['status'])) {
                    throw new \Exception($resp['error']);
                }
            }
            $this->sendResponse(array('code' => 200, 'message' => 'Record updated succssfully', 'data' => $cond['data']));
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function deleteRecord()
    {
        try {
            $rules = ['master' => array("rules" => 'required|max_length[100]', 'label' => "Master Name")];
            $validation = $this->validateReqData($rules, $this->input);
            if (empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            if (!$validation['valid']) {
                $this->sendResponse(array('code' => 400, 'message' => 'Validation Error', 'data' => $validation['validation_error']));
            }
            $data = $this->input;
            unset($data['master']);
            if($this->input['master'] == 'client') {
                $resp = $this->AdminClientModel->deleteClient($data['id']);
                if (empty($resp['status'])) {
                    throw new \Exception($resp['error']);
                }
                $this->sendResponse(array('code' => 200, 'message' => 'Record deleted succssfully', 'data' => null));
            } else {
                $cond = $this->AdminModel->getDeleteCondition($this->input['master'], $data);
                if (empty($cond['status'])) {
                    throw new \Exception($cond['error']);
                }
                if ($this->input['master'] == 'courier-master') {
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_courier_api_master"], "id=" . $data['id']);
                }
                if ($this->input['master'] == 'payment-gateway') {
                    $rsp = $this->AdminModel->getMasterData($this->AdminModel->tables["admin_payment_gateway_master"], "id=" . $data['id']);
                }
                $resp = $this->AdminModel->deleteMasterData($this->input['master'], $cond['data']);
                if (empty($resp['status'])) {
                    throw new \Exception($resp['error']);
                }
                if ($this->input['master'] == 'courier-master' || $this->input['master'] == 'payment-gateway') {
                    $this->deleteImg($rsp['data'], $this->input['master']);
                }
                $this->sendResponse(array('code' => 200, 'message' => 'Record deleted succssfully', 'data' => $resp['affected_rows']));
            }
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function exportRecord()
    {
        try {
            $rules = [
                'master' => array("rules" => 'required|max_length[100]', 'label' => "Master Name"),
                'columns' => array("rules" => 'required', 'label' => "Column(s) to export"),
                'id' => array("rules" => 'required', 'label' => "Row(s) to export"),
            ];
            $validation = $this->validateReqData($rules, $this->input);
            if (empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            if (!$validation['valid']) {
                $this->sendResponse(array('code' => 400, 'message' => $this->getFirstValidationError(), 'data' => $validation['validation_error']));
            }
            $dest_path = NULL;
            $file_path = NULL;
            $file_name = NULL;
            switch (strtolower($this->input['master'])) {
                case 'client':
                    $export_cols = Utilities::getExportColumnFieldAlias($this->input['columns'], $this->AdminClientModel->columns);
                    if (empty($export_cols)) {
                        throw new \Exception("Columns not getting to be exported");
                    }
                    $file_name   = "SAN_ORDO_CLIENT_" .  date('YMDHis') . '.csv';
                    $file_path   = Utilities::getCsvExportPath($file_name);
                    $rsp = $this->AdminClientModel->getExportClientList($export_cols, $this->input['id'], $file_path);
                    if (!$rsp['status']) {
                        throw new \Exception($rsp['error']);
                    }
                    $dest_path   = Utilities::getCsvDownloadPath($file_name);
                    break;
                default:
                    throw new \Exception("Invalid master name");
                    break;
            }
            if (!empty($file_path) && !empty($dest_path)) {
                // if (!file_exists($file_path)) {
                //     throw new \Exception("Unable to export data. Unable to read CSV File $file_path");
                // }
                $scriptPath = $_ENV['EXPORT_MOVE_SCRIPT_PATH'];
                $cmd = "sudo $scriptPath " . escapeshellarg($file_path) . " 2>&1";
                $output = shell_exec($cmd);
                if ($output) {
                    $new_file_path = Utilities::getCsvRelativePath($file_name);
                    $this->sendResponse(array('code' => 200, 'message' => $output, 'data' => ["file_path" => $new_file_path, "file_name" => $file_name]));
                } else {
                    throw new \Exception("Unable to export data. Failed to copy the file to Destination" . $output);
                }
            } else {
                throw new \Exception("Unable to export data");
            }
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function saveTemplateFor()
    {
        try {
            $rules = ['assignments' => array("rules" => 'required', 'label' => "Template Assignment list")];
            $validation = $this->validateReqData($rules, $this->input);
            if (empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            if (!$validation['valid']) {
                $this->sendResponse(array('code' => 400, 'message' => 'Validation Error', 'data' => $validation['validation_error']));
            }

            $master_rules = $this->AdminModel->getRules('template_assign', $this->input);
            if (empty($master_rules['status'])) {
                throw new \Exception($master_rules['error']);
            }
            foreach ($this->input['assignments'] as $index => $assignment) {
                $validation = $this->validateReqData($master_rules['rules'], $assignment);
                if (empty($validation['status'])) {
                    throw new \Exception($validation['error']);
                }
                if (!$validation['valid']) {
                    $this->sendResponse(array('code' => 400, 'message' => 'Validation Error. Please check all required fields', 'data' => $validation['validation_error']));
                }
            }
            $resp = $this->AdminModel->deleteMasterData('template_assign', "1=1");
            if (empty($resp['status'])) {
                throw new \Exception($resp['error']);
            }
            $resp = $this->AdminTemplateModel->addTemplateFor($this->input['assignments']);
            if (empty($resp['status'])) {
                throw new \Exception($resp['error']);
            }
            $this->sendResponse(array('code' => 200, 'message' => 'Record saved succssfully', 'data' => null));
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function getAppSettings()
    {
        try {
            $rsp = $this->AdminModel->getAppSettings();
            if (!$rsp['status']) {
                throw new \Exception($rsp['error']);
            }
            $this->sendResponse(array('code' => 200, 'message' => null, 'data' => $rsp['data']));
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function checkSmtpSettings()
    {
        try {
            $rules = [
                'smtp_email_id' => array("rules" => 'required|max_length[150]|email', 'label' => "SMTP Email ID"),
                'smtp_email_password' => array("rules" => 'required|max_length[100]', 'label' => "SMTP Password"),
                'smtp_email_server' => array("rules" => 'required|max_length[100]', 'label' => "SMTP Server"),
                'smtp_port' => array("rules" => 'required|integer|max_length[10]', 'label' => "SMTP Port"),
            ];
            $validation = $this->validateReqData($rules, $this->input);
            if (empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            $enable_ssl = !empty($this->input['smtp_enable_ssl']) ? true : false;
            $verify_ssl = !empty($this->input['smtp_verify_ssl']) ? true : false;
            $this->Mailer->configure($this->input['smtp_email_server'], $this->input['smtp_email_id'], $this->input['smtp_email_password'], $this->input['smtp_port'], $enable_ssl, $verify_ssl);
            $data = [
                'to' => [['email_id' => 'vinod.kumar@sansoftwares.in', 'name' => 'Vinod'], ['email_id' => 'vinodkumarnsvk@gmail.com', 'name' => 'Vinod K']],
                'subject' => 'Test Mail',
                'body' => 'SMTP Setting works'
            ];
            $resp = $this->Mailer->sendEmail($data);
            if (empty($resp['status'])) {
                throw new \Exception($resp['error']);
            }
            $this->sendResponse(array('code' => 200, 'message' => 'Email Sent', 'data' => $resp));
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function uploadImg()
    {
        try {
            if (empty($_FILES['upload_img'])) {
                throw new \Exception("Please select image to upload");
            }
            if (empty($this->input['id'])) {
                throw new \Exception("ID is required to upload image");
            }
            $max_file_size = Main::getLogoUploadMaxSize();
            $allowed_file_types = Main::getAllowedLogoFileTypes();
            if ($_FILES["upload_img"]["size"] > Main::getLogoUploadMaxSize()) {
                throw new \Exception('File size should be less than ' . ($max_file_size / 1024) . ' KB');
            }
            if (!in_array($_FILES["upload_img"]["type"], $allowed_file_types)) {
                throw new \Exception('Only ' . implode(", ", $allowed_file_types) . ' files are allowed.');
            }
            $uploadDir = Main::getUploadPath();
            $uploadFolder = Main::getUploadFolder();
            $uploadBasePath = $uploadDir . '/admin-docs/';
            if (!is_dir($uploadBasePath)) {
                mkdir($uploadBasePath, 0755, true);
            }
            if (!is_dir($uploadBasePath)) {
                throw new \Exception("Upload path does not exist");
            }
            $file_name = $this->input['type'] . '_' . $this->input['id'] . '.' . pathinfo($_FILES['upload_img']['name'], PATHINFO_EXTENSION);

            if (!move_uploaded_file($_FILES['upload_img']['tmp_name'], $uploadBasePath . $file_name)) {
                throw new \Exception("Error in uploading logo file");
            }
            $img_path = $uploadFolder . '/admin-docs/' . $file_name;
            $data = ['img' => $img_path];

            $master = $this->input['master'];
            $primaryKey = $this->input['primary'];
            $retData = $this->AdminModel->updateMasterData($master, $data, [$primaryKey => $this->input['id']]);
            if (!$retData['status']) {
                throw new \Exception($retData['error']);
            }
            $this->sendResponse(array('code' => 200, 'message' => 'Image uploaded successfully', 'data' => ['img_path' => $img_path]));
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }

    public function deleteImg($data)
    {
        try {
            if ($data['img']) {
                $previousFilePath = $_ENV['SERVER_PATH'] . '/' . $data['img'];
                if (file_exists($previousFilePath)) {
                    if (!unlink($previousFilePath)) {
                        return array('status' => false, 'error' => 'Failed to delete previous file.');
                    }
                }
            }
            return ['status' => true];
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            return ["status" => false, "error" => $e->getMessage()];
        }
    }
}
