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

class Challanctrl extends CI_Controller
{
	public $Challanmdl;
	public $excel;
	public $pagination;
	public function __construct()
	{
		parent::__construct();

		$this->load->model('challan/Challanmdl');
		$this->load->library('session');
		$this->load->library('upload');
		$this->load->library('pagination');
		$this->config->load('extra');
		$this->load->library('db_operations');
	}


/*challan master*/

	public function challan_master()
	{
		if(sessionExist())
		{
			if($_GET['action'] == 'view')
			{
				$config 				= array();
				$config 				= $this->config->item('pagination');
				$config['total_rows'] 	= $this->Challanmdl->get_all_challan_data_cnt();
				$config['base_url'] 	= base_url("challan/challanctrl/challan_master?search=true");

				foreach ($_GET as $key => $value)
				{
					if($key != 'search' && $key != 'offset')
					{
						$config['base_url'] .= "&" . $key . "=" .$value;
					}
				}

				$offset = (!empty($_GET['offset'])) ? $_GET['offset'] : 0;
				$this->pagination->initialize($config);

				$record['count'] 		= $offset;
				$record['total_rows'] 	= $config['total_rows'];
				$record['role'] 		= $this->config->item('role');
				$record['data']			= $this->Challanmdl->get_all_challan_data($config['per_page'],$offset);
				$this->load->view('pages/challan/challan_master', $record);
			}
			elseif ($_GET['action'] == 'add')
			{
				$record = $this->Challanmdl->get_challan_data_for_add();
				// echo "<pre>"; print_r($record); exit;
				$this->load->view('pages/challan/challan_form', $record);
			}
			elseif($_GET['action'] == 'edit')
			{
				$cm_id = encrypt_decrypt("decrypt", $_GET['id'], SECRET_KEY);
				$record = $this->Challanmdl->get_challan_data_for_edit($cm_id);
				// echo "<pre>"; print_r($record); exit;
				$this->load->view('pages/challan/challan_form', $record);
			}
			elseif($_GET['action'] == 'print')
			{
				$cm_id = encrypt_decrypt("decrypt", $_GET['id'], SECRET_KEY);
				$record = $this->Challanmdl->get_challan_data_for_edit($cm_id);
				// echo "<pre>"; print_r($record); exit;
				$this->load->view('pdfs/challan/challan_print', $record);
			}
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}

	public function get_diamond_data($dm_id)
	{
		if(sessionExist())
		{
			echo json_encode($this->Challanmdl->get_diamond_data($dm_id));
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}
	public function challan_insert_update($cm_id)
	{
		if (sessionExist())
		{
			$form_data = $this->input->post();

			// echo "<pre>";print_r($cm_id);
			// echo "<pre>";print_r($form_data);exit();

			/*sale master data array*/
			$challan_data = array();

			$challan_data['cm_entry_no'] 		= $form_data['cm_entry_no'];
			$challan_data['cm_entry_date'] 		= date('Y-m-d H:i:s',strtotime($form_data['cm_entry_date']));
			$challan_data['cm_cust_id'] 		= $form_data['cm_cust_id'];
			$challan_data['cm_broker_id'] 		= $form_data['cm_broker_id'];
			$challan_data['cm_through'] 		= $form_data['cm_through'];
			$challan_data['cm_notes'] 			= $form_data['cm_notes'];
			$challan_data['cm_total_qty'] 		= $form_data['cm_total_qty'];
			$challan_data['cm_total_amt'] 		= $form_data['cm_total_amt'];


			if ($cm_id == 0)
			{
				$this->db->trans_begin();
				/*check duplicate purchase entry no*/
				$cnt = $this->db_operations->get_cnt('challan_master', array('cm_entry_no' => $form_data['cm_entry_no'], 'cm_fin_month' => $_SESSION['fin_month']));
				if ($cnt != 0)
				{
					/*$challan_data['cm_entry_no'] = $this->db_operations->get_fin_year_max_id('challan_master', 'cm_entry_no', 'cm_fin_year');*/
					$challan_data['cm_entry_no'] = $this->db_operations->get_fin_year_max_id('challan_master', 'cm_entry_no', 'cm_fin_month');
					// $response['resp'] = 2;
					// echo json_encode($response);
				}
				$challan_data['cm_fin_year']		= $_SESSION['fin_year'];
				$challan_data['cm_fin_month']		= $_SESSION['fin_month'];
				$challan_data['cm_userid'] 			= $_SESSION['user_id'];
				$challan_data['cm_create_date'] 	= date('Y-m-d H:i:s');
				$challan_data['cm_update_userid'] 	= $_SESSION['user_id'];
				$challan_data['cm_update_date'] 	= date('Y-m-d H:i:s');

				/*insert data to purchase_order_master table*/
				$cm_id = $this->db_operations->data_insert('challan_master', $challan_data);

				if (!empty($cm_id))
				{
					/*insert data to purchase_trans table*/
					$ct_result 	= $this->insert_update_challan_trans($form_data, $cm_id);
					// echo "<pre>"; print_r($ct_result); exit;
				}
				// echo "<pre>"; print_r($this->db->trans_status());exit;

				if ($this->db->trans_status() === FALSE) {
				    $this->db->trans_rollback();
				    $response['resp'] = 0;
					echo json_encode($response);

				} else {
				    $this->db->trans_commit();
				    $response['resp'] = 1;
				    $response['last_id'] = encrypt_decrypt("encrypt", $cm_id, SECRET_KEY);
					echo json_encode($response);
				}
			}
			else
			{
				$this->db->trans_begin();
				/*update code*/
				$cnt = $this->db_operations->get_cnt('challan_master', array('cm_id !=' => $cm_id,'cm_entry_no' => $form_data['cm_entry_no'], 'cm_fin_month' => $_SESSION['fin_month']));

				if ($cnt != 0)
				{
					$response['resp'] = 2;
					echo json_encode($response);
				}
				else
				{
					$challan_data['cm_update_userid'] 	= $_SESSION['user_id'];
					$challan_data['cm_update_date'] 	= date('Y-m-d H:i:s');

					/*update data to sale_master table*/
					$result = $this->db_operations->data_update('challan_master', $challan_data, 'cm_id', $cm_id);

					if (!empty($result))
					{
						/*update data to sale_master table*/
						$ct_result 	= $this->insert_update_challan_trans($form_data, $cm_id);
					}

					if ($this->db->trans_status() === FALSE) {
					    $this->db->trans_rollback();
					    // echo 0;
					    $response['resp'] = 0;
						echo json_encode($response);
					} else {
					    $this->db->trans_commit();
						// echo 1;
						$response['resp'] = 1;
					 	$response['last_id'] = encrypt_decrypt("encrypt", $cm_id, SECRET_KEY);
						echo json_encode($response);
					}
				}
			}
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}
	public function insert_update_challan_trans($form_data, $cm_id)
	{
		// 0 = not avialable
		// 1 = avialable

		$challan_trans_data = $this->db_operations->get_record('challan_trans',array('ct_cm_id' =>$cm_id)); // get all db record first and all form data and match who is missing and those data delete by system
		// echo "<pre>"; print_r($challan_trans_data);
		// echo "<pre>"; print_r($form_data); exit();

		foreach ($challan_trans_data as $key => $value)
		{
			if (!in_array($value['ct_id'], $form_data['ct_id']))
			{
				/*delete transactions*/
				$crt_data =  $this->Challanmdl->get_latest_crt_id($value['ct_dm_id']);
				if(!empty($crt_data))
				{
					$crt_id = $crt_data[0]['crt_id'];
					$this->db_operations->data_update('challan_return_trans',['crt_delete'=>1],'crt_id',$crt_id);
				}
				else
				{
					$crt_id = 0;
				}


				$diamond_data_db 							= $this->Challanmdl->get_challan_return_data_by_id($value['ct_dm_id']);
				if(empty($diamond_data_db))
				{
					$diamond_data_db 						= $this->db_operations->get_record('diamond_master', ['dm_id'=>$value['ct_dm_id']]);
					$diamond_data_delete['dm_update_id'] 	= $diamond_data_db[0]['dm_user_id'];
					$diamond_data_delete['dm_date_update'] 	= $diamond_data_db[0]['dm_date_create'];
					$diamond_data_delete['dm_status'] 		= 0;


					$diamond_data_delete['dm_ct_id'] 		= 0;
					$diamond_data_delete['dm_crt_id'] 		= $crt_id;

				}
				else
				{
					$diamond_data_delete['dm_update_id'] 	= $diamond_data_db[0]['crm_update_userid'];
					$diamond_data_delete['dm_date_update'] 	= $diamond_data_db[0]['crm_update_date'];
					$diamond_data_delete['dm_status'] 		= 4;


					$diamond_data_delete['dm_ct_id'] 		= 0;
					$diamond_data_delete['dm_crt_id'] 		= $crt_id;
				}



				$this->db_operations->data_update('diamond_master',$diamond_data_delete,'dm_id',$value['ct_dm_id']);
				$del_res = $this->db_operations->delete_record('challan_trans',array('ct_id' =>$value['ct_id']));
			}
		}
		$bank_rate = 0;
		$bank_rate_data = $this->db_operations->get_record('bank_rate_master', ['bank_rate_date' => date('Y-m-d', strtotime($form_data['cm_entry_date']))]);
		// echo "<pre>"; print_r($bank_rate_data); exit();
		if (!empty($bank_rate_data))
		{
			$bank_rate = $bank_rate_data[0]['bank_rate'];
		}

		foreach ($form_data['ct_id'] as $key => $value)
		{
			/*purchase transaction data*/
			$challan_trans_data = array();

			$challan_trans_data['ct_cm_id'] 		  	= $cm_id;
			$challan_trans_data['ct_dm_id'] 	 	  	= $form_data['ct_dm_id'][$key];
			$challan_trans_data['ct_dm_code'] 	 	  	= $this->db_operations->get_record('diamond_master', ['dm_id'=>$challan_trans_data['ct_dm_id']])[0]['dm_code'];
			$challan_trans_data['ct_dm_sh'] 	 	  	= $form_data['ct_dm_sh'][$key];
			$challan_trans_data['ct_dm_wt'] 	 	  	= $form_data['ct_dm_wt'][$key];
			$challan_trans_data['ct_dm_col'] 	 	  	= $form_data['ct_dm_col'][$key];
			$challan_trans_data['ct_dm_cla'] 	 	  	= $form_data['ct_dm_cla'][$key];
			$challan_trans_data['ct_dm_cut'] 	 	  	= $form_data['ct_dm_cut'][$key];
			$challan_trans_data['ct_dm_pol'] 	 	  	= $form_data['ct_dm_pol'][$key];
			$challan_trans_data['ct_dm_sym'] 	 	  	= $form_data['ct_dm_sym'][$key];
			$challan_trans_data['ct_dm_fl'] 	 	  	= $form_data['ct_dm_fl'][$key];
			$challan_trans_data['ct_dm_lab'] 	 	  	= $form_data['ct_dm_lab'][$key];
			$challan_trans_data['ct_dm_disc'] 	 	  	= $form_data['ct_dm_disc'][$key];
			$challan_trans_data['ct_dollar'] 	 	  	= isset($form_data['ct_dollar'][$key]) ? $form_data['ct_dollar'][$key] : "";
			$challan_trans_data['ct_dm_rap'] 	 	  	= isset($form_data['ct_dm_rap'][$key]) ? $form_data['ct_dm_rap'][$key] : "";
			$challan_trans_data['ct_dm_cert'] 	 	  	= isset($form_data['ct_dm_cert'][$key]) ? $form_data['ct_dm_cert'][$key] : "";

			if(strtoupper($challan_trans_data['ct_dm_lab']) == 'GIA')
            {
                $challan_trans_data['ct_sub_total'] = $challan_trans_data['ct_dm_wt'] * $challan_trans_data['ct_dm_rap'];


                if(!empty($challan_trans_data['ct_dm_disc']))
               	{
               		$disc = explode('-', $challan_trans_data['ct_dm_disc']);
                    if(empty($disc[0]))
                    {
                        $disc = $disc[1];
                    }
                    else
                    {
                        $disc = $disc[0];
                    }
               	}
               	else
               	{
               		$disc = 0;
               	}

                $challan_trans_data['ct_disc_amt'] = ($challan_trans_data['ct_sub_total'] * $disc)/100;
                $challan_trans_data['ct_dollar'] = $challan_trans_data['ct_sub_total'] - $challan_trans_data['ct_disc_amt'];

                $challan_trans_data['ct_bank_rate'] = $bank_rate;
                $challan_trans_data['ct_total_amt'] = $challan_trans_data['ct_dollar'] * $bank_rate;
                $challan_trans_data['ct_ppc'] = $challan_trans_data['ct_dollar'] / $challan_trans_data['ct_dm_wt'];


            }
            elseif(strtoupper($challan_trans_data['ct_dm_lab']) == 'IGI' || strtoupper($challan_trans_data['ct_dm_lab']) == 'HRD')
            {
                $challan_trans_data['ct_sub_total'] = $challan_trans_data['ct_dm_wt'] * $challan_trans_data['ct_dm_rap'];

                if(!empty($challan_trans_data['ct_dm_disc']))
               	{
               		$disc = explode('-', $challan_trans_data['ct_dm_disc']);
                    if(empty($disc[0]))
                    {
                        $disc = $disc[1];
                    }
                    else
                    {
                        $disc = $disc[0];
                    }
               	}
               	else
               	{
               		$disc = 0;
               	}

                $disc_amt = ($challan_trans_data['ct_sub_total'] * $disc)/100;
                $challan_trans_data['ct_bank_rate'] = $bank_rate;
                $total_dollar = $challan_trans_data['ct_sub_total'] - $disc_amt;

                $challan_trans_data['ct_total_amt'] = $total_dollar * $bank_rate;
                $challan_trans_data['ct_disc_amt'] = ($total_dollar * 2) / 100;
                $challan_trans_data['ct_dollar'] = $total_dollar - $challan_trans_data['ct_disc_amt'];
                $challan_trans_data['ct_ppc'] = $challan_trans_data['ct_dollar'] / $challan_trans_data['ct_dm_wt'];
            }
            else
            {
            	$challan_trans_data['ct_sub_total'] = $challan_trans_data['ct_dm_wt'] * $challan_trans_data['ct_dm_rap'];

                if(!empty($challan_trans_data['ct_dm_disc']))
               	{
               		$disc = explode('-', $challan_trans_data['ct_dm_disc']);
                    if(empty($disc[0]))
                    {
                        $disc = $disc[1];
                    }
                    else
                    {
                        $disc = $disc[0];
                    }
               	}
               	else
               	{
               		$disc = 0;
               	}

                $challan_trans_data['ct_disc_amt'] = ($challan_trans_data['ct_sub_total'] * $disc)/100;
                $challan_trans_data['ct_dollar'] = $challan_trans_data['ct_sub_total'] - $challan_trans_data['ct_disc_amt'];
                $challan_trans_data['ct_bank_rate'] = $bank_rate;
                $challan_trans_data['ct_total_amt'] = $challan_trans_data['ct_dollar'] * $bank_rate;

                if($challan_trans_data['ct_dm_wt'] > 0)
                {
                	$challan_trans_data['ct_ppc'] = $challan_trans_data['ct_dollar'] / $challan_trans_data['ct_dm_wt'];
                }
                else
                {
                	$challan_trans_data['ct_ppc'] = 0;
                }

            }


			if ($value == 0)
			{
				/*sale transaction insert process*/
				$challan_trans_data['ct_status']	= 1;
				$challan_trans_data['ct_delete']	= 1;
				$challan_trans_result 				= $this->db_operations->data_insert('challan_trans', $challan_trans_data);

				$diamond_data_add['dm_update_id'] 	= $_SESSION['user_id'];
				$diamond_data_add['dm_date_update'] = date('Y-m-d H:i:s');
				$diamond_data_add['dm_status'] 		= 1;
				$diamond_data_add['dm_ct_id'] 		= $challan_trans_result;
				$diamond_data_add['dm_crt_id'] 		= 0;

				$this->db_operations->data_update('diamond_master',$diamond_data_add,'dm_id',$challan_trans_data['ct_dm_id']);

				$cnt = $this->db_operations->get_cnt('challan_return_trans', ['crt_dm_id'=>$challan_trans_data['ct_dm_id'], 'crt_delete'=>1]);

				if($cnt != 0)
				{
					$this->db_operations->data_update('challan_return_trans',['crt_delete'=>0],'crt_dm_id',$challan_trans_data['ct_dm_id']);
				}
			}
			else
			{
				/*purchase transaction update process*/
				$challan_trans_result = $this->db_operations->data_update('challan_trans',$challan_trans_data,'ct_id',$value);

				$diamond_data_edit['dm_update_id'] 	= $_SESSION['user_id'];
				$diamond_data_edit['dm_date_update'] = date('Y-m-d H:i:s');

				$this->db_operations->data_update('diamond_master',$diamond_data_edit,'dm_id',$challan_trans_data['ct_dm_id']);

			}


		}
		// exit();
	}
	public function challan_delete($cm_id)
	{
		if(sessionExist()) {
			$ct_data = $this->db_operations->get_record('challan_trans', ['ct_cm_id'=>$cm_id]);
			$ct_delete = 1;
			foreach ($ct_data as $key => $value)
			{
				if($value['ct_delete'] == 0)
				{
					$ct_delete = 0;
				}
			}
			// if($cnt != 0)
			if($ct_delete == 1)
			{
				$ct_data = $this->db_operations->get_record('challan_trans', ['ct_cm_id'=>$cm_id, 'ct_status'=>1]);

				foreach ($ct_data as $key => $value)
				{
					$crt_data =  $this->Challanmdl->get_latest_crt_id($value['ct_dm_id']);
					if(!empty($crt_data))
					{
						$crt_id = $crt_data[0]['crt_id'];
						$this->db_operations->data_update('challan_return_trans',['crt_delete'=>1],'crt_id',$crt_id);
					}
					else
					{
						$crt_id = 0;
					}

					$diamond_data_db = $this->Challanmdl->get_challan_return_data_by_id($value['ct_dm_id']);
					if(empty($diamond_data_db))
					{
						$diamond_data_db = $this->db_operations->get_record('diamond_master', ['dm_id'=>$value['ct_dm_id']]);
						$diamond_data['dm_update_id'] 	= $diamond_data_db[0]['dm_user_id'];
						$diamond_data['dm_date_update'] = $diamond_data_db[0]['dm_date_create'];
						$diamond_data['dm_status'] 		= 0;
						$diamond_data['dm_ct_id'] 		= 0;
						$diamond_data['dm_crt_id'] 		= $crt_id;
					}
					else
					{
						$diamond_data['dm_update_id'] 	= $diamond_data_db[0]['crm_update_userid'];
						$diamond_data['dm_date_update'] = $diamond_data_db[0]['crm_update_date'];
						$diamond_data['dm_status'] 		= 4;
						$diamond_data['dm_ct_id'] 		= 0;
						$diamond_data['dm_crt_id'] 		= $crt_id;
					}

					$this->db_operations->data_update('diamond_master',$diamond_data,'dm_id',$value['ct_dm_id']);

				}
				$this->db_operations->delete_record('challan_master', array('cm_id' => $cm_id));
					$this->db_operations->delete_record('challan_trans', array('ct_cm_id' => $cm_id));
				echo 1;
			}
			else
			{
				echo 2;
			}


		} else {
			redirect('loginctrl/logout');
		}
	}
	public function update_total_amt()
	{
		$challan_trans_db_data = $this->db->query("SELECT cm.cm_entry_date, ct.ct_id, ct.ct_dm_lab,  ct.ct_dm_wt, ct.ct_dm_rap, ct.ct_dm_disc FROM challan_master cm LEFT JOIN challan_trans ct ON(ct.ct_cm_id = cm.cm_id)")->result_array();
		$flag = 0;
		// echo "<pre>"; print_r($challan_trans_data); exit();
		foreach ($challan_trans_db_data as $key => $value)
		{
			$bank_rate = 0;
			$bank_rate_data = $this->db_operations->get_record('bank_rate_master', ['bank_rate_date' => date('Y-m-d', strtotime($value['cm_entry_date']))]);
			// echo "<pre>"; print_r($bank_rate_data); exit();
			if (!empty($bank_rate_data))
			{
				$bank_rate = $bank_rate_data[0]['bank_rate'];
			}

			if(strtoupper($value['ct_dm_lab']) == 'GIA')
	        {
	        	$challan_trans_data = [];
	            $challan_trans_data['ct_sub_total'] = $value['ct_dm_wt'] * $value['ct_dm_rap'];

	            if(!empty($value['ct_dm_disc']))
	           	{
	           		$disc = explode('-', $value['ct_dm_disc']);
	                if(empty($disc[0]))
	                {
	                    $disc = $disc[1];
	                }
	                else
	                {
	                    $disc = $disc[0];
	                }
	           	}
	           	else
	           	{
	           		$disc = 0;
	           	}

	            $challan_trans_data['ct_disc_amt'] = ($challan_trans_data['ct_sub_total'] * $disc)/100;
	            $challan_trans_data['ct_dollar'] = $challan_trans_data['ct_sub_total'] - $challan_trans_data['ct_disc_amt'];

	            $challan_trans_data['ct_bank_rate'] = $bank_rate;
	            $challan_trans_data['ct_total_amt'] = $challan_trans_data['ct_dollar'] * $bank_rate;

	            $challan_trans_data['ct_ppc'] = $challan_trans_data['ct_dollar'] / $value['ct_dm_wt'];


	        }
	        elseif(strtoupper($value['ct_dm_lab']) == 'IGI' || strtoupper($value['ct_dm_lab']) == 'HRD')
	        {
	        	$challan_trans_data = [];
	            $challan_trans_data['ct_sub_total'] = $value['ct_dm_wt'] * $value['ct_dm_rap'];

	            if(!empty($value['ct_dm_disc']))
	           	{
	           		$disc = explode('-', $value['ct_dm_disc']);
	                if(empty($disc[0]))
	                {
	                    $disc = $disc[1];
	                }
	                else
	                {
	                    $disc = $disc[0];
	                }
	           	}
	           	else
	           	{
	           		$disc = 0;
	           	}

	            $disc_amt = ($challan_trans_data['ct_sub_total'] * $disc)/100;
	            $total_dollar = $challan_trans_data['ct_sub_total'] - $disc_amt;
	            $challan_trans_data['ct_bank_rate'] = $bank_rate;
	            $challan_trans_data['ct_total_amt'] = $total_dollar * $bank_rate;

	            $challan_trans_data['ct_disc_amt'] = ($total_dollar * 2) / 100;
	            $challan_trans_data['ct_dollar'] = $total_dollar - $challan_trans_data['ct_disc_amt'];
	            $challan_trans_data['ct_ppc'] = $challan_trans_data['ct_dollar'] / $value['ct_dm_wt'];
	        }
	        else
	        {
	        	$challan_trans_data = [];
	        	$challan_trans_data['ct_sub_total'] = $value['ct_dm_wt'] * $value['ct_dm_rap'];

	            if(!empty($value['ct_dm_disc']))
	           	{
	           		$disc = explode('-', $value['ct_dm_disc']);
	                if(empty($disc[0]))
	                {
	                    $disc = $disc[1];
	                }
	                else
	                {
	                    $disc = $disc[0];
	                }
	           	}
	           	else
	           	{
	           		$disc = 0;
	           	}

	            $challan_trans_data['ct_disc_amt'] = ($challan_trans_data['ct_sub_total'] * $disc)/100;
	            $challan_trans_data['ct_bank_rate'] = $bank_rate;

	            $challan_trans_data['ct_dollar'] = $challan_trans_data['ct_sub_total'] - $challan_trans_data['ct_disc_amt'];
	            $challan_trans_data['ct_total_amt'] = $challan_trans_data['ct_dollar'] * $bank_rate;
	            if($value['ct_dm_wt'] > 0)
	            {
	            	$challan_trans_data['ct_ppc'] = $challan_trans_data['ct_dollar'] / $value['ct_dm_wt'];
	            }
	            else
	            {
	            	$challan_trans_data['ct_ppc'] = 0;
	            }

	        }

	        if($this->db_operations->data_update('challan_trans', $challan_trans_data, 'ct_id', $value['ct_id']) < 1)
	        {
	        	$flag = 1;
	        }
		}

		if($flag == 0)
		{
			echo "Data update successfully";
		}
		else
		{
			echo "Data not update successfully";
		}
	}
/*/challan master*/

/*challan return master*/
	public function challan_return_master()
	{
		if(sessionExist())
		{
			if($_GET['action'] == 'view')
			{
				$config 				= array();
				$config 				= $this->config->item('pagination');
				$config['total_rows'] 	= $this->Challanmdl->get_all_challan_return_data_cnt();
				$config['base_url'] 	= base_url("challan/challanctrl/challan_return_master?search=true");

				foreach ($_GET as $key => $value)
				{
					if($key != 'search' && $key != 'offset')
					{
						$config['base_url'] .= "&" . $key . "=" .$value;
					}
				}

				$offset = (!empty($_GET['offset'])) ? $_GET['offset'] : 0;
				$this->pagination->initialize($config);

				$record['count'] 		= $offset;
				$record['total_rows'] 	= $config['total_rows'];
				$record['role'] 		= $this->config->item('role');
				$record['data']			= $this->Challanmdl->get_all_challan_return_data($config['per_page'],$offset);
				$this->load->view('pages/challan/challan_return_master', $record);
			}
			elseif ($_GET['action'] == 'add')
			{
				$record = $this->Challanmdl->get_challan_return_data_for_add();
				// echo "<pre>"; print_r($record); exit;
				$this->load->view('pages/challan/challan_return_form', $record);
			}
			elseif($_GET['action'] == 'edit')
			{
				$crm_id = encrypt_decrypt("decrypt", $_GET['id'], SECRET_KEY);
				$record = $this->Challanmdl->get_challan_return_trans_data_for_edit($crm_id);
				// echo "<pre>"; print_r($record); exit;
				$this->load->view('pages/challan/challan_return_form', $record);
			}
			elseif($_GET['action'] == 'print')
			{
				$cm_id = encrypt_decrypt("decrypt", $_GET['id'], SECRET_KEY);
				$record = $this->Challanmdl->get_challan_data_for_edit($cm_id);
				// echo "<pre>"; print_r($record); exit;
				$this->load->view('pdfs/challan/challan_print', $record);
			}
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}
	public function get_broker_data_from_challan($cust_id)
	{
		if(sessionExist())
		{
			echo json_encode($this->Challanmdl->get_broker_data_from_challan($cust_id));
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}
	public function get_through_data_from_challan($broker_id, $cust_id)
	{
		if(sessionExist())
		{
			echo json_encode($this->Challanmdl->get_through_data_from_challan($broker_id, $cust_id));
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}
	public function challan_return_insert_update($crm_id)
	{
		if (sessionExist())
		{
			$form_data = $this->input->post();

			// echo "<pre>";print_r($form_data);exit();

			/*sale master data array*/
			$challan_return_data = array();

			$challan_return_data['crm_entry_no'] 		= $form_data['crm_entry_no'];
			$challan_return_data['crm_entry_date'] 		= date('Y-m-d H:i:s',strtotime($form_data['crm_entry_date']));
			$challan_return_data['crm_cust_id'] 		= $form_data['crm_cust_id'];
			$challan_return_data['crm_broker_id'] 		= $form_data['crm_broker_id'];
			$challan_return_data['crm_through'] 		= $form_data['crm_through'];
			$challan_return_data['crm_notes'] 			= $form_data['crm_notes'];
			$challan_return_data['crm_total_qty'] 		= $form_data['crm_total_qty'];
			$challan_return_data['crm_total_amt'] 		= $form_data['crm_total_amt'];


			if ($crm_id == 0)
			{
				$this->db->trans_begin();
				/*check duplicate purchase entry no*/
				$cnt = $this->db_operations->get_cnt('challan_return_master', array('crm_entry_no' => $form_data['crm_entry_no'], 'crm_fin_month' => $_SESSION['fin_month']));
				if ($cnt != 0)
				{
					$challan_return_data['crm_entry_no'] = $this->db_operations->get_fin_year_max_id('challan_return_master', 'crm_entry_no', 'crm_fin_month');
					// $response['resp'] = 2;
					// echo json_encode($response);
				}
				$challan_return_data['crm_fin_year']		= $_SESSION['fin_year'];
				$challan_return_data['crm_fin_month']		= $_SESSION['fin_month'];
				$challan_return_data['crm_userid'] 			= $_SESSION['user_id'];
				$challan_return_data['crm_create_date'] 	= date('Y-m-d H:i:s');
				$challan_return_data['crm_update_userid'] 	= $_SESSION['user_id'];
				$challan_return_data['crm_update_date'] 	= date('Y-m-d H:i:s');

				/*insert data to purchase_order_master table*/
				$crm_id = $this->db_operations->data_insert('challan_return_master', $challan_return_data);

				if (!empty($crm_id))
				{
					/*insert data to purchase_trans table*/
					$crt_result 	= $this->insert_update_challan_return_trans($form_data, $crm_id);
				}
				// echo "<pre>"; print_r($this->db->trans_status());exit;

				if ($this->db->trans_status() === FALSE) {
				    $this->db->trans_rollback();
				    $response['resp'] = 0;
					echo json_encode($response);

				} else {
				    $this->db->trans_commit();
				    $response['resp'] = 1;
				    $response['last_id'] = encrypt_decrypt("encrypt", $crm_id, SECRET_KEY);
					echo json_encode($response);
				}
			}
			else
			{
				$this->db->trans_begin();
				/*update code*/
				$cnt = $this->db_operations->get_cnt('challan_return_master', array('crm_id !=' => $crm_id,'crm_entry_no' => $form_data['crm_entry_no'], 'crm_fin_year' => $_SESSION['fin_year']));

				if ($cnt != 0)
				{
					$response['resp'] = 2;
					echo json_encode($response);
				}
				else
				{
					$challan_return_data['crm_update_userid'] 	= $_SESSION['user_id'];
					$challan_return_data['crm_update_date'] 	= date('Y-m-d H:i:s');

					/*update data to sale_master table*/
					$result = $this->db_operations->data_update('challan_return_master', $challan_return_data, 'crm_id', $crm_id);

					if (!empty($result))
					{
						/*update data to sale_master table*/
						$crt_result 	= $this->insert_update_challan_return_trans($form_data, $crm_id);
					}

					if ($this->db->trans_status() === FALSE)
					{
					    $this->db->trans_rollback();
					    // echo 0;
					    $response['resp'] = 0;
						echo json_encode($response);
					} else {
					    $this->db->trans_commit();
						// echo 1;
						$response['resp'] = 1;
					 	$response['last_id'] = encrypt_decrypt("encrypt", $crm_id, SECRET_KEY);
						echo json_encode($response);
					}
				}
			}
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}
	public function insert_update_challan_return_trans($form_data, $crm_id)
	{
		// 0 = not avialable
		// 1 = avialable

		$challan_return_trans_data = $this->db_operations->get_record('challan_return_trans',array('crt_crm_id' =>$crm_id)); // get all db record first and all form data and match who is missing and those data delete by system
		// echo "<pre>"; print_r($purchase_order_trans_data);
		// echo "<pre>"; print_r($form_data); exit();

		foreach ($challan_return_trans_data as $key => $value)
		{
			if (!in_array($value['crt_id'], $form_data['crt_id']))
			{
				/*delete transactions*/
				$diamond_data_db 						= $this->Challanmdl->get_challan_data_by_id($value['crt_dm_id']);
				$diamond_data_delete['dm_update_id'] 	= $diamond_data_db[0]['cm_update_userid'];
				$diamond_data_delete['dm_date_update'] 	= $diamond_data_db[0]['cm_update_date'];
				$diamond_data_delete['dm_status'] 		= 1;
				$diamond_data_delete['dm_ct_id'] 		= $value['crt_ct_id'];
				$diamond_data_delete['dm_crt_id'] 		= 0;

				$this->db_operations->data_update('diamond_master',$diamond_data_delete,'dm_id',$value['crt_dm_id']);
				$this->db_operations->data_update('challan_trans',['ct_status'=>1, 'ct_delete'=>1],'ct_id',$value['crt_ct_id']);
				$del_res = $this->db_operations->delete_record('challan_return_trans',array('crt_id' =>$value['crt_id']));
			}
		}

		foreach ($form_data['crt_id'] as $key => $value)
		{
			/*purchase transaction data*/
			$challan_return_trans_data = array();

			$challan_return_trans_data['crt_crm_id'] 		  	= $crm_id;
			$challan_return_trans_data['crt_dm_id'] 	 	  	= $form_data['crt_dm_id'][$key];
			$challan_return_trans_data['crt_ct_id'] 	 	  	= $form_data['ct_id'][$key];
			$challan_return_trans_data['crt_dm_code'] 	 	  	= $this->db_operations->get_record('diamond_master', ['dm_id'=>$challan_return_trans_data['crt_dm_id']])[0]['dm_code'];
			$challan_return_trans_data['crt_dm_sh'] 	 	  	= $form_data['crt_dm_sh'][$key];
			$challan_return_trans_data['crt_dm_wt'] 	 	  	= $form_data['crt_dm_wt'][$key];
			$challan_return_trans_data['crt_dm_col'] 	 	  	= $form_data['crt_dm_col'][$key];
			$challan_return_trans_data['crt_dm_cla'] 	 	  	= $form_data['crt_dm_cla'][$key];
			$challan_return_trans_data['crt_dm_cut'] 	 	  	= $form_data['crt_dm_cut'][$key];
			$challan_return_trans_data['crt_dm_pol'] 	 	  	= $form_data['crt_dm_pol'][$key];
			$challan_return_trans_data['crt_dm_sym'] 	 	  	= $form_data['crt_dm_sym'][$key];
			$challan_return_trans_data['crt_dm_fl'] 	 	  	= $form_data['crt_dm_fl'][$key];
			$challan_return_trans_data['crt_dm_lab'] 	 	  	= $form_data['crt_dm_lab'][$key];
			$challan_return_trans_data['crt_dm_disc'] 	 	  	= $form_data['crt_dm_disc'][$key];
			$challan_return_trans_data['crt_dm_rap'] 	 	  	= $form_data['crt_dm_rap'][$key];
			$challan_return_trans_data['crt_dm_rap'] 	 	  	= $form_data['crt_dm_rap'][$key];
			$challan_return_trans_data['crt_dm_cert'] 	 	  	= $form_data['crt_dm_cert'][$key];
			$challan_return_trans_data['crt_dm_status']	 	  	= $form_data['crt_dm_status'][$key];
			$challan_return_trans_data['crt_dm_remarks'] 	  	= $form_data['crt_dm_remarks'][$key];

			if ($value == 0)
			{
				/*sale transaction insert process*/
				$challan_return_trans_data['crt_delete'] 	  	= 1;
				$challan_return_trans_result = $this->db_operations->data_insert('challan_return_trans', $challan_return_trans_data);
				$diamond_data['dm_ct_id'] 	 = 0;
				$diamond_data['dm_crt_id'] 	 = $challan_return_trans_result;
				$cnt = $this->db_operations->get_cnt('challan_trans', ['ct_dm_id'=>$challan_return_trans_data['crt_dm_id'], 'ct_delete'=>1]);

				if($cnt != 0)
				{
					$this->db_operations->data_update('challan_trans',['ct_delete'=>0],'ct_dm_id',$challan_return_trans_data['crt_dm_id']);
				}
			}
			else
			{
				/*purchase transaction update process*/
				$challan_return_trans_result = $this->db_operations->data_update('challan_return_trans',$challan_return_trans_data,'crt_id',$value);

			}
			$diamond_data['dm_update_id'] 	= $_SESSION['user_id'];
			$diamond_data['dm_date_update'] = date('Y-m-d H:i:s');
			$diamond_data['dm_status'] 		= $challan_return_trans_data['crt_dm_status'];
			$this->db_operations->data_update('diamond_master',$diamond_data,'dm_id',$challan_return_trans_data['crt_dm_id']);
			$this->db_operations->data_update('challan_trans',['ct_status'=>$challan_return_trans_data['crt_dm_status']],'ct_id',$challan_return_trans_data['crt_ct_id']);

		}
		// exit();
	}
	public function challan_return_delete($crm_id)
	{
		if(sessionExist())
		{
			$crt_data = $this->db_operations->get_record('challan_return_trans', ['crt_crm_id'=>$crm_id]);
			$crt_delete = 1;
			foreach ($crt_data as $key => $value)
			{
				if($value['crt_delete'] == 0)
				{
					$crt_delete = 0;
				}
			}
			// if($cnt != 0)
			if($crt_delete == 1)
			{
				$crt_data = $this->db_operations->get_record('challan_return_trans', ['crt_crm_id'=>$crm_id]);
				foreach ($crt_data as $key => $value)
				{
					$diamond_data_db 				= $this->Challanmdl->get_challan_data_by_id($value['crt_dm_id']);
					$diamond_data['dm_update_id'] 	= $diamond_data_db[0]['cm_update_userid'];
					$diamond_data['dm_date_update'] = $diamond_data_db[0]['cm_update_date'];
					$diamond_data['dm_status'] 		= 1;
					$diamond_data['dm_ct_id'] 		= $value['crt_ct_id'];
					$diamond_data['dm_crt_id'] 		= 0;
					$this->db_operations->data_update('diamond_master',$diamond_data,'dm_id',$value['crt_dm_id']);
					$this->db_operations->data_update('challan_trans',['ct_status'=>1, 'ct_delete'=>1],'ct_id',$value['crt_ct_id']);
				}
				$this->db_operations->delete_record('challan_return_master', array('crm_id' => $crm_id));
				$this->db_operations->delete_record('challan_return_trans', array('crt_crm_id' => $crm_id));
				echo 1;
			}
			else
			{
				echo 2;
			}

		} else {
			redirect('loginctrl/logout');
		}
	}
	public function receive_certificate($crt_id)
	{
		if(sessionExist())
		{

			echo json_encode($this->db_operations->data_update('challan_return_trans', ['crt_dm_cert'=>1], 'crt_id',  $crt_id));
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}
/*/challan return master*/


/***********************************************************************************************************************************************/
/*Master Ctrl End*/
}

/*master ctroller End*/
?>