inwardgateregister_model = new Inwardgateregister_model(); $this->IGRRemarks_model = new IGRRemarks_model(); $this->gasShortage_model = new GasShortageModel(); $this->rawMaterialDetails_model = new Rawmaterialdetails_model(); $this->session = session(); helper('form'); //$this->load->library('form_validation'); $this->logger = service('logger'); // Load the logger service $this->isLoggedIn(); } /** * This function used to load the first screen of the user */ public function index() { $this->global['pageTitle'] = 'Inward Gate Register'; $this->loadViews("viewinwardgateregister", $this->global, NULL, NULL); } function viewIGR() { if ($this->request->getMethod() === 'GET') { $toDate = date('Y-m-d'); $fromDate = date('Y-m-d', strtotime('-90 days', strtotime($toDate))); } elseif ($this->request->getMethod() === 'POST') { $fromDate = $this->request->getPost('fromDate'); $toDate = $this->request->getPost('toDate'); $fromDate = date('Y-m-d', strtotime($fromDate)); $toDate = date('Y-m-d', strtotime($toDate)); } $this->global['pageTitle'] = 'View Inward Gate Register'; $result = $this->inwardgateregister_model->ViewigrListing($fromDate, $toDate); $igrList = $result[0]; foreach ($igrList as &$igr) { $igrNo = $igr->IGRNO; $fileDetails = $this->inwardgateregister_model->getAllIgrFileDetails($igrNo); $igr->isIgrFilePresent = false; // Initialize the key foreach ($fileDetails as $file) { if (!empty($file->file)) { $igr->isIgrFilePresent = true; break; } } } // Unset reference to avoid side effects unset($igr); $data['IGR'] = $igrList; $data['IGRDownload'] = $result[1]; $data['userRole'] = $this->session->get('role'); $data['transporter'] = $this->inwardgateregister_model->transporter(); $data['fromDate'] = date('d-m-Y', strtotime($fromDate)); $data['toDate'] = date('d-m-Y', strtotime($toDate)); $data['driverlist'] = $this->inwardgateregister_model->getdriverlist(); $this->loadViews("viewinwardgateregister", $this->global, $data, NULL); } function accountsDashboard(){ $toDate = date('Y-m-d'); $fromDate = date('Y-m-d'); $this->global['pageTitle'] = 'Accounts Dashboard'; $result = $this->inwardgateregister_model->customViewigrListing($fromDate, $toDate); $igrList = $result[0]; foreach ($igrList as &$igr) { $igrNo = $igr->IGRNO; $fileDetails = $this->inwardgateregister_model->getAllIgrFileDetails($igrNo); $igr->isIgrFilePresent = false; foreach ($fileDetails as $file) { if (!empty($file->file)) { $igr->isIgrFilePresent = true; break; } } } // Unset reference to avoid side effects unset($igr); $data['IGR'] = $igrList; $data['IGRDownload'] = $result[1]; $data['userRole'] = $this->session->get('role'); $data['transporter'] = $this->inwardgateregister_model->transporter(); $data['fromDate'] = date('d-m-Y', strtotime($fromDate)); $data['toDate'] = date('d-m-Y', strtotime($toDate)); $this->loadViews("accountsDashboard" , $this->global, $data, NULL); } function addIGR() { $this->inwardgateregister_model = new inwardgateregister_model(); $this->global['pageTitle'] = 'Add Inward Gate Register'; $result = $this->inwardgateregister_model->getpurchaseorder(); $result1 = $this->inwardgateregister_model->transporter(); $data['driverlist'] = $this->inwardgateregister_model->getdriverlist(); $data['transporter'] = array_filter($result1 , function($item) { return ($item->isactive == 1); }); // $data['PO_NO'] = array_filter($result, function($item) { // return !($item->status === 'ST027' && $item->IsOpenOrder === null); // }); $data['PO_NO'] = array_filter($result, function($item) { return !($item->status === 'ST027'); }); $data['emp_data'] = []; // $data['emp_data'] = $this->inwardgateregister_model->getAdditionalIGRFile(); // dd($data['driverlist']);die; $this->loadViews("inwardgateregister", $this->global, $data, NULL); } function addoutwardgateregister() { $this->inwardgateregister_model = new inwardgateregister_model(); $this->global['pageTitle'] = 'Add Outward Gate Register'; $data['Customer'] = $this->inwardgateregister_model->getCustomer(); $data['Supplier'] = $this->inwardgateregister_model->getSupplier(); //$data['Invoice'] = $this->inwardgateregister_model->getInvoice(); $data['storedmaterialcode'] = $this->inwardgateregister_model->getstoredmaterialcode(); //print_r($data['PO_NO']); $this->loadViews("ogr", $this->global, $data, NULL); } function ViewOgr() { $this->inwardgateregister_model = new inwardgateregister_model(); $this->global['pageTitle'] = 'View Outward Gate Register'; $data['OGR_Data'] = $this->inwardgateregister_model->getOGRData(); //print_r($data['OGR_Data']); $this->loadViews("ogrlist", $this->global, $data, NULL); } function EditOGR() { $OGRNO = $_GET['OGRNO']; $MRIRNO = $_GET['MRIRNO']; $this->global['pageTitle'] = 'View Outward Gate Register'; $data['OGR_Data'] = $this->inwardgateregister_model->getOGRDataforedit($OGRNO); $data['OGR_line'] = $this->inwardgateregister_model->getOGRlineDataforedit($OGRNO, $MRIRNO); $this->loadViews("editogr", $this->global, $data, NULL); } function GetInvoices() { $CustomerId = $this->request->getPost('customerId'); $data = $this->inwardgateregister_model->getInvoice($CustomerId); echo json_encode($data); } function GetPO() { $supplierId = $this->request->getPost('supplierId'); $data = $this->inwardgateregister_model->getPO($supplierId); echo json_encode($data); } function getPODetails() { $PONO = $this->request->getPost('PONO'); $data = $this->inwardgateregister_model->getPODetails($PONO); //$data['poout'] = $this->inwardgateregister_model->getPODetails($PONO); echo json_encode($data); } function getMRIRDetails() { $MRIRno = $this->request->getPost('mrirno'); $PONO = $this->request->getPost('PONO'); $materialcode = $this->request->getPost('materialcode'); $data = $this->inwardgateregister_model->getPOMRIRDetails($MRIRno, $PONO, $materialcode); //$data['outqty'] = $this->inwardgateregister_model->gettotalout($PONO,$materialcode); //$data['poout'] = $this->inwardgateregister_model->getPODetails($PONO); echo json_encode($data); } function getMRIR() { $MRIRno = $this->request->getPost('MRIRNO'); $PONO = $this->request->getPost('PONO'); $data = $this->inwardgateregister_model->getPOMRIRMaterial($MRIRno, $PONO); //$data['poout'] = $this->inwardgateregister_model->getPODetails($PONO); echo json_encode($data); } function getPOmrir() { $PONO = $this->request->getPost('PONO'); $data = $this->inwardgateregister_model->getPOmrir($PONO); //$data['poout'] = $this->inwardgateregister_model->getPODetails($PONO); echo json_encode($data); } function getPOmaterialDetails() { $PONO = $this->request->getPost('PONO'); $materialcode = $this->request->getPost('materialcode'); $data = $this->inwardgateregister_model->getPOmaterialDetails($PONO, $materialcode); echo json_encode($data); } function getPOmaterial() { $PONO = $this->request->getPost('PONO'); $data = $this->inwardgateregister_model->getPOmaterial($PONO); //$data['poout'] = $this->inwardgateregister_model->getPODetails($PONO); echo json_encode($data); } function getIGRLineItemDetails() { $PO = $this->request->getPost('id'); $CreatedBy = $this->session->get('userId'); // $this->inwardgateregister_model->UpdatePOMaster($PO, $CreatedBy,IGR_CREATED); $data = $this->inwardgateregister_model->viewpurchaseorder($PO); // echo "
"; print_r($data);die;

    echo json_encode($data);
  }
  
  

  function getAdditionalIGRFile()
  {

    $lastinsertbillid = 0;
    
    
    $pono = $this->request->getPost('PONO');
    $igr = $this->request->getPost('igr');
    
    $file = $this->request->getFile('file');
    $requestfilename = $file->getName();    

    $files = $this->inwardgateregister_model->getAdditionalIGRFile($igr);

    $fcount = 0;
    foreach ($files as $value) {
      $lastfile = $value->FilePath;// not a file path just file name only 
      if ($lastfile == $requestfilename) {
        $fcount++;
      }
    }


    if ($fcount == 0) {
      
      if (!empty($requestfilename)) {
        
        if ($file->isValid() && !$file->hasMoved()) {
          $path = ROOTPATH.'public/uploads/Igrfiles/';
          if(!is_dir($path)) { mkdir($path, 0777, true); }
          $Picture = $file->getName();
          $file->move($path, $Picture);    
        }else{
          $Picture = "";
        }

        $myfiles = array('PONO' => $pono, 'IGRNO' => $igr, 'FilePath' => $Picture);

        $lastinsertbillid = $this->inwardgateregister_model->uploadAdditionalFile($myfiles);
      }
    }

    if ($lastinsertbillid > 0) {
      echo "File updated Successfully!-".$lastinsertbillid;
    } else {
      echo "File name already Exist";
    }
  }

  function deleteAdditionalIGRFile(){

    $deleteAdditionalFile = false;
    $fileid = $this->request->getPost('id');
    $deleteAdditionalFile = $this->inwardgateregister_model->deleteAdditionalFile($fileid);
      return $this->response->setJSON([
        'status' => 'success',
        'message' => 'Operation successful',
        'data' => $deleteAdditionalFile
    ]);
 
  }


  function edituploadfile()
  {


    $bill = $this->request->getPost('param1');

    $oldfile = $this->request->getPost('param2');

    $newfile =  $this->request->getFile('file');
    
    
    if ($newfile->isValid() && !$newfile->hasMoved()) {
      $path = ROOTPATH . 'public/uploads/Igrfiles/';
      $newfilename = $newfile->getName();    
      if(!is_dir($path)) { mkdir($path, 0777, true); }
      $Picture = str_replace(" ", "", $newfilename);
      $newfile->move($path,$Picture);
    } else {
      $Picture = $oldfile;
    }

    $uploadfile = $this->inwardgateregister_model->updatefile($bill, $Picture, $oldfile);


    // if($uploadfile > 0){
    echo "updated successfully!";
    //  }
    //  else{
    //    echo "updated successfully!";
    // }
  }

  function SaveIGR()
  {
    #Step 1 IGR Details
    helper('numberseries');
    $PONO = $this->request->getPost('PONO');
    $IsThisOpenOrderPO = $this->request->getPost('hiddenIsOpenOrder');
    $DeliveryChellanOrInvoiceNo = $this->request->getPost('InvoiceNo');
    $DeliveryChellan = (string)$this->request->getPost('InvoiceDate');
    $DeliveryChellanDate = !$DeliveryChellan || $DeliveryChellan === null ? NULL : get_date_time_format($DeliveryChellan);
    $Mat_Rcvd_Dt = (string)$this->request->getPost('MaterialRcvdDate');
    $MaterialRcvdDt = !$Mat_Rcvd_Dt || $Mat_Rcvd_Dt === null ? NULL : get_date_time_format($Mat_Rcvd_Dt);
    $VehicleNo = $this->request->getPost('VehicleNo');
    $TransporterId = $this->request->getPost('TransporterId');
    $DriverName = $this->request->getPost('DriverName');
    $DriverMobileNumber = $this->request->getPost('DriverMobileNumber');
    $CreatedBy = $this->session->get('userId');
    $RowCount =  $this->request->getPost('txtRowCount');
    $MasterRemarks =  $this->request->getPost('MasterRemarks');
    $createddt =  get_current_date_time();
    //$IGRStatus = IGR_CREATED;//old
    $PreIGRStatus = (int)$this->request->getPost('hideIGRStatus') == 1 ? IGR_CREATED : IGR_DRAFT;
    $IGRStatus = ((int)$IsThisOpenOrderPO == 1) ? IGR_DRAFT : $PreIGRStatus;

    $igr = array(); // For IGR Master 
    $paymentstatus = NO_PAIDIGR;
    
    $fileupdated_count = 0;
    $fileupdated_name = []; 
   
    #Step 1 File Path Creation
    $path = ROOTPATH.'public/uploads/Igrfiles/'; 
    if(!is_dir($path)) { mkdir($path, 0777, true); }

    #Step 2 Master File and Its Details Gathering
    $MasterFile = $this->request->getFile('MasterFile');
    $requestMasterFileName = NULL;
     if (!empty($MasterFile)) {
      $requestMasterFileName = $MasterFile->getName(); 
         if ($MasterFile && $MasterFile->isValid() && !$MasterFile->hasMoved()) {
           if (!empty($this->inwardgateregister_model->isFileExistsInIGRmaster(filename: $requestMasterFileName))) {
             log_message('error', 'File already exists in the database'.$requestMasterFileName);
           }
           else{
             $MasterFile->move($path, $requestMasterFileName);  
             $fileupdated_count++;
             $fileupdated_name[] = $requestMasterFileName;  
           }
         } 
     }
    #Step 3 Master Details Gathering to Save In DB
    $last_igrno = $this->inwardgateregister_model->lastIGRNO();
    // echo $last_igrno;
    $newIGRNO = generate_igr_number($last_igrno); 
    // echo $newIGRNO;die;
    $igr = array('IGRNO'=>$newIGRNO,'PONO' => $PONO, 'VehicleNo' => $VehicleNo, 'TransporterId'=>$TransporterId,'DeliveryChellanOrInvoiceNo' => $DeliveryChellanOrInvoiceNo, 'DeliveryChellanDate' => $DeliveryChellanDate, 'MaterialRcvdDate' => $MaterialRcvdDt, 'DriverName' => $DriverName, 'DriverMobileNumber' => $DriverMobileNumber,'IGRStatus' => $IGRStatus, 'CreatedBy' => $CreatedBy, 'CreatedDate' => $createddt, 'PaymentStatus' => $paymentstatus, 'Remark'=>$MasterRemarks);
    $igr['MasterFile'] = $requestMasterFileName;
    #Step 4 Calling DB to Save IGR Master
    $IGRNO = $this->inwardgateregister_model->addigrM($igr);    

    if($IGRNO){

      $files = $this->request->getFiles();
      $fileNames = $this->request->getPost('file_name'); // Get user-entered file names
      if(isset($files['emp_file']))
      {
        foreach ($files['emp_file'] as $index => $file) {
            if ($file->isValid() && !$file->hasMoved()) {
                // Move the file to the desired directory
                $finallyfilename = (!empty($fileNames[$index])) ? $fileNames[$index] : $file->getName();
                $newName = $file->getRandomName();
                $file->move($path, $newName);
                // Store the file information in the database
                $additionalFiles = array(
                    'Remarks' => $finallyfilename, 
                    'FilePath' => $newName, 
                    'IGRNO' => $IGRNO,
                    'PONO' => $PONO  
                );
                $lastInsertFileId = $this->inwardgateregister_model->uploadAdditionalFile($additionalFiles);
                if ($lastInsertFileId) {
                  $fileupdated_count++;
                  $fileupdated_name[] = $finallyfilename;  
                }  
            }
        }
      }
   
      #Step 5 Save Master Detail On Stored on History Table
      # - Check Step 9 After I Insert.

      #Step 6 Updating OGR Details 
      $OGRStatus = $IGRStatus;
      $check_OGRPO = $this->inwardgateregister_model->update_OGR($PONO, $OGRStatus);
      // echo "uuu".(int)$check_OGRPO;
      $IGRItemStatus = REQITEM_NEW;
      $TotalPendingQty = '';
      $TotalPendingQty = (int)$TotalPendingQty;
      #Step 7 To Update the Date PO MASTER , Material Master , Historydetails and IGR line Item Details Updating OGR Details 
      for ($i = 1; $i <= (int)$RowCount; $i++) {
        $MaterialCode = $this->request->getPost('MaterialCode' . $i);
        $MaterialCode = $MaterialCode !== null && is_string($MaterialCode) ? trim($MaterialCode) : null;
        $QuantityAsPerInvoice = $this->request->getPost('txtQuantityAsPerInvoice' . $i);
        $QuantityAsPerInvoice = $QuantityAsPerInvoice !== null && is_string($QuantityAsPerInvoice) ? trim($QuantityAsPerInvoice) : null;
        $OrderedQuantity = $this->request->getPost('OrderedQuantity' . $i);
        $OrderedQuantity = $OrderedQuantity !== null && is_string($OrderedQuantity) ? trim($OrderedQuantity) : null;
        $ReceivedQty = $this->request->getPost('txtReceivedQuantity' . $i);
        $ReceivedQty = $ReceivedQty !== null && is_string($ReceivedQty) ? trim($ReceivedQty) : null;
        $PendingQty = $this->request->getPost('txtPendingQty' . $i);
        $TotalPendingQty = $TotalPendingQty + $PendingQty;
        $GrossWeight =  $this->request->getPost('txtGrossWeight' . $i);
        $grossWeightDate=  $this->request->getPost('txtGrossWeightDate' . $i);
        $TareWeight=  $this->request->getPost('txtTareWeight' . $i);
        $tareWeightDate=  $this->request->getPost('txtTareWeightDate' . $i);
        $NetWeight=  $this->request->getPost('txtNetWeight' . $i);
        // var_dump($grossWeightDate);
        // var_dump($tareWeightDate);
        #Step 8 Saving Weight File and Its Details Gathering
        $WeightFile = $this->request->getFile('txtWeightFile' . $i);
        $requestWeightFileName = $WeightFile->getName(); 
        // echo $i.$requestWeightFileName;die;

        if (!empty($requestWeightFileName)) {
            if ($WeightFile && $WeightFile->isValid() && !$WeightFile->hasMoved()) {
              //       $WeightFile->move($path, $requestWeightFileName);  
              if (!empty($this->inwardgateregister_model->isFileExistsInIGRdetails($requestWeightFileName))) {
                log_message('error', 'File already exists in the database'.$requestWeightFileName);
                $requestWeightFileName = NULL;
              }
              else{
                $WeightFile->move($path, $requestWeightFileName);   
                $fileupdated_count++;
                $fileupdated_name[] = $requestWeightFileName; 
              }
            }else{
              $requestWeightFileName = NULL;
            }
        }else{
          $requestWeightFileName = NULL;
        }

        $GrossWeightDate = !empty($grossWeightDate) && is_string($grossWeightDate) ? date('Y-m-d H:i:s', strtotime($grossWeightDate)) : null;
        $TareWeightDate = !empty($tareWeightDate) && is_string($tareWeightDate) ? date('Y-m-d H:i:s', strtotime($tareWeightDate)) : null;
        log_message('error', "TareWeightDate" .  $TareWeightDate);      
          $Remarks = $this->request->getPost('txtRemarks' . $i);
          $ItemStatus = '';
          if (strlen($QuantityAsPerInvoice) > 0 && $QuantityAsPerInvoice != '0') {
            if ($PendingQty == 0.00) {
              $ItemStatus  = $IGRStatus;
            } else {
              $ItemStatus  = POLINEITEM_IGRPARTIAL_CREATED;
            }
          }
          else if ((int)$IsThisOpenOrderPO == 1) {
            $ItemStatus  = POLINEITEM_IGRPARTIAL_CREATED;
          }

          $CreatedBy = $this->session->get('userId');

          $igrDetails = array(
            'IGRNO' => $IGRNO, 'MaterialCode' => $MaterialCode, 'QuantityAsPerInvoice' => $QuantityAsPerInvoice,
           'Remarks' => $Remarks, 'IGRItemStatus' => $IGRItemStatus,'GrossWeight' => (float)$GrossWeight ,
           'GrossWeightDate'=> $GrossWeightDate,'TareWeight' => (float)$TareWeight ,'TareWeightDate' => $TareWeightDate ,
           'NetWeight' => (float)$NetWeight,  'CreatedBy' => $CreatedBy, 'CreatedDate' => $createddt,

           //current change 04-04-2025 by vadivel
           'mIGRStatus' => $IGRStatus);

          $igrDetails['WeightFile'] =  $requestWeightFileName;
        
          log_message('error', 'SaveIGR igrDetails result : ' . json_encode($igrDetails));
          $igrlineno = "";
          if (strlen($QuantityAsPerInvoice) > 0 && $QuantityAsPerInvoice != '0' && ((int)$IsThisOpenOrderPO != 1)){
            $igrD = $this->inwardgateregister_model->addigrD($igrDetails); 
            $igrlineno = !empty($igrD) ? $igrD : '';
          }else if((int)$IsThisOpenOrderPO == 1){
            $igrD = $this->inwardgateregister_model->addigrD($igrDetails); 
            $igrlineno = !empty($igrD) ? $igrD : '';
          }
          if($igrlineno){
            $itemvalue = '';
            $SupplierId = '';
          
            $polineitemvalue = $this->inwardgateregister_model->getitemvalue($PONO, $MaterialCode);
            foreach ($polineitemvalue as $it) {
              $itemvalue = $it->Rate;
              $SupplierId = $it->SupplierID;
            }
            $historydetails = array('MaterialCode' => $MaterialCode, 'Transaction_type' => "Add", 'Ref_Type' => "IGR", 'Ref_No' => $igrlineno, 'Quantity' => $QuantityAsPerInvoice, 'CreatedBy' => $CreatedBy, 'CreatedOn' => $createddt, 'SupplierID' => $SupplierId, 'ItemValue' => $itemvalue);
            $this->inwardgateregister_model->addmaterialhistory($historydetails);

            $get_pre_qty = $this->inwardgateregister_model->get_CurrentQty($MaterialCode);
            $av_qty = 0; //$av_qty means Avaliable Quantity 
            if (!empty($get_pre_qty)) {
              foreach ($get_pre_qty as $gt) {
                $av_qty = $gt->Current_stock;
              }
            }
            $currentav_qty = (int)$QuantityAsPerInvoice + (int)$av_qty;
            $current_qty = array('Current_stock' => $currentav_qty);
            $this->inwardgateregister_model->addmaterialmaster($current_qty, $MaterialCode);
            $Recqty =  $this->inwardgateregister_model->getPOLineItemReceivedQty($PONO, $MaterialCode);
            $ReceivedQuantity = 0.00;
            if (count($Recqty) > 0) {
              foreach ($Recqty as $key) {
                $ReceivedQuantity = $key->ReceivedQuantity;
              }
            }
            $totalReceivedqty =  (int)$IsThisOpenOrderPO == 1 ? 0 : (int)$ReceivedQuantity + (int)$QuantityAsPerInvoice ;
            // $totalReceivedqty =  $ReceivedQuantity + $QuantityAsPerInvoice;
            if(((int)$totalReceivedqty > 0) && ((int)$IsThisOpenOrderPO != 1)){
              $POLineItem = array('ReceivedQuantity' => $totalReceivedqty, 'Status' => $ItemStatus, 'UpdateBY' => $CreatedBy, 'UpdatedOn' => $createddt);
              $this->inwardgateregister_model->UpdatePOLineItem($POLineItem, $PONO, $MaterialCode);
            }else if((int)$IsThisOpenOrderPO == 1){
              $POLineItem = array('ReceivedQuantity' => $totalReceivedqty, 'Status' => $ItemStatus, 'UpdateBY' => $CreatedBy, 'UpdatedOn' => $createddt);
              $this->inwardgateregister_model->UpdatePOLineItem($POLineItem, $PONO, $MaterialCode);
            }
          }
      }
      $this->inwardgateregister_model->UpdatePOMaster($PONO, $CreatedBy,$IGRStatus);
      
      #Step 9 Updating Pending Quantity IN PO Master amd Line Item Details. 
      if ((int)$IsThisOpenOrderPO != 1) {
      if ($TotalPendingQty == 0.00) {
        $Newstatus = array('Status' => $IGRStatus);
        $this->inwardgateregister_model->POLineItemsupdatestatus($PONO, $Newstatus);
        $this->inwardgateregister_model->pomasterupdatestatus($PONO, $Newstatus);
      } else { 
        /*echo 'error' ;*/
      }}
      #finally
      $finalstatement = "Successfully Created IGR Number: $IGRNO \n";
      
      # Step 5 Shifted Here
      // if($IGRNO){
      //     $igr_history = [
      //       'field' => NULL,
      //       'history_dated' => get_current_date_time(),
      //       'by' => $this->session->get('userId'),
      //       'IGR_No' => $IGRNO,
      //       'is_add' => 1 
      //     ];
  
      //     // Insert history entry
      //     $history_id = $this->inwardgateregister_model->igr_history($igr_history);
          
      //     if ($history_id) {
      //         log_message('error', "History Newly Created for IGR No: $IGRNO. History ID: $history_id. ");
      //     } 
      // }

      if($IGRNO){
        if($IGRStatus !== ""){
          $NamedIGRStatus = $this->inwardgateregister_model->get_status($IGRStatus);

          $igr_history = [
            'field' => "IGRStatus",
            'new_data' => $NamedIGRStatus,
            'old_data' => "",
            'history_dated' => get_current_date_time(),
            'by' => $this->session->get('userId'),
            'IGR_No' => $IGRNO,
            'is_add' => 1 
          ];

          // Insert history entry
          $history_id = $this->inwardgateregister_model->igr_history($igr_history);
          if ($history_id) {
              log_message('error', "History Newly Created for IGR No: $IGRNO. History ID: $history_id. ");
          }
        }
      }
      
      if ($fileupdated_count > 0) {
          $finalstatement .= "Number of files updated: $fileupdated_count \n";
          // $finalstatement .= "Files: \n" . implode(PHP_EOL, $fileupdated_name);
          $finalstatement .= "Files: \n" . implode(PHP_EOL, array_map(fn($file) => "• " . $file, $fileupdated_name));
      } else {
          $finalstatement .= "No files to update";
      }
  } else {
      $finalstatement = 'No data available to process IGR.';
  }
  
  // Escape newlines and quotes for the JavaScript alert
  $finalstatement = json_encode($finalstatement);

  echo "";

}
function drivernameautocomplete(){
      $dr = $this->request->getGet('query');
      $query = $this->inwardgateregister_model->checkdrivername($dr);
      echo json_encode($query);
}
public function drivermobileautocomplete() {
  $dr = $this->request->getGet('query');
  $drName = $this->request->getGet('driverName');
  $query = $this->inwardgateregister_model->checkdriverMobile($dr, $drName);
  echo json_encode($query);
}


