<?php
defined('BASEPATH') or exit('No direct script access allowed');

class User extends CI_Controller
{

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *         http://example.com/index.php/welcome
     *    - or -
     *         http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public $fromEmail = null;
    public $fromName = null;
    protected $columnNames = [
    "roleID" => ["table" => "user_role_master", "alias" => "r", "column" => "roleName", "key2" => "roleID", "select" => "t.roleID as roleID, r.roleName as roleName"],
    ];

    protected $customCol = [
        "default_company" => ["table" => "info_settings", "alias" => "dc", "column" => "companyName", "key2" => "infoID", "select" => ""],
            "modified_by" => ["table" => "admin", "alias" => "am", "column" => "name", "key2" => "adminID", "select" => ""],
            "created_by" => ["table" => "admin", "alias" => "ad", "column" => "name", "key2" => "adminID", "select" => ""],
    ];
    protected $Model;
    public $menuID;
    var $defaultColumns=["name","adminID","email"];
    public function __construct(){
        parent::__construct();
        $this->load->database();
        $this->load->helper('form');
        $this->load->model('SearchAdminModel');
        $this->load->model('CommonModel');
        $this->load->model('LoginModel');
        $this->load->library("pagination");
        
        $this->load->helper(['url','security']);
        $this->load->model('core/CommonModelNew');
        $this->Model = $this->CommonModelNew;
        $this->load->library("ValidateData");
        $this->load->library('core/FilterEngine', [], 'filterengine');
        $this->load->library('core/FilterBuilder', [], 'filterbuilder');
        $this->load->library('Filters',['customCol' => $this->customCol,'columnNames'=>$this->columnNames], 'filters');
        if (!$this->config->item('development')) {
            $this->load->library("Emails");
        }
        $this->load->library("Datatables");
        $this->load->library("Filters");
    }
    
    public function profileUpdate()
    {
        $this->access->checkTokenKey();
        $this->response->decodeRequest();
        $userDetails = array();
        $where = array();
        $userDetails['name'] = $this->validatedata->validate('name', 'name', true, '', array());
        $userDetails['contactNo'] = $this->validatedata->validate('contactNo', 'contact No', false, '', array());
        $userDetails['whatsappNo']= $this->validatedata->validate('whatsappNo', 'Whatsapp No.', false, '', array());
        $userDetails['dateOfBirth']= $this->validatedata->validate('dateOfBirth', 'Birth Date', false, '', array());
        $userDetails['time_zone']= $this->validatedata->validate('time_zone', 'Time Zone', false, '', array());
        $userDetails['address']= $this->validatedata->validate('address', 'Address', false, '', array());
        $adminID =$this->input->post('SadminID');
        $where['adminID'] = $adminID;
        if (!isset($adminID) && empty($adminID)) {
            $status['msg'] = $this->systemmsg->getErrorCode(304);
            $status['statusCode'] = 304;
            $status['data'] = array();
            $status['flag'] = 'F';
            $this->response->output($status, 200);
        } else {
            
            $isupdated = $this->CommonModel->updateMasterDetails('admin',$userDetails,$where);
            if($isupdated){
                $status['msg'] = "sucess";
                $status['statusCode'] = 200;
                $status['data'] = array();
                $status['flag'] = 'S';
                $this->response->output($status, 200);
            } else {
                $status['msg'] = $this->systemmsg->getErrorCode(305);
                $status['statusCode'] = 305;
                $status['data'] = array();
                $status['flag'] = 'F';
                $this->response->output($status, 200);
            }
        }
    }
     public function profileData()
    {
        $this->access->checkTokenKey();
        $this->response->decodeRequest();
        $adminID =$this->input->post('SadminID');
        $where['adminID'] = $adminID;
        $userData = $this->CommonModel->getMasterDetails("admin", $select = "name,contactNo,whatsappNo,dateOfBirth,time_zone,address,photo", $where);
        if($userData){
            $status['msg'] = "sucess";
            $status['statusCode'] = 200;
            $status['data'] =$userData;
            $status['flag'] = 'S';
            $this->response->output($status, 200);
        } else {
            $status['msg'] = "Fail";
            $status['statusCode'] = 305;
            $status['data'] = array();
            $status['flag'] = 'F';
            $this->response->output($status, 200);
        }
    }
    
