HEX
Server: Apache/2.4.41 (Amazon) OpenSSL/1.0.2k-fips PHP/5.6.40
System: Linux ip-172-31-40-18 4.14.146-93.123.amzn1.x86_64 #1 SMP Tue Sep 24 00:45:23 UTC 2019 x86_64
User: apache (48)
PHP: 5.6.40
Disabled: NONE
Upload Files
File: /var/www/html/nt/application/controllers/admin/Main.php
<?php
defined('BASEPATH') or exit('No direct script access allowed');

// require 'vendor/autoload.php';

// use PhpOffice\PhpSpreadsheet\Spreadsheet;
// use PhpOffice\PhpSpreadsheet\Reader\Xls;

require_once APPPATH . "third_party/PHPExcel.php";
require_once APPPATH . "third_party/PHPExcel/IOFactory.php";

class Main extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model(array('admin/mmain', 'admin/muser', 'admin/mcar', 'mcommon'));
		$this->load->helper(array('sms', 'email'));
	}


	public function index()
	{
		$post_array = $this->input->post();
		$data = array();
		$data = array('menu_id' => 7);
		$data['applications'] = array();
		$where = array();

		$data['start_date'] = $this->input->post('start_date');
		$data['end_date'] = $this->input->post('end_date');
		$data['industrial_park_id'] = $this->input->post('industrial_park_id');

		if ($this->input->post()) {
			if ($this->input->post('start_date')) {
				$where['DATE(a.created_at) >='] = date('Y-m-d', strtotime($this->input->post('start_date')));
			}
			if ($this->input->post('end_date')) {
				$where['DATE(a.created_at) <='] = date('Y-m-d', strtotime($this->input->post('end_date')));
			}
			if ($this->input->post('industrial_park_id') != 0) {
				$where['a.industrial_park_id = '] = $this->input->post('industrial_park_id');
			}
		}

		$where['pi.status = '] = 'Captured';
		//echo "<pre>"; print_r($where); die;

		$data['indParks'] = $this->mcommon->getDetailsOrder('industrial_park_master', array('is_active' => 1), 'park_name', 'ASC');

		if (check_user_permission($data['menu_id'], 'delete_flag')) {
			$applications = $this->session->admin['role_id'] == ROLE_SUPERADMIN ? $this->mapplication->get_application($where) : $this->mapplication->get_application(array('a.project_id' => ''));
		}

		if (!empty($applications)) {
			$data['applications'] = $applications;
		}

		//echo '<pre>'; print_r($data['applications']);die;
		$data['content'] = 'admin/application/list';
		$this->load->view('admin/layouts/index', $data);
	}

	public function upload_daily_statement()
	{
		$data['content'] = 'admin/upload_daily_statement/add';
		$this->load->view('admin/layouts/index', $data);
	}

	public function transaction_file_upload()
	{
		$this->load->library('form_validation');
		$file_tracking_id = time();
		$data = array();
		if ($this->input->post()) {
			// $this->form_validation->set_rules('transaction_file','Transaction File','trim|required');
			$this->form_validation->set_rules('file_type', 'File type', 'required');

			if ($this->form_validation->run() == FALSE) {
				$this->session->set_flashdata('error', validation_errors());
				redirect('upload_daily_statement');
			} else {
				// $data['transaction_file'] = $this->input->post('transaction_file');
				$file_type = $this->input->post('file_type');
				$data['file_type'] = $file_type;
				$data['uploaded_by'] = $this->session->admin['user_id'];
				$data['uploaded_ts'] = date('Y-m-d H:i:s');

				if (!empty($_FILES['transaction_file']['name'])) {
					$config['upload_path'] = './public/transaction_files';
					$config['allowed_types'] = '*';
					$config['file_name'] = $_FILES["transaction_file"]['name'];
					$this->load->library('upload', $config);
					$this->upload->initialize($config);
					if ($this->upload->do_upload('transaction_file')) {
						$file_name = $this->upload->data()['file_name'];
						$file_path = $this->upload->data()['full_path'];
						$data['file_name'] = $file_name;
						$data['file_path'] = $file_path;
						$data['file_tracking_id'] = $file_tracking_id;

						if ($file_type == "a") {
							$fileExtension = pathinfo($file_path, PATHINFO_EXTENSION);
							if (strtolower($fileExtension) !== 'xls') {
								$this->session->set_flashdata('error', 'Invalid file type! Please upload an XLS file for Black & White EFTPOS');
								redirect('upload_daily_statement');
								exit;
							}
							$xlsData = $this->readXls($file_path);
							if ($xlsData[0][2] !== 'EFTPOS Statement Summary for Period') {
								$this->session->set_flashdata('error', 'Invalid file! This is not a proper file for Black & White EFTPOS. Please recheck your file and try again.');
								redirect('upload_daily_statement');
								exit;
							}

							$fileDateLine = explode(" ", $xlsData[1][2]);
							$fileDate = explode("/", $fileDateLine[3] ? $fileDateLine[3] : $fileDateLine[4]);
							$data['file_date'] = $fileDate[2] . '-' . $fileDate[1] . '-' . $fileDate[0];
							
							$existingFile = $this->mmain->checkTransactionLogAlreadyExists($data);
							if ($existingFile) {
								$this->session->set_flashdata('error', 'File already uploaded for this date. Please upload another file.');
								redirect('upload_daily_statement');
								exit;
							}

							$loop_data = array_slice($xlsData, 7);
							// echo "<pre>"; print_r($loop_data); die;
							$this->insertXlsDataAType($loop_data, $file_type, $file_tracking_id);
						}

						if ($file_type == "b") {
							$csvData = $this->read_csv($file_path);
							if ($csvData[0][0] !== 'Process Date') {
								$this->session->set_flashdata('error', 'Invalid file! This is not a proper file for Cab Charge EFTPOS. Please recheck your file and try again.');
								redirect('upload_daily_statement');
								exit;
							}

							$fileDate = explode("/", $csvData[0][2]);
							$data['file_date'] = $fileDate[2] . '-' . $fileDate[1] . '-' . $fileDate[0];
							$existingFile = $this->mmain->checkTransactionLogAlreadyExists($data);
							if ($existingFile) {
								$this->session->set_flashdata('error', 'File already uploaded for this date. Please upload another file.');
								redirect('upload_daily_statement');
								exit;
							}

							$loop_data = array_slice($csvData, 4);
							$this->insertCsvDataBType($loop_data, $file_type, $file_tracking_id);
						}

						if ($file_type == "c") {
							$csvData = $this->read_csv($file_path);
							if ($csvData[0][0] !== 'Taxi_No') {
								$this->session->set_flashdata('error', 'Invalid file! This is not a proper file for CPVV EFTPOS. Please recheck your file and try again.');
								redirect('upload_daily_statement');
								exit;
							}

							$fileDate = explode("/", $csvData[1][4]);
							$data['file_date'] = $fileDate[2] . '-' . $fileDate[1] . '-' . $fileDate[0];
							$existingFile = $this->mmain->checkTransactionLogAlreadyExists($data);
							if ($existingFile) {
								$this->session->set_flashdata('error', 'File already uploaded for this date. Please upload another file.');
								redirect('upload_daily_statement');
								exit;
							}

							$loop_data = array_slice($csvData, 4);
							// echo "<pre>"; print_r($loop_data); die;
							$this->insertCsvDataCType($loop_data, $file_type, $file_tracking_id);
						}
						// echo "<pre>"; print_r($loop_data); die;
					} else {
						$msg = $this->upload->display_errors();
						$this->session->set_flashdata('error', $msg);
						redirect('upload_daily_statement');
					}
				} else {
					$this->session->set_flashdata('error', 'Please select a file to upload.');
					redirect('upload_daily_statement');
				}

				if ($data['file_path'] != "") {
					$result = $this->mmain->saveTransactionLog($data);
				}


				if ($result) {
					$this->session->set_flashdata('success', 'All transactions recorded successfully.');
					redirect('upload_daily_statement');
				} else {
					$this->session->set_flashdata('error', 'Something is Wrong. Try Again.');
					redirect('upload_daily_statement');
				}
			}
		}
	}

	private function read_csv($filePath)
	{
		// Open the file for reading
		$file = fopen($filePath, 'r');

		$csvData = [];

		// Loop through each line in the file
		while (($line = fgetcsv($file)) !== FALSE) {
			$csvData[] = $line;
		}

		// Close the file
		fclose($file);

		return $csvData;
	}
	public function readXls($filePath)
	{
		try {
			if (!file_exists($filePath)) {
				die('File not found.');
			}
			$objPHPExcel = PHPExcel_IOFactory::load($filePath);
			$worksheet = $objPHPExcel->getActiveSheet();

			$highestRow = $worksheet->getHighestRow(); // e.g. 10
        	$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
        	$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 6

			// Read data from the worksheet
			$data = [];
			for ($row = 1; $row <= $highestRow; ++$row) {
				$rowData = [];
				for ($col = 0; $col < $highestColumnIndex; ++$col) {
					$cell = $worksheet->getCellByColumnAndRow($col, $row);
					$rowData[] = $cell->getValue();
				}
				$data[] = $rowData;
			}
			// echo "<pre>"; print_r($data); die;
			return $data;
		} catch (\Throwable $th) {
			echo "Error: " . $th->getMessage();
			die;
		}
	}
	// public function readXls($filePath)
	// {
	// 	try {
	// 		if (!file_exists($filePath)) {
	// 			die('File not found.');
	// 		}
	// 		$reader = new Xls();
	// 		// echo "<pre>"; print_r($reader); die;
	// 		$spreadsheet = $reader->load($filePath);
	// 		// Get the first worksheet
	// 		$worksheet = $spreadsheet->getActiveSheet();

	// 		// Get the highest row and column numbers referenced in the worksheet
	// 		$highestRow = $worksheet->getHighestRow(); // e.g. 10
	// 		$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
	// 		$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5

	// 		// Read data from the worksheet
	// 		$data = [];
	// 		for ($row = 1; $row <= $highestRow; ++$row) {
	// 			$rowData = [];
	// 			for ($col = 1; $col <= $highestColumnIndex; ++$col) {
	// 				$cell = $worksheet->getCellByColumnAndRow($col, $row);
	// 				$rowData[] = $cell->getValue();
	// 			}
	// 			$data[] = $rowData;
	// 		}
	// 		return $data;
	// 	} catch (\Throwable $th) {
	// 		echo "Error: " . $th->getMessage();
	// 		die;
	// 	}
	// }
	private function insertXlsDataAType($dataToInsert, $file_type, $file_tracking_id)
	{
		$batch_no = '';
		foreach ($dataToInsert as $row) {
			if ($row[1] != "") {
				$batch_no = $row[1];
				$tripDate = explode("/", $row[3]);
				$data = [
					'file_type' => $file_type,
					'taxi_number' => $row[0],
					'batch_no' => $row[1],
					'transaction_type' => $row[2],
					'trip_date' => $tripDate[2] . '-' . $tripDate[1] . '-' . trim($tripDate[0]), // Convert date to Y-m-d format
					'trip_time' => $row[4],
					'rrn' => $row[5],
					'terminal_id' => $row[6],
					'driver_id' => $row[7],
					'amount' => $row[8],
					'balance' => $row[8],
					'commission' => $row[11] ?? 0,
					'subsidy' => $row[12] ?? 0,
					'posting_date' => '',
					'file_referance' => '',
					'uploaded_by' => $this->session->admin['user_id'],
					'uploaded_ts' => date('Y-m-d H:i:s'),
					'file_tracking_id' => $file_tracking_id
				];

				// echo "<pre>"; print_r($data); die;

				$existingCar = $this->mcar->checkExistingCar($data);
				if (!$existingCar) {
					$carData = [
						'taxi_number' => $data['taxi_number'],
						'terminal' => isset($data['terminal_id']) ? $data['terminal_id'] : '',
						'owner_name' => '',
						'password' => '',
						'remarks' => '',
						'status' => 1,
					];
					$this->mcar->saveCarData($carData);
				}
				$this->mmain->saveTransaction($data);
			} else {
				if($row[1] == "" && $row[7] == "Batch Total"){
					$existing_batch_reference = $this->mmain->check_existing_batch_reference($batch_no);
					if (!$existing_batch_reference) {
						$posting_date = explode("/", $row[13]);
						$batch_reference = [
							'batch_no' => $batch_no,
							'posting_date' => $posting_date[2] . '-' . $posting_date[1] . '-' . trim($posting_date[0]),
							'reference' => $row[14],
						];
						$this->mmain->save_batch_reference($batch_reference);
					}
				}
			}
		}
	}
	private function insertCsvDataBType($dataToInsert, $file_type, $file_tracking_id)
	{
		foreach ($dataToInsert as $row) {
			if ($row[0] == 'D') {
				$amount = 0;
				if ($row[8] == "eTicket") {
					$amount = $row[15];
				} elseif ($row[8] == "Charge") {
					$amount = $row[12];
				} elseif ($row[8] == "Eftpos") {
					$amount = $row[13];
				} elseif ($row[8] == "iHail") {
					$amount = $row[14];
				} else {
					$amount = 0;
				}
				$tripDate = explode("/", $row[6]);
				$data = [
					'file_type' => $file_type,
					'taxi_number' => $row[2],
					'batch_no' => $row[2],
					'transaction_type' => $row[8],
					'trip_date' => $tripDate[2] . '-' . $tripDate[1] . '-' . $tripDate[0], // Convert date to Y-m-d format
					'trip_time' => $row[7],
					'rrn' => $row[5],
					'terminal_id' => $row[3],
					'driver_id' => $row[4],
					'amount' => $amount,
					'balance' => $amount,
					'commission' => '',
					'subsidy' => '',
					'posting_date' => '',
					'file_referance' => '',
					'uploaded_by' => $this->session->admin['user_id'],
					'uploaded_ts' => date('Y-m-d H:i:s'),
					'file_tracking_id' => $file_tracking_id
				];

				// echo "<pre>"; print_r($data); die;

				$existingCar = $this->mcar->checkExistingCar($data);
				if (!$existingCar) {
					$carData = [
						'taxi_number' => $data['taxi_number'],
						'terminal' => isset($data['terminal_id']) ? $data['terminal_id'] : '',
						'owner_name' => '',
						'password' => '',
						'remarks' => '',
						'status' => 1,
					];
					$this->mcar->saveCarData($carData);
				}
				$this->mmain->saveTransaction($data);
			}
		}
	}

	private function insertCsvDataCType($dataToInsert, $file_type, $file_tracking_id)
	{
		foreach ($dataToInsert as $row) {

			$tripDate = explode("/", $row[4]);
			$amount = explode("$", $row[1]);
			$subsidy = explode("$", $row[2]);
			$data = [
				'file_type' => $file_type,
				'taxi_number' => $row[0],
				'batch_no' => "",
				'transaction_type' => $row[3],
				'trip_date' => $tripDate[2] . '-' . $tripDate[1] . '-' . $tripDate[0], // Convert date to Y-m-d format
				'trip_time' => "",
				'rrn' => "",
				'terminal_id' => "",
				'driver_id' => "",
				'amount' => $amount[1],
				'balance' => $amount[1],
				'commission' => '',
				'subsidy' => $subsidy[1],
				'posting_date' => '',
				'file_referance' => '',
				'uploaded_by' => $this->session->admin['user_id'],
				'uploaded_ts' => date('Y-m-d H:i:s'),
				'file_tracking_id' => $file_tracking_id
			];

			// echo "<pre>"; print_r($data); die;

			$existingCar = $this->mcar->checkExistingCar($data);
			if (!$existingCar) {
				$carData = [
					'taxi_number' => $data['taxi_number'],
					'terminal' => isset($data['terminal_id']) ? $data['terminal_id'] : '',
					'owner_name' => '',
					'password' => '',
					'remarks' => '',
					'status' => 1,
				];
				$this->mcar->saveCarData($carData);
			}
			$this->mmain->saveTransaction($data);
		}
	}

	public function downloadFile($filename) {
        // Specify the full path to your file directory
        $filePath = 'public/transaction_files/' . $filename;

        // Check if the file exists
        if (file_exists($filePath)) {
            // Set the headers to force download
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
            header('Content-Length: ' . filesize($filePath));

            // Read the file and output its content
            readfile($filePath);
            exit;
        } else {
            // File doesn't exist, show error or redirect
            show_error('File not found.', 404);
        }
    }



	public function uploaded_transactional_file_log()
	{
		if ($this->input->post()) {
			// echo "<pre>"; print_r($this->input->post()); die;
			$data['transactionLogs'] = $this->mmain->searchTransactionLogData($this->input->post());
			$data['searchParam'] = $this->input->post();
		} else {
			$data['transactionLogs'] = $this->mmain->getTransactionLogData();
			$data['searchParam'] = array();
		}
		// echo "<pre>"; print_r($data['transactionLogs']); die;
		$data['content'] = 'admin/uploaded_transactional_file_log/list';
		$this->load->view('admin/layouts/index', $data);
	}

	public function transaction_list()
	{
		if ($this->input->post()) {
			$data['searchParam'] = $this->input->post();
		} else {
			$data['searchParam'] = array();
		}
		$data['transactions'] = $this->mmain->getTransactionsData($data['searchParam']);
		// echo "<pre>"; print_r($data['transactions']); die;
		$data['content'] = 'admin/transaction_list/list';
		$this->load->view('admin/layouts/index', $data);
	}

	public function transaction_search_report()
	{
		$data['uniqueTaxiNumbers'] = $this->mmain->getUniqueTaxiNumbers();
		$data['uniqueTerminals'] = $this->mmain->getUniqueTerminals();
		$data['uniqueDriverIds'] = $this->mmain->getUniqueDriverIds();

		if ($this->input->post()) {
			$data['transactions'] = $this->mmain->searchTransactions($this->input->post());
			$data['searchParam'] = $this->input->post();
		} else {
			$data['transactions'] = $this->mmain->getAllTransactions();
			$data['searchParam'] = array();
		}

		// echo "<pre>"; print_r($data['searchParam']); die;
		$data['content'] = 'admin/transaction_search_report/list';
		$this->load->view('admin/layouts/index', $data);
	}

	public function negative_transaction_list()
	{
		if ($this->input->post()) {
			$data['negativeTransactions'] = $this->mmain->searchNegativeTransactions($this->input->post());
			$data['searchParam'] = $this->input->post();
		} else {
			$data['negativeTransactions'] = $this->mmain->getNegativeTransactionsData();
			$data['searchParam'] = array();
		}
		$data['content'] = 'admin/negative_transaction_list/list';
		$this->load->view('admin/layouts/index', $data);
	}
	public function settle_transaction_from_dashboard()
	{
		$transactionData = $this->mmain->getTransactionDataByTransactionId($this->input->post("transaction_id_to_settle"));
		$update = $this->mcommon->update('transaction', array('transaction_id' => $this->input->post('transaction_id_to_settle')), array('balance' => $this->input->post("settlement_type") == 0 ? $transactionData['balance'] - $this->input->post("full_amount") : $transactionData['balance'] + $this->input->post("partial_amount")));
		// echo "<pre>"; print_r( $transactionData["balance"]); die;
		// echo "<pre>"; print_r($this->input->post("settlement_type") == 0 ? $transactionData['balance'] - $this->input->post("full_amount") : $transactionData['balance'] + $this->input->post("partial_amount")); die;

		$data = [
			'transaction_id' => $this->input->post("transaction_id_to_settle"),
			'remarks' => $this->input->post("remarks"),
			'settled_amount' => $this->input->post("settlement_type") == 0 ? $this->input->post("full_amount") * -1 : $this->input->post("partial_amount"),
			'settlement_type' => $this->input->post("settlement_type"),
			'settled_by' => $this->session->admin['user_id'],
			'settled_ts' => date('Y-m-d H:i:s'),
		];

		$settled_transaction_id = $this->mmain->saveSettledTransactionData($data);
		// echo $car_id; die;
		if ($settled_transaction_id) {
			$this->session->set_flashdata('success', 'Record saved successfully!');
		} else {
			$this->session->set_flashdata('error', 'There was an error in saving the data. Please try again.');
		}

		redirect('dashboard');
	}

	public function settled_transaction_history()
	{
		if ($this->input->post()) {
			$data['settledTransactions'] = $this->mmain->getSettledTransactionsData($this->input->post());
			$data['searchParam'] = $this->input->post();
		} else {
			$data['settledTransactions'] = $this->mmain->getSettledTransactionsData(array());
			$data['searchParam'] = array();
		}
		// echo "<pre>"; print_r($data['settledTransactions']); die;
		$data['content'] = 'admin/settled_transaction_history/list';
		$this->load->view('admin/layouts/index', $data);
	}


	public function detailedView($application_id)
	{
		$data = array();

		$data['application_id'] = decode_url($application_id);

		if ($data['application_id'] > 0) {
			$data['application_detail'] = $this->mapplication->get_application_detail(array('a.application_id' => $data['application_id']));
			$data['family_income_criteria'] = $this->mapplication->getFamilyIncomeCategory($data['application_detail']['applicant_user_id']);
			$data['pvData'] = $this->mcommon->getDetails('application_physical_verification_dtl', array('application_id' => $data['application_id']));
			$data['coApplicantDetail'] = $this->mcommon->getRow('applicant', array('applicant_id' => $data['application_detail']['second_applicant_id']));
			$data['coApplicantStateName'] = $this->mcommon->getRow('state_master', array('state_id' => $data['application_detail']['permanent_state_id']));

			$data['content'] = 'admin/application_list/edit';
			$this->load->view('admin/layouts/index', $data);
		} else {
			redirect(base_url('dashboard'));
		}
	}
	public function print_receipt($application_id)
	{
		$data = array();
		$data['application_detail'] = array();
		$data['coApplicantDetail'] = array();
		$data['coApplicantStateName'] = array();

		$data['application_id'] = decode_url($application_id);

		if ($data['application_id'] > 0) {
			$data['application_detail'] = $this->mapplication->get_application_detail(array('a.application_id' => $data['application_id']));
			$data['family_income_criteria'] = $this->mapplication->getFamilyIncomeCategory($data['application_detail']['applicant_user_id']);
			$data['pvData'] = $this->mcommon->getDetails('application_physical_verification_dtl', array('application_id' => $data['application_id']));
			if ($data['application_detail']['second_applicant_id'] > 0) {
				$data['coApplicantDetail'] = $this->mcommon->getRow('applicant', array('applicant_id' => $data['application_detail']['second_applicant_id']));
				$data['coApplicantStateName'] = $this->mcommon->getRow('state_master', array('state_id' => $data['application_detail']['permanent_state_id']));
			}

			$this->load->view('admin/application_list/print', $data);
		} else {
			redirect(base_url('dashboard'));
		}
	}
	public function uploadImages($fieldName, $folder_name)
	{

		$config['upload_path']          = './public/' . $folder_name;
		$config['allowed_types']        = '*';
		$config['max_size']             = 5000;
		$config['encrypt_name'] = TRUE;
		//$config['max_width']            = 1024;
		//$config['max_height']           = 768;

		$this->load->library('upload', $config);

		$img_ret = array();

		if ($this->upload->do_upload($fieldName)) {
			$upload_data = $this->upload->data();
			$image_path = $upload_data['file_name'];

			$img_ret = array('status' => true, 'img_path' => $image_path);
		} else {
			$img_ret = array('status' => false, 'error' => $this->upload->display_errors());
		}

		return $img_ret;
	}
}