public function drivermobileautocomplete2() {
  $driverName = $this->request->getGet('drivername');
  $term = $this->request->getGet('term');

  // Debugging
  if (!$driverName || !$term) {
      return $this->response->setJSON(['error' => 'Missing parameters']);
  }

  $query = $this->inwardgateregister_model->checkdriverMobile($driverName, $term);

  // Check the output
  if (is_array($query)) {
      return $this->response->setJSON($query);
  } else {
      return $this->response->setJSON(['error' => 'Invalid response from model']);
  }
}

function viewIGRDetails()
{

  $IGRNO = $this->request->getPost('id');
  
  $data['details'] =  $this->inwardgateregister_model->viewigr($IGRNO);

  $TaxInPercentage = 0;
  for ($i = 0; $i < count($data['details']); $i++) {
    $details = $data['details'][$i];

    if ($details->POType == 'IMPORT') {
        $TaxInPercentage = isset($details->import_igst) ? $details->import_igst : 0;
    }

    if ($details->POType == 'CAPITAL' && $details->CapitalRange == 0) {
        $TaxInPercentage = isset($details->import_igst) ? $details->import_igst : 0;
    }

    if ($details->POType == 'CAPITAL' && $details->CapitalRange == 1) {
        $TaxInPercentage = 
            (isset($details->service_cgst) ? $details->service_cgst : 0) +
            (isset($details->service_sgst) ? $details->service_sgst : 0) +
            (isset($details->service_igst) ? $details->service_igst : 0);
    }

    if ($details->POType == 'REVENUE') { 
        $TaxInPercentage = 
            (isset($details->revenue_cgst) ? $details->revenue_cgst : 0) +
            (isset($details->revenue_sgst) ? $details->revenue_sgst : 0) +
            (isset($details->revenue_igst) ? $details->revenue_igst : 0);
    }

    if ($details->POType == 'SERVICE') {
        $TaxInPercentage = 
            (isset($details->service_cgst) ? $details->service_cgst : 0) +
            (isset($details->service_sgst) ? $details->service_sgst : 0) +
            (isset($details->service_igst) ? $details->service_igst : 0);
    }

    $data['details'][$i]->TaxInPercentage = $TaxInPercentage;
  }
  $data['files'] =  $this->inwardgateregister_model->viewIGRFile($IGRNO);

  echo json_encode($data);
}
  function ViewIGRfile()
  {
    $IGRNO = $this->request->getPost('id');
    $igrfile =  $this->inwardgateregister_model->viewIGRFile($IGRNO);
    $billfile = []; // $this->inwardgateregister_model->ViewIGRfile1($IGRNO);
    $data = array_merge($igrfile, $billfile);
    echo json_encode($data);
  }
  function ViewIGRHistory()
  {
    $IGRNO = $this->request->getPost('igr');
    $result =  $this->inwardgateregister_model->ViewIGRHistory($IGRNO);
    return $this->response->setJSON($result);
  }
  function getCostCenterData()
  {
    $pono = $this->request->getPost('pono');
    $result =  $this->inwardgateregister_model->getCostCenterData($pono);

    return $this->response->setJSON($result);
  }


  function UpdateIGR()
  {
 
    $IGRNo = $this->request->getPost('igr');
    $PONo = $this->request->getPost('po');

    $DeliveryChellanOrInvoiceNo = $this->request->getPost('invno');
    $DeliveryChellan = $this->request->getPost('invdate');
    $DeliveryChellanDate = !$DeliveryChellan || $DeliveryChellan === null ? NULL : get_date_time_format($DeliveryChellan);

    $Mat_Rcvd_Dt = $this->request->getPost('mrc');
    $MaterialRcvdDt = !$Mat_Rcvd_Dt || $Mat_Rcvd_Dt === null ? NULL : get_date_time_format($Mat_Rcvd_Dt);


    $VehicleNo = $this->request->getPost('vehicle_no');
    $TransporterId = $this->request->getPost('Transporter_Id');
    $DriverName = $this->request->getPost('driver');
    $DriverMobileNumber = $this->request->getPost('driver_mobile');

    $IGRStatus = (int)$this->request->getPost('status') == 1 ? IGR_CREATED : IGR_DRAFT;

    $tableData = $this->request->getPost('tableData');
    if (is_string($tableData)) {
      $tableData = json_decode($tableData, true);
    }
    $updateby  = $this->session->get('userId');

    $path = ROOTPATH.'public/uploads/Igrfiles/'; 
    if(!is_dir($path)) { mkdir($path, 0777, true); }

    $MasterRemarks = $this->request->getPost('MasterRemarks');
    $igrarr = array('DeliveryChellanDate' => $DeliveryChellanDate, 'MaterialRcvdDate' => $MaterialRcvdDt,'VehicleNo'=>$VehicleNo,'TransporterId'=>$TransporterId,'DriverMobileNumber'=>$DriverMobileNumber,'DriverName'=>$DriverName, 'IGRStatus' => $IGRStatus,'UpdateBY' => $updateby,'DeliveryChellanOrInvoiceNo'=>$DeliveryChellanOrInvoiceNo,'Remark'=>$MasterRemarks);

    $MasterFile = $this->request->getfile('MasterFile');
    $fileupdated_count = 0;
    $fileupdated_name = []; 

    if (!empty($MasterFile)) {
      $requestMasterFileName = $MasterFile->getName(); 
      if ($MasterFile && $MasterFile->isValid() && !$MasterFile->hasMoved()) {
        if (!empty($this->inwardgateregister_model->isFileExistsInIGRmaster($requestMasterFileName))) {
          log_message('error', 'File already exists in the database'.$requestMasterFileName);
        }
        else{
          $MasterFile->move($path, $requestMasterFileName); 
          $fileupdated_count++;
          $fileupdated_name[] = $requestMasterFileName;    
          $igrarr['MasterFile'] = $requestMasterFileName;
        }
      }
    }

      $fileNames = $this->request->getPost('file_name');   
      $files = $this->request->getFileMultiple('emp_file');       


      if(isset($files))
      {
        foreach ($files as $index => $file) {
     
            if ($file->isValid() && !$file->hasMoved()) {

                // Move the file to the desired directory
                $finallyfilename = (!empty($fileNames[$index])) ? $fileNames[$index] : $file->getName();
                $newName = $file->getRandomName();
                $file->move($path, $newName);
                // Store the file information in the database
                $additionalFiles = array( 
                    'Remarks' => $finallyfilename,  
                    'FilePath' => $newName,  
                    'IGRNO' => $IGRNo, 
                    'PONO' => $PONo  
                );
                $lastInsertFileId = $this->inwardgateregister_model->uploadAdditionalFile($additionalFiles);
                if ($lastInsertFileId) {
                  $fileupdated_count++;
                  $fileupdated_name[] = $finallyfilename;  
                }  
            }  
        }
      }
   
    $this->saveIGRMasterHistory($igrarr,$IGRNo);
    $getigrstatus =  $this->inwardgateregister_model->getigrstatus($IGRNo);
    $getigrstatus = $getigrstatus->IGRStatus;
    $updateigrmaster =  $this->inwardgateregister_model->updateigr($igrarr, $IGRNo);

    log_message('error', "Master updated successfully: " . $updateigrmaster);
    if(!empty($tableData )){

        foreach ($tableData as $row) {
          $quantityAsPerInvoice = $row['QuantityAsPerInvoice'];
          $remarks = $row['Remarks'];
          $grossWeight = $row['GrossWeight'];
          $grossWeightDate = $row['GrossWeightDate'];
          $tareWeight = $row['TareWeight'];
          $tareWeightDate = $row['TareWeightDate'];
          $netWeight = $row['NetWeight'];
          $igrItemNo = $row['IGRItemNo'];
          $GrossWtDt = !empty($grossWeightDate) && strtolower($grossWeightDate) !== 'null' ? get_date_time_format($grossWeightDate) : NULL;
          $TareWtDt = !empty($tareWeightDate) && strtolower($tareWeightDate) !== 'null' ? get_date_time_format($tareWeightDate) : NULL;
               
                    $igrline = array(
                        'QuantityAsPerInvoice' => $quantityAsPerInvoice,
                        'Remarks' => $remarks,
                        'GrossWeight' => $grossWeight,
                        'GrossWeightDate' => $GrossWtDt,
                        'TareWeight' => $tareWeight,
                        'TareWeightDate' => $TareWtDt,
                        'NetWeight' => $netWeight,
                        'IGRItemNo' => $igrItemNo,
                        'UpdateBY' => $updateby
                    );
                    $this->saveIGRLineitemHistory($igrline, $IGRNo,$igrItemNo);
                    // $WeightFile = $this->request->getfile('WeightFile');
                    // $requestWeightFileName = $WeightFile->getName(); 
  
                    // if (!empty($requestWeightFileName)) {
                    //   if ($WeightFile && $WeightFile->isValid() && !$WeightFile->hasMoved()) {
                    //     if (!empty($this->inwardgateregister_model->isFileExistsInIGRdetails($requestWeightFileName))) {
                    //       log_message('error', 'File already exists in the database'.$requestWeightFileName);
                    //     }
                    //     else{
                    //       $WeightFile->move($path, $requestWeightFileName);   
                    //       $igrline['WeightFile'] = $requestWeightFileName;
                    //     }
                    //   }
                    // }
  
                    $updateigrlineitem = $this->inwardgateregister_model->updateIGRLineItem($igrline, $igrItemNo);
                    log_message('error', "lineitem updated successfully: " . $updateigrlineitem);
                    log_message('error', 'UpdateIGR updateigrlineitem: ' . json_encode($igrline));
        }

        

    }
    if ($getigrstatus == 'ST027' && ($updateigrmaster > 0 || $updateigrlineitem > 0)) {
     
      if(session()->get('roleText') == 'System Administrator') // id is 1
      {
        $roleId = 2;
      }
      else if(session()->get('roleText') == 'Auditor')  // id is 2
      {
        $roleId = 1;
      }
      $result_for_email = $this->inwardgateregister_model->getDetailsforEmail($this->session->get('userId'),$roleId);
      $result_for_history = $this->inwardgateregister_model->getHistoryDetailsforEmail($IGRNo);
      
       
      $notification = new Notification();
      
      $history_content = "
IGR History

"; $to_email_addr = ""; for ($i = 0; $i < count($result_for_email['to_mails']); $i++) { $to_email_addr .= $result_for_email['to_mails'][$i]->email . " , "; } // $to_email_addr .= "sanjeev.p@venbainfotech.com,gowtham.m@venbainfotech.com"; $to_email_addr = rtrim($to_email_addr, " ,"); $email_response = $notification->sendEmail([ 'recipient_email' => $to_email_addr, 'subject' => $result_for_email['company'].' - IGR Notification', 'carboncopy' =>"pavithra.t@venbainfotech.com", // 'description' => 'IGR Number : '.$IGRNo.' is Edited By '.($result_for_email['full_name'] ?? $this->session->get('name'))." On ".date('d-m-Y H:i A', strtotime(get_current_date_time() . ' +30 seconds')). $history_content, 'description' => $result_for_history['first_line']."
" .$history_content, 'company' => $result_for_email['company'], 'from_mail'=> $result_for_email['from_mails'] ]); log_message('error', 'email reponse : ' . json_encode($email_response)); // Determine the email response $mail_log = isset($email_response['success']) ? 'Email sent successfully' : 'Failed to send email'; $receiving_status = isset($email_response['success']) ? 1 : 0; // Log the result if ($receiving_status) { $this->logger->info("Email IDs = " . $to_email_addr . " " . $mail_log); } else { $this->logger->error("Email IDs = " . $to_email_addr . " " . $mail_log); } // echo "***".$history_content;die; }else{ $this->logger->info("History content Not Founded...."); } } if ($updateigrmaster > 0) { $finalstatement = "Successfully Updated IGR Number: $IGRNo \n"; } else if($updateigrlineitem >0){ $finalstatement = "Successfully Updated IGR Number: $IGRNo \n"; }else{ $finalstatement = "IGR Number: $IGRNo \n"; } if ($fileupdated_count > 0) { $finalstatement .= "Number of files updated: $fileupdated_count \n"; // $finalstatement .= "Files: \n" . implode(PHP_EOL, $fileupdated_name); $finalstatement .= "Files: \n" . implode(PHP_EOL, array_map(fn($file) => "• " . $file, $fileupdated_name)); } else { $finalstatement .= "No files to update"; } echo $finalstatement; } function updateIGRWeight(){ $GrossWeight = $this->request->getPost('GrossWeight'); $GrossWeightDate = $this->request->getPost('GrossWeightDate'); $TareWeight = $this->request->getPost('TareWeight'); $TareWeightDate = $this->request->getPost('TareWeightDate'); $NetWeight = $this->request->getPost('NetWeight'); $IGRNO = $this->request->getPost('IGR'); $IGRItemNo = $this->request->getPost('IGRlineitem'); $updateby = $this->session->get('userId'); $WeightFile = $this->request->getfile('WeightFile'); $GrossWtDt = (!empty($GrossWeightDate) && (string)$GrossWeightDate != 'null' ) ? get_date_time_format($GrossWeightDate) : null; $TareWtDt =(!empty($TareWeightDate) && (string)$TareWeightDate != 'null') ? get_date_time_format($TareWeightDate) : null; $path = ROOTPATH.'public/uploads/Igrfiles/'; if(!is_dir($path)) { mkdir($path, 0777, true); } $IGRItemNo = $this->request->getPost('IGRlineitem'); $igr_lineitem = array('GrossWeight' => $GrossWeight,'GrossWeightDate' => $GrossWtDt,'TareWeightDate' => $TareWtDt,'TareWeight' => $TareWeight,'NetWeight' => $NetWeight,'UpdateBY' => $updateby); $this->saveIGRLineitemHistory($igr_lineitem, $IGRNO,$IGRItemNo); $requestWeightFileName =null ; $msg = null; if ($WeightFile && $WeightFile->isValid() && !$WeightFile->hasMoved()) { $requestWeightFileName = $WeightFile->getName(); // Generate a unique name // Optional: Check for duplicates in DB if needed if (!empty($this->inwardgateregister_model->isFileExistsInIGRdetails($requestWeightFileName))) { log_message('error', 'File already exists in the database: ' . $requestWeightFileName); $msg = "'File already exists in the database: ' . $requestWeightFileName"; } else { $WeightFile->move($path, $requestWeightFileName); $igr_lineitem['WeightFile'] = $requestWeightFileName; $msg = ""; } }else{ log_message('error', 'File invlisd: ' . $requestWeightFileName); $msg = ""; } $update = $this->inwardgateregister_model->updateIGRLineItem($igr_lineitem, $IGRItemNo); if ($update) { echo "Details updated successfully!\n".$msg; } } function AddOgr() { //echo "string"; $type = $this->request->getPost('type'); $Supplier = $this->request->getPost('sup'); $Date = $this->request->getPost('Date'); $vehicle = $this->request->getPost('Vehicle'); $driver = $this->request->getPost('drive'); if ($type == 1) { $invoice = $this->request->getPost('invno'); $Otype = 'Invoice'; $Status = 'ST063'; $ogrmaster = array( 'OgrType' => $Otype, 'CreatedDate' => $Date, 'Driver' => $driver, 'PONO_INV' => $invoice, 'VehicleNo' => $vehicle, 'Status' => $Status ); $addogrmaster = $this->inwardgateregister_model->AddOGR($ogrmaster); $OGRNO = ''; if (count($addogrmaster) > 0) { foreach ($addogrmaster as $add) { $OGRNO = $add->OGRNO; } } $itemcode = $this->request->getPost('itemcode'); $Description = $this->request->getPost('Description'); $invoutwardqty = $this->request->getPost('invoutwardqty'); $Ogrline = array('OGRNO' => $OGRNO, 'MaterialCode' => $itemcode, 'OutwardQty' => $invoutwardqty, 'Status' => $Status); $addOgrline = $this->inwardgateregister_model->AddOgrLine($Ogrline); if ((count($addogrmaster) > 0) && ($addOgrline > 0)) { echo "Saved Successfully OGR No is OGR" . $OGRNO; } } else if ($type == 2) { $pono = $this->request->getPost('pono'); $MRIRNO = $this->request->getPost('mrirno'); $Otype = 'PO'; $row = $this->request->getPost('rowcount'); $ogrmaster = array( 'OgrType' => $Otype, 'CreatedDate' => $Date, 'Driver' => $driver, 'PONO_INV' => $pono, 'VehicleNo' => $vehicle, 'MRIRNO' => $MRIRNO ); $addogrmaster = $this->inwardgateregister_model->AddOGR($ogrmaster); $OGRNO = ''; if (count($addogrmaster) > 0) { foreach ($addogrmaster as $add) { $OGRNO = $add->OGRNO; } } for ($i = 1; $i <= $row; $i++) { $MaterialCode = $this->request->getPost('materialcode' . $i); $OutwardQty = $this->request->getPost('outward' . $i); $rejqty = $this->request->getPost('RejectedQty' . $i); $pendingoutward = $this->request->getPost('pendingoutward' . $i); $balance_Qty = $rejqty - $OutwardQty; //$balance_Qty = $this->request->getPost('pendingoutward'.$i); $Outwardtotal = $OutwardQty; $allowed = $this->request->getPost('allowed' . $i); if ($MaterialCode != '' && $OutwardQty != '') { $polqty = $this->inwardgateregister_model->getPOLineItemReceivedQty($pono, $MaterialCode); $ReceivedQuantity = 0.00; if (count($polqty) > 0) { foreach ($polqty as $key) { $ReceivedQuantity = $key->ReceivedQuantity; } } $totalReceivedqty = $ReceivedQuantity - $Outwardtotal; $POMStatus = OGR_CREATED; $POLineItem = array('ReceivedQuantity' => $totalReceivedqty, 'OGR_Status' => $POMStatus); $this->inwardgateregister_model->UpdatePOLineItem($POLineItem, $pono, $MaterialCode); if ($pendingoutward == 0) { $Status = OGR_COMPLETE; } else { $Status = OGR_PARTIAL_COMPLETE; } $Ogrline = array('OGRNO' => $OGRNO, 'MaterialCode' => $MaterialCode, 'OutwardQty' => $Outwardtotal, 'Status' => $Status, 'balance_Qty' => $balance_Qty); $addOgrline = $this->inwardgateregister_model->AddOgrLine($Ogrline); //print_r($addOgrline); $ogrlineno = ''; $itemvalue = ''; $SupplierId = ''; $CreatedBy = $this->session->get('userId'); $createddt = get_current_date_time(); if (count($addogrmaster) > 0) { $ogrlinearray = $this->inwardgateregister_model->getlastogrline(); foreach ($ogrlinearray as $og) { $ogrlineno = $og->OGRItemNO; } $polineitemvalue = $this->inwardgateregister_model->getitemvalue($pono, $MaterialCode); foreach ($polineitemvalue as $it) { $itemvalue = $it->Rate; $SupplierId = $it->SupplierID; } } $historydetails = array('MaterialCode' => $MaterialCode, 'Transaction_type' => "Reduce", 'Ref_Type' => "OGR", 'Ref_No' => $ogrlineno, 'Quantity' => $Outwardtotal, 'CreatedBy' => $CreatedBy, 'CreatedOn' => $createddt, 'ItemValue' => $itemvalue, 'SupplierID' => $SupplierId); $this->inwardgateregister_model->addmaterialhistory($historydetails); $get_pre_qty = $this->inwardgateregister_model->get_CurrentQty($MaterialCode); $av_qty = 0; if (!empty($get_pre_qty)) { foreach ($get_pre_qty as $gt) { $av_qty = $gt->Current_stock; } } $currentav_qty = $av_qty - $Outwardtotal; $current_qty = array('Current_stock' => $currentav_qty); $this->inwardgateregister_model->addmaterialmaster($current_qty, $MaterialCode); $this->inwardgateregister_model->UpdateOGRMasterOGRStatus($OGRNO); $this->inwardgateregister_model->UpdateMRIRMasterOGRStatus($MRIRNO, $OGRNO); $mrirout = $this->inwardgateregister_model->GetMRIROutQty($MRIRNO, $MaterialCode); $premrirout = 0; if (!empty($mrirout)) { foreach ($mrirout as $mr) { $premrirout = $mr->Ogr_Out_Qty; } } $totmrirout = $premrirout + $Outwardtotal; $mrirarray = array('Ogr_Out_Qty' => $totmrirout); $this->inwardgateregister_model->UpdateMRIROUTQty($mrirarray, $MRIRNO, $MaterialCode); $POMasterStatus = array('Status' => PO_RELEASED); $this->inwardgateregister_model->UpdatePOMasterOGRStatus($pono, $POMasterStatus); } } if ((count($addogrmaster) > 0) && (count($addOgrline) > 0)) { echo "Saved Successfully OGR No is OGR" . $OGRNO; } } else if ($type == 3) { $Otype = 'SERVICE'; $Status = 'ST063'; $ogrmaster = array('OgrType' => $Otype, 'CreatedDate' => $Date, 'Driver' => $driver, 'VehicleNo' => $vehicle, 'Status' => $Status); $addogrmaster = $this->inwardgateregister_model->AddOGR($ogrmaster); //print_r($addogrmaster); $OGRNO = ''; //echo count($addogrmaster); if (count($addogrmaster) > 0) { foreach ($addogrmaster as $add) { $OGRNO = $add->OGRNO; } } $material = $this->request->getPost('material'); $name = $this->request->getPost('name'); $pooutward = $this->request->getPost('pooutward'); $destination = $this->request->getPost('destination'); $Remarks = $this->request->getPost('Remark'); $Ogrline = array('OGRNO' => $OGRNO, 'MaterialCode' => $material, 'OutwardQty' => $pooutward, 'Destination' => $destination, 'Status' => $Status, 'SupplierID' => $name, 'Remark' => $Remarks); //print_r($Ogrline); //die(); $addOgrline = $this->inwardgateregister_model->AddOgrLine($Ogrline); if ((count($addogrmaster) > 0) && ($addOgrline > 0)) { echo "Saved Successfully OGR No is OGR" . $OGRNO; } } } public function downloadFilesAsZip() { // Get the IGR number from query string $igrno = $this->request->getGet('IGRNO'); // Get file details based on IGR number $fileDetails = $this->inwardgateregister_model->getAllIgrFileDetails($igrno); // Define root path for original files $fileRootPath = ROOTPATH . 'public/uploads/Igrfiles/'; // Define separate directory for ZIP output $zipDir = ROOTPATH . 'writable/zips/'; if (!is_dir($zipDir)) { if (!mkdir($zipDir, 0777, true)) { echo ''; return; } } // Make sure ZIP directory is writable if (!is_writable($zipDir)) { echo ''; return; } // OPTIONAL: Set PHP's temp directory if the system one is failing $customTemp = ROOTPATH . 'writable/tempzip/'; if (!is_dir($customTemp)) { mkdir($customTemp, 0777, true); } ini_set('sys_temp_dir', $customTemp); // Create ZIP archive $zip = new ZipArchive(); $zipFileName = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $igrno) . '.zip'; // sanitize filename $zipFilePath = $zipDir . $zipFileName; if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) { echo ''; return redirect()->to('/ViewIGR'); } $filesAdded = false; // Add each file to ZIP foreach ($fileDetails as $file) { $filePath = $fileRootPath . $file->file; if (file_exists($filePath) && is_file($filePath)) { $sanitizedFilename = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $file->file); if (!$zip->addFile($filePath, $sanitizedFilename)) { echo ''; $zip->close(); return redirect()->to('/ViewIGR'); } $filesAdded = true; } else { echo ''; } } if ($filesAdded) { $zip->close(); return $this->response->download($zipFilePath, null)->setFileName($zipFileName); } else { $zip->close(); if (file_exists($zipFilePath)) { unlink($zipFilePath); } echo ''; return redirect()->to('/ViewIGR'); } } public function getIGRRemarks() { $igrNo = $this->request->getPost('igr_no'); $data = $this->IGRRemarks_model->select('t_igr_remarkes.remark ,t_igr_remarkes.remark_on , t_employee_details.FirstName as remark_by') ->join('t_employee_details', 't_igr_remarkes.remark_by = t_employee_details.EmpID', 'left') ->where('t_igr_remarkes.igr_no', $igrNo) ->findAll(); echo json_encode($data); } public function saveIGRRemarks() { $data['igr_no'] = $this->request->getPost('igr_no'); $data['remark'] = $this->request->getPost('remark'); $data['remark_by'] = session()->get('EmpID'); $data['remark_on'] = date('Y-m-d H:i:s'); $insert = $this->IGRRemarks_model->save($data); $data = $this->IGRRemarks_model->select('t_igr_remarkes.remark ,t_igr_remarkes.remark_on , t_employee_details.FirstName as remark_by') ->join('t_employee_details', 't_igr_remarkes.remark_by = t_employee_details.EmpID', 'left') ->where('t_igr_remarkes.igr_no', $data['igr_no']) ->findAll(); $this->sendRemarkMail($this->request->getPost('igr_no'),$this->request->getPost('remark'),session()->get('EmpID')); echo json_encode($data); } public function sendRemarkMail($IGRNo,$remark,$empCode) { if(session()->get('roleText') == 'System Administrator') // id is 1 { $roleId = 2; } else if(session()->get('roleText') == 'Auditor') // id is 2 { $roleId = 1; } $result_for_email = $this->inwardgateregister_model->getDetailsforEmail($this->session->get('userId'),$roleId); // print_r($result_for_email);die; $to_email_addr = ''; for ($i = 0; $i < count($result_for_email['to_mails']); $i++) { $to_email_addr .= $result_for_email['to_mails'][$i]->email . " , "; } // $to_email_addr = " venbalap08@gmail.com , sanjeev.p@venbainfotech.com"; $to_email_addr = rtrim($to_email_addr, " ,"); $content = 'A new remark was created by '.$result_for_email['full_name'].' against IGR no '.$IGRNo.',

"'.$remark.'"'; $notification = new Notification(); $notification->sendEmail([ 'recipient_email' => $to_email_addr, 'subject' => $result_for_email['company'].' - IGR Remark Raised', 'carboncopy' =>"pavithra.t@venbainfotech.com", 'description' => $content, 'company' => $result_for_email['company'], 'from_mail'=> $result_for_email['from_mails'] ]); } public function saveIGRMasterHistory($request, $IGRNo) { $dbIGRMaster = $this->inwardgateregister_model->get_igr_master_for_history($IGRNo); $history_entries = []; foreach ($request as $key => $value) { foreach ($dbIGRMaster as $key1 => $value1) { if ($value1 != $value && $key1 == $key) { $value = ($key1 == "IGRStatus") ? $this->inwardgateregister_model->get_status($value) : $value; $value1 = ($key1 == "IGRStatus") ? $this->inwardgateregister_model->get_status($value1) : $value1; $value = ($key1 == "TransporterId") ? $this->inwardgateregister_model->get_TransporterId($value) : $value; $value1 = ($key1 == "TransporterId") ? $this->inwardgateregister_model->get_TransporterId($value1) : $value1; // Store each changed field in an array $history_entries[] = [ 'field' => $key1, 'new_data' => $value, 'old_data' => $value1, 'history_dated' => get_current_date_time(), 'by' => $this->session->get('userId'), 'IGR_No' => $IGRNo, 'IGRItem_No' => NULL, 'is_edit' => 1, ]; } } } // Insert all history entries foreach ($history_entries as $entry) { $history_id = $this->inwardgateregister_model->igr_history($entry); if ($history_id) { log_message('error', "History updated successfully for IGR No: $IGRNo, Field: {$entry['field']}. History ID: $history_id"); } else { log_message('error', "Failed to update history for IGR No: $IGRNo, Field: {$entry['field']}"); } } } public function saveIGRLineitemHistory($request, $IGRNo, $IGRLineItem) { $dbIGRChild = $this->inwardgateregister_model->get_igr_child_for_history($IGRNo, $IGRLineItem); $history_entries = []; foreach ($request as $key => $value) { foreach ($dbIGRChild as $key1 => $value1) { if ($value1 != $value && $key1 == $key) { // Store each changed field in an array $history_entries[] = [ 'field' => $key1, 'new_data' => $value, 'old_data' => $value1, 'history_dated' => get_current_date_time(), 'by' => $this->session->get('userId'), 'IGR_No' => $IGRNo, 'IGRItem_No' => $IGRLineItem, 'is_edit' => 1, ]; } } } // Insert all history entries foreach ($history_entries as $entry) { $history_id = $this->inwardgateregister_model->igr_history($entry); if ($history_id) { log_message('error', "History updated successfully for IGR No: $IGRNo, Item No: $IGRLineItem, Field: {$entry['field']}. History ID: $history_id"); } else { log_message('error', "Failed to update history for IGR No: $IGRNo, Item No: $IGRLineItem, Field: {$entry['field']}"); } } } /* ********************************************************* sec_gas_shortage_starts ************************************************************** */ public function gasCylinderEntered(){ $this->global['pageTitle'] = 'Gas Cylinder Entered'; $gasMaterialCodes = $this->rawMaterialDetails_model->getAllGasMaterialCode(); $gasMaterialCodes = array_column($gasMaterialCodes,'MaterialCode'); $igrDetailsListByMcatGas = $this->inwardgateregister_model->getIgrDetailsListByMcatGas($gasMaterialCodes,"gas_entered"); $data['gasCylinderEnteredList'] = $igrDetailsListByMcatGas; $this->loadViews("gasCylinderEntered", $this->global, $data, NULL); } public function gasCylinderPending(){ $this->global['pageTitle'] = 'Gas Cylinder Pending'; $gasMaterialCodes = $this->rawMaterialDetails_model->getAllGasMaterialCode(); $gasMaterialCodes = array_column($gasMaterialCodes,'MaterialCode'); $igrDetailsListByMcatGas = $this->inwardgateregister_model->getIgrDetailsListByMcatGas($gasMaterialCodes,"gas_pending"); $data['gasCylinderPendingList'] = $igrDetailsListByMcatGas; $this->loadViews("gasCylinderPending", $this->global, $data, NULL); } public function gasCylinderReturned(){ $this->global['pageTitle'] = 'Gas Cylinder Returned'; $gasMaterialCodes = $this->rawMaterialDetails_model->getAllGasMaterialCode(); $gasMaterialCodes = array_column($gasMaterialCodes,'MaterialCode'); $igrDetailsListByMcatGas = $this->inwardgateregister_model->getIgrDetailsListByMcatGas($gasMaterialCodes,"gas_returned"); $data['gasCylinderReturnedList'] = $igrDetailsListByMcatGas; $this->loadViews("gasCylinderReturned", $this->global, $data, NULL); } public function updateGasShortage() { try { $postData = $this->request->getJSON(true); // Convert JSON to an associative array // Validate if any data is received if (!$postData) { return $this->response->setJSON([ 'status' => 'error', 'message' => 'Invalid request. No data received.' ]); } // Validate required fields if (empty($postData['invoiceNo']) ) { return $this->response->setJSON([ 'status' => 'error', 'message' => 'Missing invoiceNo data.' ]); } $updates = []; $inserts = []; if(isset($postData['id'])){ //update operation $cylinderData = [ 'id' => $postData['id'], 'IGRNO' => $postData['IGRNO'] ?? '', 'fullCylinderDate' => $postData['fullCylinderDate'] ?? '', 'emptyCylinderDate' => $postData['emptyCylinderDate'] ?? '', 'invoiceNo' => $postData['invoiceNo'] ?? '', 'cylinderNo' => $postData['cylinderNo'], 'grossWeight' => $postData['grossWeight'], 'tareWeight' => $postData['tareWeight'] ?? '', 'netWeight' => $postData['netWeight'] ?? '', 'actualWeight' => $postData['actualWeight'], 'shortage' => $postData['shortage'] ?? '', 'gas_cylinder_status' => "gas_returned" ]; $updates[] = $cylinderData ; }else{//Insert Operation // Process each cylinder entry foreach ($postData['cylinders'] as $cylinder) { // Ensure cylinder data is valid if (!isset($cylinder['cylinderNo'], $cylinder['grossWeight'], $cylinder['actualWeight'])) { continue; // Skip incomplete data } $cylinderData = [ 'IGRNO' => $postData['IGRNO'] ?? '', 'fullCylinderDate' => $postData['fullCylinderDate'] ?? '', 'emptyCylinderDate' => $postData['emptyCylinderDate'] ?? '', 'invoiceNo' => $postData['invoiceNo'] ?? '', 'cylinderNo' => $cylinder['cylinderNo'], 'grossWeight' => $cylinder['grossWeight'], 'tareWeight' => $cylinder['tareWeight'] ?? '', 'netWeight' => $cylinder['netWeight'] ?? '', 'actualWeight' => $cylinder['actualWeight'], 'shortage' => $cylinder['shortage'] ?? '', 'gas_cylinder_status' => 'gas_pending' ]; $inserts[] = $cylinderData; } } if (!empty($updates)) { $this->gasShortage_model->updateBatch($updates, 'id'); } if (!empty($inserts)) { $this->gasShortage_model->insertBatch($inserts); } return $this->response->setJSON([ 'status' => 'success', 'message' => 'Gas shortage details processed successfully.' ]); } catch (\Throwable $th) { // Log the error for debugging log_message('error', 'Gas Shortage Update Error: ' . $th->getMessage()); return $this->response->setJSON([ 'status' => 'error', 'message' => 'An unexpected error occurred while processing gas shortage details.', 'error' => $th->getMessage() ]); } } public function gasCylindersByIgr(){ $IGRNO = $this->request->getPost('IGRNO'); $gasMaterialCodes = $this->rawMaterialDetails_model->getAllGasMaterialCode(); $gasMaterialCodes = array_column($gasMaterialCodes,'MaterialCode'); $cylinderDetails = $this->inwardgateregister_model->gasCylindersByIgr($IGRNO , $gasMaterialCodes); $response = [ 'status' => 'success', 'message' => 'Gas cylinders retrieved successfully.', 'data' => $cylinderDetails ]; return $this->response->setJSON($response); } /* ********************************************************* sec_gas_shortage_ends ************************************************************** */ }