    public function setModuleDefaultView()
    {
        $this->access->checkTokenKey();
        $this->response->decodeRequest();
        $json = $this->input->post('jsonForm');
        $adminID = $this->input->post('SadminID');
        $adminDetails['user_setting'] = $json;
        // print_r($json);exit;
        // print_r($adminDetails);exit;
        $iscreated = $this->CommonModel->updateMasterDetails('admin', $adminDetails, array('adminID' => $adminID));
        if (!$iscreated) {
            $status['msg'] = $this->systemmsg->getErrorCode(998);
            $status['statusCode'] = 998;
            $status['data'] = array();
            $status['flag'] = 'F';
            $this->response->output($status, 200);
        } else {
            $status['msg'] = $this->systemmsg->getSucessCode(400);
            $status['statusCode'] = 400;
            $status['data'] = array();
            $status['flag'] = 'S';
            $this->response->output($status, 200);
        }
    }
    public function updateToken()
    {
        $this->access->checkTokenKey();
        $this->response->decodeRequest();
        $adminID = trim($this->input->post("adminID"));
        $fToken = trim($this->input->post("fToken"));
        $adminDetails = array();
        $where = array();
        $where['adminID'] = $adminID;
        $adminDetails['fToken'] = $fToken;
        $isupdated = $this->SearchAdminModel->updateAdminDetails($adminDetails, $adminID);
        if (!$isupdated) {
            $status['msg'] = $this->systemmsg->getErrorCode(998);
            $status['statusCode'] = 998;
            $status['data'] = array();
            $status['flag'] = 'F';
            $this->response->output($status, 200);
        } else {

            $status['msg'] = "Token Updated Successfully";
            $status['statusCode'] = 400;
            $status['data'] = array();
            $status['flag'] = 'S';
            $this->response->output($status, 200);
        }
    }
    public function setprofilePic()
    {
        if (empty($_FILES['profile_pic'])) {
            $this->response->output([
                'flag' => 'F',
                'msg'  => 'No file uploaded'
            ], 200);
            return;
        }

        $memberID = $this->input->post('SadminID');

        if (!$memberID) {
            $this->response->output([
                'flag' => 'F',
                'msg'  => 'Invalid Admin ID'
            ], 200);
            return;
        }

        // 🔹 Base directory
        $basePath = rtrim($this->config->item("imagesPATH"), '/').'/user_'.$memberID.'/profilePic/';

        // 🔹 Ensure directory exists
        if (!is_dir($basePath)) {
            mkdir($basePath, 0775, true);
        }

        $config = [
            'upload_path'   => $basePath,
            'allowed_types' => 'jpg|jpeg|png|webp',
            'encrypt_name'  => FALSE,
            'max_size'      => 2048, // KB
            'file_name' => 'profile_'.$memberID,
            'overwrite'=>true,
        ];
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('profile_pic')) {
            $this->response->output([
                'flag' => 'F',
                'msg'  => strip_tags($this->upload->display_errors())
            ], 200);
            return;
        }
        $data = $this->upload->data();
        // 🔹 Save relative path or filename
        $relativePath = 'user_' . $memberID.'/profilePic/'.$data['file_name'];

        $isupdated = $this->CommonModel->updateMasterDetails(
            'admin',
            ['photo' => $relativePath],
            ['adminID' => $memberID]
        );

