dahsboard_Model = new Dashboard_model(); $this->costcenter_model = new Costcenter_model(); $this->department_model = new Department_model(); $this->employeedetails_model = new employeedetails_model(); $this->user_model = new User_model(); $this->ipinvoice_model = new Ipinvoice_model(); $this->ipattachment_model = new Ipattachment_model(); $this->CreditNoteModel = new CreditNoteModel(); $this->CreditNotesItemsModel = new IpCreditNotesItemsModel(); $this->session = session(); helper('form'); //$this->load->library('form_validation'); $this->isLoggedIn(); } /** * This function used to load the first screen of the user */ public function index() { $this->global['pageTitle'] = 'Dashboard'; log_message('error', '#####Dashboard session name : ' . $this->session->get('name')); $data['EmpCount'] = $this->employeedetails_model->getEmployeeCount(); $data['UserCount'] = $this->dahsboard_Model->getUserCount(); $data['totalpurchaseorder'] = $this->dahsboard_Model->totalpurchaseorder(); $data['totalordervalue'] = $this->dahsboard_Model->totalordervalue(); $data['pendingpo'] = $this->dahsboard_Model->pendingpo(); $data['totalimportpo'] = $this->dahsboard_Model->totalimportpo(); $data['details'] = $this->dahsboard_Model->reqdetail(); $data['pending_details'] = $this->dahsboard_Model->req_pending(); $data['serviceprogress'] = $this->dahsboard_Model->serviceprogress(); $data['revenueprogress'] = $this->dahsboard_Model->revenueprogress(); $data['importprogress'] = $this->dahsboard_Model->importprogress(); $data['capitalprogress'] = $this->dahsboard_Model->capitalprogress(); //month-wise area chart $data['getTotalServicePoCount'] = $this->dahsboard_Model->getTotalServicePoCount(); $data['getTotalimportPoCount'] = $this->dahsboard_Model->getTotalimportPoCount(); $data['getTotalcapitalPoCount'] = $this->dahsboard_Model->getTotalcapitalPoCount(); $data['getTotalrevenuePoCount'] = $this->dahsboard_Model->getTotalrevenuePoCount(); //dashboard pie chart $data['importbudgt'] = $this->dahsboard_Model->importbudgt(); $data['servicebudgt'] = $this->dahsboard_Model->servicebudgt(); $data['revenuebudgt'] = $this->dahsboard_Model->revenuebudgt(); $data['capitalbud'] = $this->dahsboard_Model->capitalbud(); $data['typebal'] = []; // $this->dahsboard_Model->typebal(); /* HR DASHBOARD Controller Start*/ $data['totemp'] = $this->dahsboard_Model->totemp(); $data['totloan'] = $this->dahsboard_Model->totloan(); $data['totpay'] = $this->dahsboard_Model->totpay(); $data['totrec'] = $this->dahsboard_Model->totrec(); $data['emplist'] = $this->dahsboard_Model->emplist(); $date = $this->request->getPost("id"); $dates = date('Y-m'); $date = $dates . '-01'; $dat = date('d', strtotime("-1 days")); $WH = 'WH' . date('j', strtotime("-1 days")); $yesterday = $this->dahsboard_Model->attyesterday($WH, $date); $valuess = 0; foreach ($yesterday as $weekda => $value) { if ($value[$WH] == 0) { $valuess++; } } $data['today'] = $valuess; $daydate = date('Y-m', strtotime($date)); $daydate = $daydate . '-01'; $yesterday = $this->dahsboard_Model->attyesterday($WH, $daydate); $values = 0; $absEmp = array(); foreach ($yesterday as $weekda => $value) { if ($value[$WH] == 0) { $values++; $absendId = $value['EmpID']; $absendName = $value['FirstName']; $absEmp[] = $absendId . "-" . $absendName; //absend empid and name list } } $data['today'] = sizeof($absEmp); $data['abs_name'] = $absEmp; $OT = 'OT' . date('j', strtotime($date)); $CUR_month = date('t'); $toDayEmployee = $this->dahsboard_Model->yesterdayAllPersentEmpSalary($WH, $OT, $daydate); $EmpID = 0; $employeeSalary = 0; foreach ($toDayEmployee as $value) { $values = 0; $totalothour = 0; if ($value[$WH] != 0) { $totalothour = $value[$OT]; $values = 1; $Empid = $value['EmpID']; $totalEmployeePersent = $this->dahsboard_Model->persentEmployeeDetails($Empid); if (!empty($totalEmployeePersent)) { $HRA_Amount = $totalEmployeePersent[0]->HRA_Amount; $Basic_Pay = $totalEmployeePersent[0]->Basic_Pay; $totalsalary = $totalEmployeePersent[0]->TotalSalary; $dayFoodAmt = $totalEmployeePersent[0]->Food_Allowances; $Food_Allowances = $dayFoodAmt * $values; $daySalary = $Basic_Pay / $CUR_month; /**per day salary working hour**/ $dayHra = $HRA_Amount / $CUR_month; /** per day hra amount **/ $onehoursSalary = ($daySalary + $dayHra) / 8; /**one hour salay ot calculation**/ if ($totalothour != 0) /** if ot not equal zero **/ { $totSalayOT = $totalothour * $onehoursSalary; } else { $totSalayOT = 0; } $currentDaySalary = $daySalary * $values; /** current day salary working days calculation**/ $currentDayHra = $dayHra * $values; /** total working days hra calculations**/ $currentDatePF = $currentDaySalary + $currentDayHra + $totSalayOT; /** current date pf calculation**/ if ($totalsalary <= 20000) { $esiAmount = $currentDatePF * 1.75 / 100; /** esiamount not elgiable for 20000 **/ } else { $esiAmount = 0; } $pfAmount = $currentDaySalary * 12 / 100; /** pf amount per day**/ $salaryInCurrentdays = $currentDaySalary + $totSalayOT + $currentDayHra + $Food_Allowances; $salaryInCurrentday = $salaryInCurrentdays - ($esiAmount + $pfAmount); $employeeSalary += round($salaryInCurrentday); } } } //$salaryInCurrentday++; $data['employeeSalary'] = $employeeSalary; $working = array(); $overtime = array(); //$holid = array(); for ($i = 1; $i <= $dat; $i++) { $Working[] = 'WH' . $i; $overtime[] = 'OT' . $i; $CUR_month = date('t'); // foreach ($holiday as $value) // { // //$holid []= 'WH'.$value; // if($i==$value) { // $holid []=$value; // } // } } $WH = implode(",", $Working); $OT = implode(",", $overtime); $salarycurrentdate = array(); $toDayEmployee = $this->dahsboard_Model->dayAllPersentEmpSalary($WH, $OT, $date); $totalSalary = 0; $working = explode(",", $WH); $overtime = explode(",", $OT); foreach ($toDayEmployee as $value) { $values = 0; foreach ($working as $work) { // foreach ($overtime as $extra) { if ($value[$work] != 0 || $value['OT' . substr($work, 2)] != 0) { $totalothour = $value['OT' . substr($work, 2)]; $values = 1; $Empid = $value['EmpID']; $totalEmployeePersent = $this->dahsboard_Model->persentEmployeeDetails($Empid); if (!empty($totalEmployeePersent)) { $HRA_Amount = $totalEmployeePersent[0]->HRA_Amount; $Basic_Pay = $totalEmployeePersent[0]->Basic_Pay; $totalsalary = $totalEmployeePersent[0]->TotalSalary; $dayFoodAmt = $totalEmployeePersent[0]->Food_Allowances; //$allowances =$totalEmployeePersent[0]->Allowances; // $Allowances = $allowances * $values; $Food_Allowances = $dayFoodAmt * $values; $daySalary = $Basic_Pay / $CUR_month; /**per day salary working hour**/ $dayHra = $HRA_Amount / $CUR_month; /** per day hra amount **/ $onehoursSalary = ($daySalary + $dayHra) / 8; /**one hour salay ot calculation**/ $totSalayOT = ($totalothour != 0) ? $totalothour * $onehoursSalary : 0; /** if ot not equal zero **/ $currentDaySalary = $daySalary * $values; /** current day salary working days calculation**/ $currentDayHra = $dayHra * $values; /** total working days hra calculations**/ $currentDatePF = $currentDaySalary + $currentDayHra + $totSalayOT; /** current date pf calculation**/ $esiAmount = ($totalsalary <= 20000) ? $currentDatePF * 1.75 / 100 : 0; /** esiamount not elgiable for 20000 **/ $pfAmount = $currentDaySalary * 12 / 100; /** pf amount per day**/ $salaryInCurrentdays = $currentDaySalary + $totSalayOT + $currentDayHra + $Food_Allowances; $salaryInCurrentday = $salaryInCurrentdays - ($esiAmount + $pfAmount); $totalSalarys = $totalSalary + $salaryInCurrentday; $totalSalary = round($totalSalarys); // $salarycurrentdate[] = $salaryInCurrentday;; } } } } $data['totalSalary'] = $totalSalary; $this->loadViews("dashboard", $this->global, $data, NULL); } /*date click on day salary,absent name, total absent display*/ function dateFunctionChangeVales() { $date = $this->request->getPost("id"); $dates = date('Y-m'); $date = $dates . '-01'; // $dat = date('d', strtotime("-1 days")); $WH = 'WH' . date('j', strtotime("-1 days")); $yesterday = $this->dahsboard_Model->attyesterday($WH, $date); $values = 0; foreach ($yesterday as $weekda => $value) { if ($value[$WH] == 0) { $values++; } } $data['values'] = $values; $date = $this->request->getPost("id"); $daydate = format_date($date, 0, 'Y-m'); $daydate = $daydate . '-01'; $WH = 'WH' . format_date($date, 0, 'j'); $yesterday = $this->dahsboard_Model->attyesterday($WH, $daydate); //$absEmp =array($absEmp); $values = 0; $absEmp = array(); foreach ($yesterday as $weekda => $value) { if ($value[$WH] == 0) { $values++; $absendId = $value['EmpID']; $absendName = $value['FirstName']; $absEmp[] = $absendId . "-" . $absendName; //absend empid and name list } } $data['today'] = $values; $data['absname'] = $absEmp; $OT = 'OT' . format_date($date, 0, 'j'); $CUR_month = date('t'); $toDayEmployee = $this->dahsboard_Model->dayAllPersentEmpSalary($WH, $OT, $daydate); //$EmpID = $toDayEmployee[0]->EmpID; $EmpID = 0; $employeeSalary = 0; foreach ($toDayEmployee as $value) { $values = 0; $totalothour = 0; if ($value[$WH] != 0) { $totalothour = $value[$OT]; $values = 1; $Empid = $value['EmpID']; $totalEmployeePersent = $this->dahsboard_Model->persentEmployeeDetails($Empid); if (!empty($totalEmployeePersent)) { $HRA_Amount = $totalEmployeePersent[0]->HRA_Amount; $Basic_Pay = $totalEmployeePersent[0]->Basic_Pay; $totalsalary = $totalEmployeePersent[0]->TotalSalary; $dayFoodAmt = $totalEmployeePersent[0]->Food_Allowances; //$allowances =$totalEmployeePersent[0]->Allowances; //$Allowances = $allowances * $values; $Food_Allowances = $dayFoodAmt * $values; $daySalary = $Basic_Pay / $CUR_month; /**per day salary working hour**/ $dayHra = $HRA_Amount / $CUR_month; /** per day hra amount **/ $onehoursSalary = ($daySalary + $dayHra) / 8; /**one hour salay ot calculation**/ if ($totalothour != 0) /** if ot not equal zero **/ { $totSalayOT = $totalothour * $onehoursSalary; } else { $totSalayOT = 0; } $currentDaySalary = $daySalary * $values; /** current day salary working days calculation**/ $currentDayHra = $dayHra * $values; /** total working days hra calculations**/ $currentDatePF = $currentDaySalary + $currentDayHra + $totSalayOT; /** current date pf calculation**/ $esiAmount = ($totalsalary <= 20000) ? $currentDatePF * 1.75 / 100 : 0; /** esiamount not elgiable for 20000 **/ $pfAmount = $currentDaySalary * 12 / 100; /** pf amount per day**/ $salaryInCurrentdays = $currentDaySalary + $totSalayOT + $currentDayHra + $Food_Allowances; $salaryInCurrentday = $salaryInCurrentdays - ($esiAmount + $pfAmount); $employeeSalary += round($salaryInCurrentday); } } } //$salaryInCurrentday++; $data['employeeSalary'] = $employeeSalary; $working = array(); $overtime = array(); //$holid = array(); $len = format_date($date, 0, 'd'); for ($i = 1; $i <= $len; $i++) //echo $dat; die; { $Working[] = 'WH' . $i; $overtime[] = 'OT' . $i; $CUR_month = date('t'); // foreach ($holiday as $value) // { // //$holid []= 'WH'.$value; // if($i==$value) { // $holid []=$value; // } // } } $WH = implode(",", $Working); $OT = implode(",", $overtime); $salarycurrentdate = array(); $toDayEmployee = $this->dahsboard_Model->dayAllPersentEmpSalary($WH, $OT, $daydate); $totalSalary = 0; $working = explode(",", $WH); $overtime = explode(",", $OT); foreach ($toDayEmployee as $value) { $values = 0; foreach ($working as $work) { //foreach ($overtime as $extra) { if ($value[$work] != 0 || $value['OT' . substr($work, 2)] != 0) { $totalothour = $value['OT' . substr($work, 2)]; $values = 1; $Empid = $value['EmpID']; $totalEmployeePersent = $this->dahsboard_Model->persentEmployeeDetails($Empid); if (!empty($totalEmployeePersent)) { $HRA_Amount = $totalEmployeePersent[0]->HRA_Amount; $Basic_Pay = $totalEmployeePersent[0]->Basic_Pay; $totalsalary = $totalEmployeePersent[0]->TotalSalary; $dayFoodAmt = $totalEmployeePersent[0]->Food_Allowances; //$allowances =$totalEmployeePersent[0]->Allowances; // $Allowances = $allowances * $values; $Food_Allowances = $dayFoodAmt * $values; $daySalary = $Basic_Pay / $CUR_month; /**per day salary working hour**/ $dayHra = $HRA_Amount / $CUR_month; /** per day hra amount **/ $onehoursSalary = ($daySalary + $dayHra) / 8; /**one hour salay ot calculation**/ $totSalayOT = ($totalothour != 0) ? $totalothour * $onehoursSalary : 0; /** if ot not equal zero **/ $currentDaySalary = $daySalary * $values; /** current day salary working days calculation**/ $currentDayHra = $dayHra * $values; /** total working days hra calculations**/ $currentDatePF = $currentDaySalary + $currentDayHra + $totSalayOT; /** current date pf calculation**/ $esiAmount = ($totalsalary <= 20000) ? $currentDatePF * 1.75 / 100 : 0; /** esiamount not elgiable for 20000 **/ $pfAmount = $currentDaySalary * 12 / 100; /** pf amount per day**/ $salaryInCurrentdays = $currentDaySalary + $totSalayOT + $currentDayHra + $Food_Allowances; $salaryInCurrentday = $salaryInCurrentdays - ($esiAmount + $pfAmount); $totalSalarys = $totalSalary + $salaryInCurrentday; $totalSalary = round($totalSalarys); // $salarycurrentdate[] = $salaryInCurrentday; } } } } $data['totalSalary'] = $totalSalary; // } echo json_encode($data); } /*this function uesd to finance startdate */ public function getFinancialStartDate() { $CURMONTH = date('n'); $CURYEAR = date('Y'); $FINYEAR = 0; if ($CURMONTH >= 4) { $FINYEAR = $CURYEAR; } else { $FINYEAR = $CURYEAR - 1; } $dateInString = $FINYEAR . '-4-1'; $result = date_create($dateInString); return $result; } /*this function uesd to finance EndDate */ public function getFinancialEndDate() { $CURMONTH = date('n'); $CURYEAR = date('Y'); $FINYEAR = 0; if ($CURMONTH < 4) { $FINYEAR = $CURYEAR; } else { $FINYEAR = $CURYEAR + 1; } $dateInString = $FINYEAR . '-3-31'; $result = date_create($dateInString); return $result; } /*this function used to speedometer month emp performances display*/ function monthattendance($empID = '') { $date = date('Y-m'); $dates = $date . '-01'; $EmpID = ''; if (empty($empID)) { $EmpID = $this->request->getPost('id'); } else { $EmpID = $empID; } $monthabs = $this->dahsboard_Model->attendance($EmpID, $dates); $persent_month = date('t'); //current month of days 31 $values = array(); $otvalues = array(); $weekdays = array(); $otHours = array(); $date = date('j'); //current month current date $CURDATE = date('d'); //current month current date $CUR_month = date('t'); //current month of days 31 $CURYEAR = date('Y'); $CURMONTH = date('m'); $datejoin = $this->dahsboard_Model->joindate($EmpID); $DateofJoiningInString = $datejoin[0]->DateofJoining; $DateofJoining = date_create($DateofJoiningInString); // $doj_month = date_format($DateofJoining, "n"); // $doj_year = date_format($DateofJoining, "Y"); // $doj_day = date_format($DateofJoining, "j"); $doj_month = format_date($DateofJoining, 0, 'n'); $doj_year = format_date($DateofJoining, 0, 'Y'); $doj_day = format_date($DateofJoining, 0, 'j'); for ($i = 1; $i <= $persent_month; $i++) { $weekdays[] = 'WH' . $i; $otHours[] = 'OT' . $i; } $totalwhhours = 0; foreach ($monthabs as $weekda) { foreach ($weekda as $key => $value) { foreach ($weekdays as $weeks) { if ($weeks == $key) { if ($value != 0) { $values[] = $value; } } } foreach ($otHours as $ot) { if ($ot == $key) { if ($value != 0) { $otvalues[] = $value; } } } } } $totalothour = array_sum($otvalues); //$totalwhhour = sizeof($values); $totalwhhours = array_sum($values); $totalwhhour = $totalwhhours / 8; if ($CURMONTH == $doj_month && $CURYEAR == $doj_year) { $data['CUR_month'] = $CURDATE - $doj_day + 1; } else { $data['CUR_month'] = $date; } if ($totalwhhour != 0) { $year = date('Y'); $current_month = date('m'); $data['values'] = $totalwhhour; //$data['salaryInCurrentday'] = round($salaryInCurrentday); $data['present_percentage'] = round(($totalwhhour / $data['CUR_month']) * 100); } else { $data['values'] = 0; //$data['salaryInCurrentday'] = 0; $data['present_percentage'] = 0; } if (empty($empID)) { echo json_encode($data); } else { return $data; } } /*this function used to speedometer year emp performances display*/ function attendanceyear($empID = '') { $CURMONTH = date('m'); $CURDATE = date('d'); $CURYEAR = date('Y'); $EmpID = ''; if (empty($empID)) { $EmpID = $this->request->getPost('id'); } else { $EmpID = $empID; } $day = array(); $datejoin = $this->dahsboard_Model->joindate($EmpID); $DateofJoiningInString = $datejoin[0]->DateofJoining; $DateofJoining = date_create($DateofJoiningInString); // $doj_month = date_format($DateofJoining, "n"); // $doj_year = date_format($DateofJoining, "Y"); // $doj_day = date_format($DateofJoining, "j"); $doj_month = format_date($DateofJoining, 0, 'n'); $doj_year = format_date($DateofJoining, 0, 'Y'); $doj_day = format_date($DateofJoining, 0, 'j'); $finStart = $this->getFinancialStartDate(); $finEnd = $this->getFinancialEndDate(); $JoinedMonth = date_format($DateofJoining, "n"); if ($DateofJoining >= $finStart && $DateofJoining <= $finEnd) { $JoinedMonthAttendance = $this->dahsboard_Model->getAllAttendances($EmpID, $JoinedMonth); $joinedMonthDaysCount = cal_days_in_month(CAL_GREGORIAN, $doj_month, $doj_year); if ($CURMONTH == $doj_month && $CURYEAR == $doj_year) { $joinedMonthWorkingDayCount = $CURDATE - $doj_day + 1; } else { $joinedMonthWorkingDayCount = $joinedMonthDaysCount - $doj_day + 1; } $joinedMonthDays = 0; for ($j = $doj_day; $j <= $joinedMonthDaysCount; $j++) { $weekdays[] = 'WH' . $j; } foreach ($JoinedMonthAttendance as $day) { foreach ($day as $key => $value) { foreach ($weekdays as $weeks) { if ($weeks == $key) { if ($value != 0) { // echo $value; $joinedMonthDays++; } } } } } $result = $this->dahsboard_Model->attendanceyear($EmpID, $JoinedMonth + 1); $yearabs = $this->dahsboard_Model->getAllAttendance($EmpID, $CURMONTH); $TotalNoofDays = $result[0]->TotalWorkingDays; $DaysWorked = $result[0]->DaysWorked; $values = 0; $values = array(); $weekdays = array(); $date = date('d'); $Work = array_sum($weekdays); for ($j = 1; $j <= $date; $j++) { $weekdays[] = 'WH' . $j; } $totalhours = 0; foreach ($yearabs as $day) { foreach ($day as $key => $value) { foreach ($weekdays as $weeks) { if ($weeks == $key) { if ($value != 0) { //$values++; //$totalhours = array_sum($value); $values[] = $value; } } } } } $DaysWorked = 0; $totalhours = array_sum($values); $values = $totalhours / 8; if ($CURMONTH == $doj_month && $CURYEAR == $doj_year) { $TotalNoofDays = $TotalNoofDays + $joinedMonthWorkingDayCount; $DaysWorked = $joinedMonthDays; } else { $TotalNoofDays = $TotalNoofDays + $CURDATE + $joinedMonthWorkingDayCount; $DaysWorked = $DaysWorked + $joinedMonthDays + $values; } $final_res = round(($DaysWorked / $TotalNoofDays) * 100); $data['workeds'] = $DaysWorked; $data['yeardata'] = $final_res; $data['totaldays'] = $TotalNoofDays; } else { $result = $this->dahsboard_Model->attendanceyear($EmpID, 4); $yearabs = $this->dahsboard_Model->getAllAttendance($EmpID, $CURMONTH); $TotalNoofDays = $result[0]->TotalWorkingDays; $DaysWorked = $result[0]->DaysWorked; $values = 0; $values = array(); $weekdays = array(); $date = date('d'); $Work = array_sum($weekdays); for ($j = 1; $j <= $date; $j++) { $weekdays[] = 'WH' . $j; } foreach ($yearabs as $day) { foreach ($day as $key => $value) { foreach ($weekdays as $weeks) { if ($weeks == $key) { if ($value != 0) { $values[] = $value; } } } } } $totalhours = array_sum($values); $values = $totalhours / 8; $TotalNoofDays = $TotalNoofDays + $CURDATE; $DaysWorked = $DaysWorked + $values; $final_res = round(($DaysWorked / $TotalNoofDays) * 100); $data['workeds'] = $DaysWorked; $data['yeardata'] = $final_res; $data['totaldays'] = $TotalNoofDays; } if (empty($empID)) { echo json_encode($data); } else { return $data; } } /****************HR DASHBOART Controller END **************************************/ /** * This function is used to load the user list */ function userListing() { $isDeleted = 0 ; // default showing active data $showArchive = 0 ; // if ($this->request->getMethod() === 'POST') { $showArchive = $this->request->getPost('showArchive'); //reversing condition that when user wants deleted data to be shown then we are making active filter 0 if($showArchive){ $isDeleted = 1; } } $data['showArchive'] = $showArchive; // dd($data); $data['userRecords'] = $this->user_model->userListing($isDeleted); $this->global['pageTitle'] = 'User Listing'; // dd($data); $this->loadViews("userListing", $this->global, $data, NULL); //} } /** * This function is used to load the add new form */ function addNew() { // if($this->isAdmin() == TRUE) // { // $this->loadThis(); // } // else // { $data['EmpList'] = $this->user_model->rolesNotAllotedEmployees(); $data['roles'] = $this->user_model->getUserRoles(); $data['Department'] = json_decode(json_encode($this->department_model->departmentListing(1)), true); // echo "
";
        // print_r($data['Department']);
        // die;

        // echo "