        if ($isupdated) {
            $this->response->output([
                'flag' => 'S',
                'msg'  => 'Profile picture updated',
                'data' => [
                    'photo' => $relativePath
                ]
            ], 200);
        } else {
            $this->response->output([
                'flag' => 'F',
                'msg'  => $this->systemmsg->getErrorCode(305)
            ], 200);
        }
    }
    public function deleteProfilePic()
    {
        $this->access->checkTokenKey();
        $this->response->decodeRequest();

        $memberID = $this->input->post('user_id');

        if (!$memberID) {
            $this->response->output([
                'flag' => 'F',
                'msg'  => $this->systemmsg->getErrorCode(305)
            ], 200);
        }

        // 🔹 Absolute file path
        $filePath = rtrim($this->config->item("imagesPATH"), '/')
            . '/user_' . $memberID
            . '/profilePic/profile_' . $memberID . '.jpg';

        // 🔹 Delete file first (safe)
        if (file_exists($filePath)) {
            @unlink($filePath);
        }

        // 🔹 Update DB (set photo = NULL)
        $isUpdated = $this->CommonModel->updateMasterDetails(
            'admin',
            ['photo' => NULL],
            ['adminID' => $memberID]
        );

        if ($isUpdated) {
            $this->response->output([
                'flag' => 'S',
                'msg'  => 'Profile picture removed successfully',
                'data' => []
            ], 200);
        } else {
            $this->response->output([
                'flag' => 'F',
                'msg'  => $this->systemmsg->getErrorCode(305)
            ], 200);
        }
    }

    public function verifyUser()
    {
        $this->response->decodeRequest();
        $adminDetails = $adminEextraDetails = array();
        $where = array();
        $adminID = $this->validatedata->validate('userID', 'userID', true, '', array());
        $password = $this->validatedata->validate('password', 'password', true, '', array());

        $confirmPassword = $this->validatedata->validate('confirmPassword', 'confirmPassword', true, '', array());
        $md_vfCode = $this->validatedata->validate('vfcode', 'vfcode', true, '', array());
        $where['adminID'] = $adminID;
        if (!isset($adminID) && empty($adminID)) {
            $status['msg'] = $this->systemmsg->getErrorCode(304);
            $status['statusCode'] = 304;
            $status['data'] = array();
            $status['flag'] = 'F';
            $this->response->output($status, 200);
        } else {
            $getOtp = $this->CommonModel->getMasterDetails("admin", $select = "otp,isVerified", $where);
            if (isset($getOtp) && !empty($getOtp)) {
                $isVerified = $getOtp[0]->isVerified;
                $dbotp = md5($getOtp[0]->otp);
                $dbotp = substr($dbotp, 0, 10);

                if (($md_vfCode == $dbotp && $dbotp != 0)) {
                    if ($password == $confirmPassword) {
                        $adminEextraDetails['otp'] = 0;
                        $adminEextraDetails['isverified'] = 'Y';
                        $isupdated = $this->SearchAdminModel->updateAdminDetails($adminEextraDetails, $adminID);
                        $this->updatePassword($adminID, $confirmPassword, $isVerified);
                    } else {
                        $status['msg'] = $this->systemmsg->getErrorCode(301);
                        $status['statusCode'] = 301;
                        $status['data'] = array();
                        $status['flag'] = 'F';
                        $this->response->output($status, 200);
                    }
                } else {
                    $status['msg'] = $this->systemmsg->getErrorCode(304);
                    $status['statusCode'] = 304;
                    $status['data'] = array();
                    $status['flag'] = 'F';
                    $this->response->output($status, 200);
                }
            } else {
                $status['msg'] = $this->systemmsg->getErrorCode(305);
                $status['statusCode'] = 305;
                $status['data'] = array();
                $status['flag'] = 'F';
                $this->response->output($status, 200);
            }
        }
    }
    public function validateOtp($adminID = '')
    {
        $adminDetails = $adminEextraDetails = array();
        $where = array();
        $where['adminID'] = $adminID;
        $this->response->decodeRequest();
        $otp = $this->validatedata->validate('otp', 'otp', true, '', array());
        $password = $this->validatedata->validate('password', 'password', true, '', array());
        $confirmPassword = $this->validatedata->validate('confirmPassword', 'confirmPassword', true, '', array());
        $getOtp = $this->CommonModel->getMasterDetails("admin", $select = "otp", $where);
        if (($otp == $getOtp[0]->otp && $otp != 0)) {
            if ($password == $confirmPassword) {
                $adminEextraDetails['otp'] = 0;
                $isupdated = $this->SearchAdminModel->updateAdminDetails($adminEextraDetails, $adminID);
                $this->updatePassword($adminID, $password);
            } else {
                $status['msg'] = $this->systemmsg->getErrorCode(301);
                $status['statusCode'] = 301;
                $status['data'] = array();
                $status['flag'] = 'F';
                $this->response->output($status, 200);
            }
        } else {
            $status['msg'] = $this->systemmsg->getErrorCode(302);
            $status['statusCode'] = 302;
            $status['data'] = array();
            $status['flag'] = 'F';
            $this->response->output($status, 200);
        }
    }
    public function resetPasswordRequest()
    {
        $this->response->decodeRequest();
        //print_r($_POST); exit;
        $email = $this->validatedata->validate('email', 'Email-Id', false, '', array());
        $userName = $this->validatedata->validate('username', 'User Name', false, '', array());
        if (isset($email) && !empty($email)) {
            $userName = $email;
        }
        $password = $this->validatedata->validate('password', 'Password', false, '', array());
        $checkEmail = $this->LoginModel->verifyUserDetails($userName, $password);
        if (empty($checkEmail)) {
            (isset($email) && !empty($email)) ? $errorCode = 328 : $errorCode = 325;
            $status['msg'] = $this->systemmsg->getErrorCode($errorCode);
            $status['statusCode'] = $errorCode;
            $status['data'] = array();
            $status['flag'] = 'F';
            $this->response->output($status, 200);
        } else {
            if (isset($email) && !empty($email)) {
                if ($checkEmail[0]->isVerified == 'N') {
                    $status['msg'] = $this->systemmsg->getErrorCode(327);
                    $status['statusCode'] = 327;
                    $status['data'] = array();
                    $status['flag'] = 'F';
                    $this->response->output($status, 200);
                }
            }
            $otp = rand(100000, 999999);
            $adminID = $checkEmail[0]->adminID;
            $this->getCompanyDetails($adminID);
            $adminEextraDetails = array("otp" => $otp);
            $adminEextraDetails['otp_exp_time'] = date('Y-m-d H:i:s', strtotime('+30 minutes'));
            $verificationCode = md5($otp);
            $verificationCode = substr($verificationCode, 0, 10);
            $baseURL = $this->config->item("app_url") . "verify-details?&vfcode=" . $verificationCode . "&type=pb&&auth-id=" . $adminID;

            $isupdated = $this->SearchAdminModel->forgotPassword($adminEextraDetails, $adminID);
            if (!$isupdated) {
                $status['msg'] = $this->systemmsg->getErrorCode(296);
                $status['statusCode'] = 296;
                $status['data'] = array();
                $status['flag'] = 'F';
                $this->response->output($status, 200);
            } else {
                $isEmailSend = $this->sendEmailsToUser("forgotPasswordOTPSendTemp", $checkEmail[0]->email, $checkEmail[0]->userName, $baseURL, $checkEmail[0]->name);
                if ($isEmailSend) {
                    $status['data'] = array("userID" => $adminID);
                    $status['msg'] = $this->systemmsg->getSucessCode(424);
                    $status['statusCode'] = 400;
                    $status['flag'] = 'S';
                    $this->response->output($status, 200);
                } else {
                    $status['msg'] = $this->systemmsg->getErrorCode(296);
                    $status['statusCode'] = 296;
                    $status['data'] = array();
                    $status['flag'] = 'F';
                    $this->response->output($status, 200);
                }

            }
        }
    }
    public function ChangePassword()
    {
        $this->access->checkTokenKey();
        $this->response->decodeRequest();
        $adminID = $this->input->post('SadminID');
        $isUpdatePassword = $this->input->post('isUpdatePassword');
        //print_r($_POST); exit;
        if (isset($isUpdatePassword) && !empty($isUpdatePassword)) {
            if ($isUpdatePassword == 'yes') {
                $oldPass = $this->input->post('current_password');
                $newPass = $this->input->post('new_password');
                $confirmNewPass = $this->input->post('confirm_password');
                $newPass = $this->validatePass($adminID, $oldPass, $newPass, $confirmNewPass);
                $adminDetails['password'] = $newPass;
            }
        }
        $iscreated = $this->SearchAdminModel->updateAdminDetails($adminDetails, $adminID);
        if (!$iscreated) {
            $status['msg'] = $this->systemmsg->getErrorCode(998);
            $status['statusCode'] = 998;
            $status['data'] = array();
            $status['flag'] = 'F';
            $this->response->output($status, 200);
        } else {
            $status['msg'] = $this->systemmsg->getSucessCode(400);
            $status['statusCode'] = 400;
            $status['data'] = array();
            $status['flag'] = 'S';
            $this->response->output($status, 200);
        }
    }
    public function validatePass($adminID = '', $oldPass = '', $newPass = '', $cNewPass = '')
    {
        $where = array("adminID" => $adminID);
        $passwordDB = $this->CommonModel->getMasterDetails('admin', 'password', $where);
        if (isset($passwordDB) && !empty($passwordDB)) {
            $oldPass = md5($oldPass);
            //$oldPass = substr($oldPass, 0, 30);
            if ($passwordDB[0]->password == $oldPass) {
                if ($newPass == $cNewPass) {
                    $newPass = md5($newPass);
                    //$newPass = substr($newPass, 0, 30);
                    //if ($newPass != $cNewPass) {
                        return $newPass;
                    //}
                } else {
                    $status['msg'] = $this->systemmsg->getErrorCode(301);
                    $status['statusCode'] = 301;
                    $status['data'] = array();
                    $status['flag'] = 'F';
                    $this->response->output($status, 200);
                }
            } else {
                $status['msg'] = $this->systemmsg->getErrorCode(316);
                $status['statusCode'] = 316;
                $status['data'] = array();
                $status['flag'] = 'F';
                $this->response->output($status, 200);
            }
        }
    }
    // public function avatar($userId)
    // {
    //     // $this->access->checkTokenKey();
    //     // $this->response->decodeRequest();
    //     //print $userId;exit;
    //     $user =$this->CommonModel->getMasterDetails('admin', 'adminID,photo',array("adminID"=>$userId));
    //     if (!$user || !$user[0]->photo) show_404();
    //     $filePath = rtrim($this->config->item("imagesPATH"), '/')."/".$user[0]->photo;
    //    // $filePath = FCPATH . 'uploads/' . $user->photo;
    //     if (!file_exists($filePath)) show_404();

    //     $lastModified = filemtime($filePath);
    //     $etag = md5($userId . $lastModified);

    //     if (
    //         isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
    //         $_SERVER['HTTP_IF_NONE_MATCH'] === $etag
    //     ) {
    //         header("HTTP/1.1 304 Not Modified");
    //         exit;
    //     }

    //     header("Content-Type: image/jpeg");
    //     header("Cache-Control: private, max-age=86400");
    //     header("ETag: $etag");
    //     header("Last-Modified: " . gmdate('D, d M Y H:i:s', $lastModified) . " GMT");

    //     readfile($filePath);
    //     exit;
    // }
    public function avatar($userId)
{
    // 1️⃣ Fetch user
    $user = $this->CommonModel->getMasterDetails(
        'admin',
        'adminID, photo',
        ['adminID' => $userId]
    );

    // 2️⃣ If no user OR no photo → 404
    if (!$user || empty($user[0]->photo)) {
        show_404();
    }

    // 3️⃣ Build file path
    $basePath = rtrim($this->config->item("imagesPATH"), '/');
    $filePath = $basePath . '/' . $user[0]->photo;

    // 4️⃣ File does not exist → 404
    if (!file_exists($filePath)) {
        show_404();
    }

    // 5️⃣ Get file info
    $lastModified = filemtime($filePath);
    $etag = md5($userId . $lastModified);

    // 6️⃣ Handle browser cache
    if (
        isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
        $_SERVER['HTTP_IF_NONE_MATCH'] === $etag
    ) {
        header("HTTP/1.1 304 Not Modified");
        exit;
    }

    // 7️⃣ Detect MIME type dynamically (IMPORTANT)
    $mime = mime_content_type($filePath);

    // 8️⃣ Send headers
    header("Content-Type: {$mime}");
    header("Content-Length: " . filesize($filePath));
    header("Cache-Control: private, max-age=86400");
    header("ETag: {$etag}");
    header("Last-Modified: " . gmdate('D, d M Y H:i:s', $lastModified) . " GMT");

    // 9️⃣ Output file
    readfile($filePath);
    exit;
}

}