";
        // print_r($data['Department']);die;
        $this->global['pageTitle'] = 'Add New User';
        $this->loadViews("addUser", $this->global, $data, NULL);
        // }
    }

    /**
     * This function is used to check whether email already exist or not
     */
    function checkEmailExists()
    {
        $userId = $this->request->getPost("userId");
        $email = $this->request->getPost("email");

        if (empty($userId)) {
            $result = $this->user_model->checkEmailExists($email);
        } else {
            $result = $this->user_model->checkEmailExists($email, $userId);
        }

        if (empty($result)) {
            echo ("true");
        } else {
            echo ("false");
        }
    }
    /* Validation for Employee  Dropdown
	*/
    function  Employee_validate($selectValue)
    {
        //echo 'select_validate  method called';
        // 'none' is the first option and the text says something like "-Choose one-"
        if ($selectValue == '0') {
            // $this->validator->setMessage('Employee_validate', 'Please Select Employee.');
            return false;
        } else // user picked something
        {
            return true;
        }
    }
    /* Validation for Employee  Dropdown
	*/
    function  Role_validate($selectValue)
    {
        //echo 'select_validate  method called';
        // 'none' is the first option and the text says something like "-Choose one-"
        if ($selectValue == '0') {
            // $this->validator->setMessage('Role_validate', 'Please Select Role.');
            return false;
        } else // user picked something
        {
            return true;
        }
    }
    /**
     * This function is used to add new user to the system
     */
    public function addNewUser()
    {
        // $validationRules = [
        //     'EmpList' => 'trim|callback_Employee_validate',
        //     'password' => 'required|max_length[20]',
        //     'cpassword' => 'trim|required|matches[password]|max_length[20]'
        // ];

        // $validationMessages = [
        //     'EmpList' => [
        //         'Employee_validateS' => 'Please select an employee.'
        //     ]
        // ];

        // $this->validate($validationRules, $validationMessages);

        // Validation passed
        $EmpID = $this->request->getPost('EmpList');
        $roleId = !empty($this->request->getPost('role')) ? $this->request->getPost('role') : '2' ;
        $password = (string)$this->request->getPost('password');
        $Createddt = date('Y-m-d H:i:s');
        $email = $this->request->getPost('MailID');
        $SelectedDepartment = (string)$this->request->getPost('txtSelectedDepartment');
        $comma_separated = explode(':', $SelectedDepartment);
        if (count($comma_separated) == 1 && in_array('DEP27', $comma_separated)) {
            $roleId = '6';
        }
        $userInfo = [
            'email' => $email,
            'EmpID' => $EmpID,
            'password' => password_hash($password, PASSWORD_DEFAULT), // Use password_hash() for hashing passwords
            'roleId' => $roleId,
            'createdBy' => $this->vendorId,
            'createdDtm' => $Createddt
        ];

        $result = $this->user_model->addNewUser($userInfo);

        if ($SelectedDepartment != '') {
            foreach ($comma_separated as $DeptCode) {
                $userdept = [
                    'EmpID' => $EmpID,
                    'Departmentcode' => $DeptCode
                ];
                $access = $this->user_model->addAccess($userdept);
            }
        }

        if ($result > 0) {
            // return redirect()->to('userListing')->with('success', 'New user created successfully!');
            $this->session->setFlashdata('success', 'New user created successfully!');
        } else {
            // return redirect()->to('userListing')->with('error', 'Failed to create user.');
            $this->session->setFlashdata('error', 'Failed to create user.');
        }
        return redirect()->route('userListing');
    }

    function Adduserdepartment()
    {
        $empid = $this->request->getPost('Eid');
        $Depcode = $this->request->getPost('Department');
        $userdept = array('EmpID' => $empid, 'Departmentcode' => $Depcode);

        $access = $this->user_model->addAccess($userdept);
        if ($access > 0) {
            echo "Successfully Added";
        };
    }


    function Deleteuserdepartment()
    {
        $empid = $this->request->getPost('Eid');
        $Depcode = $this->request->getPost('Department');
        $userdept = array('EmpID' => $empid, 'Departmentcode' => $Depcode);

        $access = $this->user_model->DeleteAccess($empid, $Depcode);

        if ($access > 0) {
            echo "Successfully Deleted";
        }
    }


    /**
     * This function is used load user edit information
     * @param number $userId : Optional : This is user id
     */
    function editOld($UserId = '')
    {
        // if($this->isAdmin() == TRUE )
        // {
        //     $this->loadThis();
        // }
        // else
        // {
        if ($UserId == '') {
            // redirect('userListing');
        }

        $Uid =  $_GET['UID'];
        $Empid = $_GET['EMPID'];

        $data['roles'] = $this->user_model->getUserRoles();

        $data['EmpList'] = $this->user_model->GetEmployeeDetails($Uid);
        $data['Departmentlist'] = $this->costcenter_model->getDepartmentnotadded($Empid);
        $data['EmpRole'] =   $this->user_model->GetRoleNameByUserID($Uid);
        $data['AccessDept'] = $this->costcenter_model->getaccessDept($Empid);

        // $data['userInfo'] = $this->user_model->getUserInfo($Uid);
        $data['userId'] = $Uid;

        $this->global['pageTitle'] = 'Edit User';
        $this->loadViews("editOld", $this->global, $data, NULL);
        //}
    }


    /**
     * This function is used to edit the user information
     */
    function editUser()
    {
        // if($this->isAdmin() == TRUE)
        // {
        //     $this->loadThis();
        // }
        // else
        // {
        // $userId =   $this->request->getPost('EmpList');
        // $this->validator->setRules([ 'EmpList'=> 'trim|callback_Employee_validate',
        // 'role'=> 'trim|callback_Role_validate',
        // 'password'=> 'required|max_length[20]',
        // 'cpassword'=> 'trim|required|matches[password]|max_length[20]']);

        // if ($this->validator->run() == FALSE) {
        //     $this->editOld($userId);
        // } else {
        $EmpID = $this->request->getPost('EmpList');
        $role = $this->request->getPost('role');
        // $password = $this->request->getPost('password');

        $updatedDate =  get_current_date_time();

        //    echo $EmpID;

        $userInfo = array();

        // $userInfo = array('password' => getHashedPassword($password), 'roleId' => $role, 'EmpId' => $EmpID, 'updatedDtm' => $updatedDate);
        $userInfo = array('roleId' => $role, 'EmpId' => $EmpID, 'updatedDtm' => $updatedDate , 'email'=> $this->request->getPost('MailID'));

        $result = $this->user_model->editUser($userInfo,  $EmpID);

        if ($result == true) {
            $this->session->setFlashdata('success', 'User updated successfully');
        } else {
            $this->session->setFlashdata('error', 'User updation failed');
        }

        return redirect()->route('userListing');
        // }
        //}
    }


    /**
     * This function is used to delete the user using userId
     * @return boolean $result : TRUE / FALSE
     */
    function deleteUser()
    {
 
        $Uid = $this->request->getGet('UID');

        $updatedDate =  get_current_date_time();

        $updateInfo = array('isDeleted' => 1, 'updatedBy' => $this->vendorId, 'updatedDtm' => $updatedDate);
        
        $result = $this->user_model->userActivation($Uid, $updateInfo);

         return redirect()->route('userListing');
    }

    function reActivateUser()
    {

        $Uid = $this->request->getGet('UID');

        $updatedDate =  get_current_date_time();

        $updateInfo = array('isDeleted' => 0, 'updatedBy' => $this->vendorId, 'updatedDtm' => $updatedDate);


        $result = $this->user_model->userActivation($Uid, $updateInfo);


         return redirect()->route('userListing');
    }

    
    function userChangePassword()
    {
        helper('form'); 
        $userId = $this->request->getPost('userId');
        $newPassword = $this->request->getPost('password');
        $cNewPassword = $this->request->getPost('cpassword');

        if ($newPassword == $cNewPassword) {
                $usersData = array(
                    'password' => getHashedPassword($newPassword),
                    'updatedBy' => $userId,
                    'updatedDtm' => date('Y-m-d H:i:sa')
                );
                $result = $this->user_model->changePassword($userId, $usersData);
                if ($result > 0) {
                    $this->session->setFlashdata('success', 'Password updation successful');
                } else {
                    $this->session->setFlashdata('error', 'Password updation failed');
                }

                return redirect()->route('userListing');
        } else {
            $this->session->setFlashdata('error', 'New Password and Confirm Password Not Same');
            return redirect()->route('userListing');
        }
    }

    /**
     * This function is used to load the change password screen
     */
    function loadChangePass()
    {
        $this->global['pageTitle'] = 'Change Password';

        $this->loadViews("changePassword", $this->global, [], NULL);
    }


    /**
     * This function is used to change the password of the user
     */
    function changePassword()
    {
        helper('form'); //$this->load->library('form_validation');

        // $this->validator->setRules(['oldPassword', 'Old password'=> 'required|max_length[20]']);
        // $this->validator->setRules(['newPassword', 'New password'=> 'required|max_length[20]']);
        // $this->validator->setRules(['cNewPassword', 'Confirm new password'=> 'required|matches[newPassword]|max_length[20]']);

        // if ($this->validator->run() == FALSE) {
        $oldPassword = $this->request->getPost('oldPassword');
        $newPassword = $this->request->getPost('newPassword');
        $cNewPassword = $this->request->getPost('cNewPassword');

        if ($newPassword == $cNewPassword) {
            $resultPas = $this->user_model->matchOldPassword($this->vendorId, $oldPassword);
            if (empty($resultPas)) {
                $this->session->setFlashdata('nomatch', 'Your old password not correct');
                return redirect()->route('loadChangePass');
            } else {
                $usersData = array(
                    'password' => getHashedPassword($newPassword),
                    'updatedBy' => $this->vendorId,
                    'updatedDtm' => date('Y-m-d H:i:sa')
                );
                $result = $this->user_model->changePassword($this->vendorId, $usersData);
                if ($result > 0) {
                    $this->session->setFlashdata('success', 'Password updation successful');
                } else {
                    $this->session->setFlashdata('error', 'Password updation failed');
                }

                return redirect()->route('loadChangePass');
            }
        } else {
            $this->session->setFlashdata('error', 'New Password and Confirm Password Not Same');
            return redirect()->route('loadChangePass');
        }
    }

    //this function used to delivery performances
    function deliver_perform()
    {

        $this->global['pageTitle'] = 'Delivery Performance';
        if ($this->request->getPost('btn_submit')) {

            $ab = (string)$this->request->getPost('financialyear');

            $fa = substr($ab, 0, -5);
            $aa = substr($ab, 5, 5);
            $m = $this->request->getPost('month');

            $data['fy'] = $this->user_model->fincalYear();
            $data['per'] = $this->user_model->deliver_perform($fa, $aa, $m);
        }

        $data['fy'] = $this->user_model->fincalYear();

        $this->loadviews("deliver_perform", $this->global, $data, NULL);
    }

    /*
        *favourite add function and load view
        */

    function favourite()
    {
        $this->global['pageTitle'] = 'Add Favourite';


        // $data['ponoreset']=$this->purchaseorder_model->ponoresetfinyear();


        $this->loadViews("Favourite", $this->global, Null);
    }
    function favouriteadd()
    {
        $name = $this->request->getPost('name');
        $url = $this->request->getPost('url');
        $status = $this->request->getPost('status');
        $CreateBy = $this->session->get('userId');


        $createddt =  get_current_date_time();
        $menu = $this->request->getPost('menu');
        // $RowCount =  $this->request->getPost('txtRowCount'); 
        // $DeletedRow =  $this->request->getPost('txtDeletedRow');
        // $comma_separated = explode(':', $DeletedRow); 
        $favourite = array('Menu_Name' => $name, 'Menu_URL' => $url, 'Status' => $status, 'Created_BY' => $CreateBy, 'Created_ON' => $createddt, 'Menu_ID' => $menu);
        $getdata = $this->user_model->favouriteadd($favourite);

        if ($getdata == 1) {
            echo "success";
        } else {
            echo "failed";
        }
    }



    function zohobooks_api_fetch_all()
    {
       
        try {
           
            helper('zohobook');
            $Zohobook_model = model('Zohobook_api_model');
            if (isset($_GET['from']) && $_GET['from'] != null && isset($_GET['to']) && $_GET['to'] != null) {
                $date_today = $_GET['to'];
                $date_yesterday = $_GET['from'];
            } else {
                $date_today = date('Y-m-d');
                $date_yesterday = date('Y-m-d', strtotime('-3 day', strtotime($date_today)));
            }
           
            $chk_acc_token_val = $Zohobook_model->get_data('zohobook_accesstoken', 'id', 1);
           
            $date = new \DateTime($chk_acc_token_val[0]['created_at']);
           
            $date->add(new \DateInterval('PT1H'));
            
            $token = 0;
            if ($date->format('Y-m-d H:i:s') > date('Y-m-d H:i:s')) {
                $token = $chk_acc_token_val[0]['token'];
            } else {
                $token = generateNewToken();
                $tokendata['token'] = $token;
                $Zohobook_model->customUpdate($tokendata, 1, 'zohobook_accesstoken');
            }
            // $token = generateNewToken(); $tokendata['token'] = $token; 
            //$Zohobook_model->update($tokendata , 1,'zohobook_accesstoken');  
            $result = getheringInvoiceDetails($date_today, $date_yesterday, $token);
            
            $headers_new = $result['headers_new'];
            $res = json_decode($result['data'], true);
            $inv_array = $res['invoices'];


            $tokenWithCreditNoteScope = generateNewTokenForCreditNoteScope();
            $cteditNotesRes = getAllCreditNotes($date_today, $date_yesterday, $tokenWithCreditNoteScope);
           
            $cteditNotesData = json_decode($cteditNotesRes['data'],true);
            
            if(count($cteditNotesData['creditnotes']))
            {
                $this->saveOrUpdateCreditNote($cteditNotesData['creditnotes'] , $tokenWithCreditNoteScope);
            }
            // dd($cteditNotesData);
           
           
            foreach ($inv_array as $inv) {
                $invoice_id = $inv['invoice_id'];
                //filter only einvoice status pushed invoices only
                //&& isset($inv['einvoice_details']) && isset($inv['einvoice_details']['status']) && ($inv['einvoice_details']['status'] == 'pushed')
                if ($invoice_id !== "") {
                    $organization_id = '776847408';
                    $result2 = getheringInvoiceSubDetails($invoice_id, $organization_id, $headers_new);
                    $resall = json_decode($result2, true);
                    $res2[] = $resall['invoice'];
                }
            }
            $insert_count = 0;
            $update_count = 0;
            // dd($res2);

            foreach ($res2 as $rs) {
               
                $gst_no = $rs['gst_no'];
                $customer_id = $rs['customer_id'];
                $customer_name = $rs['customer_name'];
                $invoice_number = $rs['invoice_number'];
                $invoice_date = $rs['date'];
                $status = $rs['status'];
                $due_date = $rs['due_date'];
                $invoice_url = $rs['invoice_url'];
                $einvoice_number = $rs['einvoice_details']['inv_ref_num'];

                $invoice_time = $rs['created_time'];
                $time_array = explode("T", $invoice_time);
                $time_array = explode("+", $time_array[1]);
                $invoice_time = $time_array[0];

                $sql_invoice_chk = $Zohobook_model->ip_invoices($invoice_number, $invoice_date);
                // dd($sql_invoice_chk);
                if ($sql_invoice_chk <= 0) {

                    //this check only for ASHOK LEYLAND LIMITED
                    if($customer_id == '3215000000000082604' || $customer_id == '3215000000000082724')
                    {
                        //this combination of customer_id & gst_no search only for client ASHOK LEYLAND
                        $gst_sql = $Zohobook_model->ip_client_ashok_leyland($gst_no,$customer_id);
                        if ($gst_sql) {
                            $client_id = $gst_sql[0]['client_id'];
                            log_message('error', 'Data fetch success DB : ip_clients , client_id : ' . $client_id);
                        }

                    }else{

                        $gst_sql = $Zohobook_model->ip_clients($gst_no);
                        if ($gst_sql) {
                            $client_id = $gst_sql[0]['client_id'];
                            log_message('error', 'Data fetch success DB : ip_clients , client_id : ' . $client_id);
                        } else {
                            log_message('error', 'No data => Data fetch failed DB : ip_clients ' . $gst_no);
                            $client_data['client_tax_code'] = $gst_no;
                            $client_data['customer_id'] = $customer_id;
                            $client_data['customer_name'] = $customer_name;
                            $gst_inserted_id = $Zohobook_model->customInsert($client_data, 'ip_clients');
                            $client_id = $gst_inserted_id;
                            log_message('error', 'New Data Created : DB : ip_clients , client_id : ' . $client_id);
                        }

                    }
                    



                   


                    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                    $charactersLength = strlen($characters);
                    $randomString = '';
                    for ($i = 0; $i < 16; $i++) {
                        $randomString .= $characters[rand(0, $charactersLength - 1)];
                    }
                    $url_key = $randomString;

                    $ip_invoices['user_id'] = 1;
                    $ip_invoices['client_id'] = $client_id;
                    $ip_invoices['invoice_group_id'] = 6;
                    $ip_invoices['invoice_status_id'] = ($status == 'draft' ? 1 : (($status == 'sent' || $status == 'overdue') ? 2 : 5));
                    $ip_invoices['invoice_date_created'] = $invoice_date;
                    $ip_invoices['invoice_time_created'] = $invoice_time;
                    $ip_invoices['invoice_date_due'] = $due_date;
                    $ip_invoices['invoice_number'] = $invoice_number;
                    $ip_invoices['invoice_url_key'] = $url_key;
                    $ip_invoices['receivedstatus'] = 'ST066';
                    $ip_invoices['credit_status'] = 0;
                    $ip_invoices['status'] = $status;
                    $ip_invoices['e_invoice_number'] = $einvoice_number;
                    $ip_invoices['invoice_url'] = $invoice_url;
                    $invoice_insert_id = $Zohobook_model->customInsert($ip_invoices, 'ip_invoices');
                    if ($invoice_insert_id) {
                        log_message('error', 'Data insert success DB : ip_invoices client id :' . $client_id);
                        $insert_count = $insert_count + 1;
                        //start invoice level custom fields

                        //custom fields insert

                        $batch_no = isset($rs['custom_fields'][5]['value']) ? $rs['custom_fields'][5]['value'] : "";
                        // $batch_no = "";
                        $vehicle_number = isset($rs['custom_field_hash']['cf_vehicle_number']) ? $rs['custom_field_hash']['cf_vehicle_number'] : '';
                        $transport_mode = isset($rs['custom_field_hash']['cf_transport_mode']) ? $rs['custom_field_hash']['cf_transport_mode'] : '';
                        $purchase_order_date = isset($rs['custom_field_hash']['cf_purchase_order_date']) ? $rs['custom_field_hash']['cf_purchase_order_date'] : '';
                        $driver = isset($rs['custom_field_hash']['cf_driver']) ? $rs['custom_field_hash']['cf_driver'] : '';
                        $place_of_supply = isset($rs['custom_field_hash']['cf_place_of_supply']) ? $rs['custom_field_hash']['cf_place_of_supply'] : '';
                        // batch_no
                        $ip_invoice_custom_b['invoice_id'] = $invoice_insert_id;
                        $ip_invoice_custom_b['invoice_custom_fieldid'] = 62;
                        $ip_invoice_custom_b['invoice_custom_fieldvalue'] = $batch_no;
                        $result_invoice_custom_insert = $Zohobook_model->customInsert($ip_invoice_custom_b, 'ip_invoice_custom');
                        if ($result_invoice_custom_insert)
                            log_message('error', 'Data insert success DB : ip_invoice_custom ');
                        else
                            log_message('error', 'Data insert failed DB : ip_invoice_custom ');
                        // vehicle_number
                        $ip_invoice_custom_v['invoice_id'] = $invoice_insert_id;
                        $ip_invoice_custom_v['invoice_custom_fieldid'] = 8;
                        $ip_invoice_custom_v['invoice_custom_fieldvalue'] = $vehicle_number;
                        $res_vehicle = $Zohobook_model->customInsert($ip_invoice_custom_v, 'ip_invoice_custom');
                        if ($res_vehicle)
                            log_message('error', 'Data insert success DB : ip_invoice_custom ');
                        else
                            log_message('error', 'Data insert failed DB : ip_invoice_custom ');
                        // transport_mode
                        $ip_invoice_custom_t['invoice_id'] = $invoice_insert_id;
                        $ip_invoice_custom_t['invoice_custom_fieldid'] = 7;
                        $ip_invoice_custom_t['invoice_custom_fieldvalue'] = $transport_mode;
                        $res_transport_mode = $Zohobook_model->customInsert($ip_invoice_custom_t, 'ip_invoice_custom');
                        if ($res_transport_mode)
                            log_message('error', 'Data insert success DB : ip_invoice_custom ');
                        else
                            log_message('error', 'Data insert failed DB : ip_invoice_custom ');
                        // purchase_order_date
                        $ip_invoice_custom_p['invoice_id'] = $invoice_insert_id;
                        $ip_invoice_custom_p['invoice_custom_fieldid'] = 15;
                        $ip_invoice_custom_p['invoice_custom_fieldvalue'] = $purchase_order_date;
                        $res_purchase_order_date = $Zohobook_model->customInsert($ip_invoice_custom_p, 'ip_invoice_custom');
                        if ($res_purchase_order_date)
                            log_message('error', 'Data insert success DB : ip_invoice_custom ');
                        else
                            log_message('error', 'Data insert failed DB : ip_invoice_custom ');
                        // driver
                        $ip_invoice_custom_d['invoice_id'] = $invoice_insert_id;
                        $ip_invoice_custom_d['invoice_custom_fieldid'] = 58;
                        $ip_invoice_custom_d['invoice_custom_fieldvalue'] = $driver;
                        $res_driver = $Zohobook_model->customInsert($ip_invoice_custom_d, 'ip_invoice_custom');
                        if ($res_driver)
                            log_message('error', 'Data insert success DB : ip_invoice_custom ');
                        else
                            log_message('error', 'Data insert failed DB : ip_invoice_custom ');
                        // place_of_supply
                        $ip_invoice_custom_d['invoice_id'] = $invoice_insert_id;
                        $ip_invoice_custom_d['invoice_custom_fieldid'] = 10;
                        $ip_invoice_custom_d['invoice_custom_fieldvalue'] = $place_of_supply;
                        $res_place = $Zohobook_model->customInsert($ip_invoice_custom_d, 'ip_invoice_custom');
                        if ($res_place)
                            log_message('error', 'Data insert success DB : ip_invoice_custom ');
                        else
                            log_message('error', 'Data insert failed DB : ip_invoice_custom ');
                        //end  invoice level custom fields

                        //if line items available
                        if (isset($rs['line_items']) && count($rs['line_items']) > 0) {
                            log_message('error', 'Processing line items' . count($rs['line_items']));

                            // dd($rs);
                            for ($i = 0; $i < count($rs['line_items']); $i++) {            //start insert line items
                                $sku = $rs['line_items'][$i]['sku'];


                                $item_price = $rs['line_items'][$i]['rate'];
                                $hsn_or_sac = $rs['line_items'][$i]['hsn_or_sac'];
                                $item_order =  $rs['line_items'][$i]['item_order'];
                                $item_product_unit = $rs['line_items'][$i]['unit'];
                                $item_name = $rs['line_items'][$i]['name'];
                                $item_description = $rs['line_items'][$i]['description'];
                                $item_quantity = $rs['line_items'][$i]['quantity'];
                                $cgst = $rs['line_items'][$i]['line_item_taxes'][1]['tax_name'];
                                $sgst = $rs['line_items'][$i]['line_item_taxes'][0]['tax_name'];
                                $cgst = $cgst[4];
                                $sgst = $sgst[4];
                                $cgst = $cgst . '.000';
                                $getcgsttax = $Zohobook_model->ip_tax_rates($cgst);
                                if ($getcgsttax) {
                                    $cgsttaxid = $getcgsttax[0]['tax_rate_id'];
                                    log_message('error', 'Data fetch success DB : ip_tax_rates cgst' . $cgst);
                                } else {
                                    log_message('error', 'No data => Data fetch failed DB : ip_tax_rates ' . $cgst);
                                    $cgst_data['tax_rate_percent'] = $cgst;
                                    $getcgsttax = $Zohobook_model->customInsert($cgst_data, 'ip_tax_rates');
                                    $cgsttaxid = $getcgsttax;
                                    log_message('error', 'New Data Created : DB : ip_tax_rates , tax_rate_id : ' . $cgsttaxid);
                                }

                                $sgst = $sgst . '.000';
                                $getsgsttax = $Zohobook_model->ip_tax_rates($sgst);
                                if ($getsgsttax) {
                                    $sgsttaxid = $getsgsttax[0]['tax_rate_id'];
                                    log_message('error', 'Data fetch success DB : ip_tax_rates sgst' . $sgst);
                                } else {
                                    log_message('error', 'No data => Data fetch failed DB : ip_tax_rates ' . $sgst);
                                    $sgst_data['tax_rate_percent'] = $sgst;
                                    $getsgsttax = $Zohobook_model->customInsert($sgst_data, 'ip_tax_rates');
                                    $sgsttaxid = $getsgsttax;
                                    log_message('error', 'New Data Created : DB : ip_tax_rates , tax_rate_id : ' . $sgsttaxid);
                                }

                                $item_subtotal = $rs['line_items'][$i]['item_total'];


                                $item_sgst_amt = $rs['line_items'][$i]['line_item_taxes'][0]['tax_amount'];
                                $item_cgst_amt = $rs['line_items'][$i]['line_item_taxes'][1]['tax_amount'];
                                $item_tax_total = ($item_sgst_amt + $item_cgst_amt);
                                $item_total = ($item_subtotal + $item_tax_total);

                                $item_discount = 0.00;
                                $item_igst_amt = 0.00;
                                // if($batch_no==""){ $batch_no = "";}


                                $sku_sql = $Zohobook_model->ip_products($sku);
                                if (!empty($sku_sql)) {
                                    $product_id = $sku_sql[0]['product_id'];
                                    log_message('error', 'Data fetch success DB : ip_products , product_id : ' . $product_id);
                                } else {
                                    log_message('error', 'No data => Data fetch failed DB : ip_products ' . $sku);
                                    $sku_data['product_name'] = $item_name;
                                    $sku_data['product_description'] = $item_description;
                                    $sku_data['sku'] = $sku;
                                    $sku_inserted_id = $Zohobook_model->customInsert($sku_data, 'ip_products');
                                    $product_id = $sku_inserted_id;
                                    log_message('error', '$sku_sql => Data fetch failed DB : ip_products ' . $sku_sql);

                                    log_message('error', 'sku' . $sku);
                                    log_message('error', 'New Data Created : DB : product_id , product_id : ' . $product_id);
                                }

                                //#1

                                $ip_invoice_items['invoice_id'] = $invoice_insert_id;
                                $ip_invoice_items['item_product_id'] = $product_id;
                                $ip_invoice_items['item_date_added'] = $invoice_date;
                                $ip_invoice_items['item_name'] = $item_name;
                                $ip_invoice_items['item_description'] = $item_description;
                                $ip_invoice_items['item_quantity'] = $item_quantity;
                                $ip_invoice_items['item_price'] = $item_price;
                                $ip_invoice_items['item_order'] = $item_order;
                                $ip_invoice_items['item_product_unit'] = $item_product_unit;
                                $ip_invoice_items['Sgst_item_tax_rate_id'] = $sgsttaxid;
                                $ip_invoice_items['Cgst_item_tax_rate_id'] = $cgsttaxid;
                                $ip_invoice_items['hsn_or_sac'] = $hsn_or_sac;
                                
                                $item_insert_id = $Zohobook_model->customInsert($ip_invoice_items, 'ip_invoice_items');
                                if ($item_insert_id)
                                    log_message('error', 'Data insert success DB : ip_invoice_items => Sgst_item_tax_rate_id :' . $sgsttaxid);
                                else
                                    log_message('error', 'Data insert failed DB : ip_invoice_items => Sgst_item_tax_rate_id :' . $sgsttaxid);

                                //tax amount --  ip_invoice_item_amounts - table
                                $ip_invoice_item_amounts['item_id'] = $item_insert_id;
                                $ip_invoice_item_amounts['item_subtotal'] = $item_subtotal;
                                $ip_invoice_item_amounts['item_tax_total'] = $item_tax_total;
                                $ip_invoice_item_amounts['item_total'] = $item_total;
                                $ip_invoice_item_amounts['item_sgst_amt'] = $item_sgst_amt;
                                $ip_invoice_item_amounts['item_cgst_amt'] = $item_cgst_amt;
                                $ip_invoice_item_amounts['item_discount'] = $item_discount;
                                $ip_invoice_item_amounts['item_igst_amt'] = $item_igst_amt;
                                $result_tax_amount_insert = $Zohobook_model->customInsert($ip_invoice_item_amounts, 'ip_invoice_item_amounts');
                                if ($result_tax_amount_insert)
                                    log_message('error', 'Data insert success DB : ip_invoice_item_amounts ');
                                else
                                    log_message('error', 'Data insert failed DB : ip_invoice_item_amounts ');
                            }         //end line items insert    

                        } else {
                            log_message('error', 'Line Items not found in API result');
                        }
                    } else {
                        log_message('error', 'Data insert failed DB : ip_invoice_items client id :' . $client_id);
                    }
                } else // update invoice status, especially for cancelled invoices
                {
                    // if($status == "void" || $status == "sent" ||  $status == "overdue")
                    // {
                    $sql_invoice_update = array();
                    $sql_invoice_update['invoice_status_id'] = (($status == "sent" || $status == "overdue") ? 2 : 5);
                    // echo 'script' . $invoice_number. $status;
                    // print_r( $sql_invoice_update);
                    // echo '
'; $sql_invoice_update = $Zohobook_model->sql_invoice_update($sql_invoice_update, $invoice_number, $invoice_date, 'ip_invoices'); if ($sql_invoice_update) { log_message('error', 'Data update success DB : ip_invoices '); } else { log_message('error', 'Data update failed DB : ip_invoices '); } $update_count = $update_count + 1; // } } // echo 'new invoice inserted count- ' . $insert_count . '/' . 'status updated count - ' . $update_count; } $response = [ 'status' => true, 'message' => "Successfully data inserted. Total inserted: " . $insert_count . ", Total Updated: " . $update_count ]; return json_encode($response); // curl_close($ch); // } } catch (\Exception $e) { $data['err'] = $e->getMessage(); // $db = \Config\Database::connect(); // $data['last_query'] = $db->getLastQuery();; $Zohobook_model->customInsert($data, 'zohobook_api_err'); log_message('error', "Data insertion failed : " . $e->getMessage()); return json_encode("Data insertion failed : " . $e->getMessage()); } } // END zoho API public function saveOrUpdateCreditNote($data , $tokenWithCreditNoteScope ) { foreach ($data as $key => $value) { $existingCreditNote = $this->CreditNoteModel->where('creditnote_id', $value['creditnote_id'])->first(); if ($existingCreditNote) { // Update existing record $this->CreditNoteModel->update($value['creditnote_id'], $value); } else { // Insert new record $this->CreditNoteModel->insert($value); } //credit note line item api call $cteditNotesLineItemsRes = getCreditNotesItemDetails($value['creditnote_id'], $tokenWithCreditNoteScope); $lineItemData = json_decode($cteditNotesLineItemsRes['data'],true); if(count($lineItemData['creditnote']['line_items'])) { foreach ($lineItemData['creditnote']['line_items'] as $itemkey => $itemvalue) { $itemvalue['creditnote_id'] = $value['creditnote_id']; $existingCreditNoteItems = $this->CreditNotesItemsModel->where('line_item_id', $itemvalue['line_item_id'])->first(); if ($existingCreditNoteItems) { // Update existing record $this->CreditNotesItemsModel->update($itemvalue['line_item_id'], $itemvalue); } else { // Insert new record $this->CreditNotesItemsModel->insert($itemvalue); } } } } } function fetchEmployeeDetails() { $EmpID = $this->request->getPost('EmpID'); if (!$EmpID) { return $this->response->setJSON(['success' => false, 'message' => 'Employee ID not provided']); } $userInfo = $this->user_model->findEmp($EmpID); if ($userInfo) { return $this->response->setJSON(['success' => true, 'userInfo' => $userInfo]); } else { return $this->response->setJSON(['success' => false, 'message' => 'Employee not found']); } } }