<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
	require FCPATH.'vendor/autoload.php';
	use PhpOffice\PhpSpreadsheet\Spreadsheet; 
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	// use PhpOffice\PhpSpreadsheet\Style\Alignment;

	use PhpOffice\PhpSpreadsheet\IOFactory;
	use PhpOffice\PhpSpreadsheet\Style\Border;
	use PhpOffice\PhpSpreadsheet\Style\Color;
	use PhpOffice\PhpSpreadsheet\Cell\DataType;
	use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
class Masterctrl extends CI_Controller
{
	public $Mastermdl;
	public $excel;
	public $pagination;
	public function __construct()
	{
		parent::__construct();

		$this->load->model('master/Mastermdl');
		// $this->load->model('master/Dhiaanmdl');
		$this->load->library('session');
		$this->load->library('upload');
		$this->load->library('pagination');
		$this->config->load('extra');
		$this->load->library('db_operations');

	}

	public function index()
	{
		if(sessionExist()) {
			$this->load->view('pages/master/index');
		} else {
			redirect('loginctrl/logout');
		}
	}

/*common function*/
	public function generate_token($length)
	{
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $token = substr( str_shuffle( $chars ), 0, $length );
        return $token;
    }
/*/common function */


/*Exchange Rate Master */
	public function exchange_rate_master()
	{
		if(sessionExist()) {
			$record['exchange_rate_data'] = $this->db_operations->get_recordlist("exchange_rate_master");
			$this->load->view('pages/master/exchange_rate_master', $record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function exchange_rate_insert($exchange_rate_id = 0)
{
    if (!sessionExist()) {
        redirect('loginctrl/logout');
        return;
    }

    $form_data = $this->input->post();

    if (empty($form_data['exchange_rate_buying_rate'])) {
        echo json_encode(['status' => 'error', 'message' => 'Buying Rate is required.']);
        return;
    }

	if (empty($form_data['exchange_rate_selling_rate'])) {
        echo json_encode(['status' => 'error', 'message' => 'Selling Rate is required.']);
        return;
    }

    if ($exchange_rate_id == 0) {
        // Insert new Exchange Rate
        $cnt = $this->db_operations->get_cnt('exchange_rate_master', ['exchange_rate_date' => $form_data['exchange_rate_date']]);
        if ($cnt != 0) {
            echo json_encode(['status' => 'exists', 'message' => 'Exchange Rate for current date already exists.']);
        } else {
            $form_data['exchange_rate_created_at'] = date("Y-m-d H:i:s");
            $form_data['exchange_rate_user_id']    = $_SESSION['user_id'];

            $new_exchange_rate_id = $this->db_operations->data_insert('exchange_rate_master', $form_data);
            if ($new_exchange_rate_id) {
                echo json_encode([
                    'status' => 'success',
                    'message' => 'Exchange Rate added successfully.',
                    'new_exchange_rate_id' => $new_exchange_rate_id,
                    'new_exchange_rate_date' => $form_data['exchange_rate_date']
                ]);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to add Exchange Rate.']);
            }
        }
    } else {
        // Update existing Exchange Rate
        $cnt = $this->db_operations->get_cnt('exchange_rate_master', ['exchange_rate_id !=' => $exchange_rate_id, 'exchange_rate_date' => $form_data['exchange_rate_date']]);
        if ($cnt != 0) {
            echo json_encode(['status' => 'exists', 'message' => 'Exchange Rate already exists.']);
        } else {
            $form_data['exchange_rate_updated_at'] = date("Y-m-d H:i:s");
            $form_data['exchange_rate_update_id']  = $_SESSION['user_id'];

            $updated = $this->db_operations->data_update('exchange_rate_master', $form_data, 'exchange_rate_id', $exchange_rate_id);
            if ($updated) {
                echo json_encode([
                    'status' => 'success',
                    'message' => 'Exchange Rate updated successfully.',
                    'new_exchange_rate_id' => $exchange_rate_id,
                    'new_exchange_rate_date' => $form_data['exchange_rate_date']
                ]);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to update Exchange Rate.']);
            }
        }
    }
}


	public function get_single_exchange_rate($exchange_rate_id)
	{
		if(sessionExist()) {
			$record = $this->db_operations->get_record("exchange_rate_master", array("exchange_rate_id" => $exchange_rate_id));
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function exchange_rate_delete($exchange_rate_id)
	{
		if(sessionExist()) {
			$this->db_operations->delete_record('exchange_rate_master', array('exchange_rate_id' => $exchange_rate_id));
		} else {
			redirect('loginctrl/logout');
		}
	}
/*/Exchange Rate Master */

/*City Master */
	public function city_master()
	{
		if(sessionExist()) {
			$record['city_data'] = $this->db_operations->get_recordlist("city_master");
			$this->load->view('pages/master/city_master', $record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function city_insert($city_id)
	{
		if(sessionExist()) {
			$form_data = $this->input->post();

			if($city_id == 0) {
				$cnt = $this->db_operations->get_cnt('city_master', ['city_name' => $form_data['city_name']]);
				if ($cnt != 0) {
					echo 2;
				} else {
					$form_data['city_created_at'] 	= date("Y-m-d H:i:s");
					$form_data['city_user_id'] 		= $_SESSION['user_id'];
					$result = $this->db_operations->data_insert('city_master', $form_data);
					echo (!empty($result)) ? 1 : 0;
				}
			} else {
				$cnt = $this->db_operations->get_cnt('city_master', ['city_id !=' => $city_id, 'city_name' => $form_data['city_name']]);
				if ($cnt != 0) {
					echo 2;
				} else {
					$form_data['city_updated_at'] 	= date("Y-m-d H:i:s");
					$form_data['city_update_id'] 	= $_SESSION['user_id'];
					echo $this->db_operations->data_update('city_master', $form_data, 'city_id', $city_id);
				}
			}
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function get_single_city($city_id)
	{
		if(sessionExist()) {
			$record = $this->db_operations->get_record("city_master", array("city_id" => $city_id));
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function city_delete($city_id)
	{
		if(sessionExist()) {
			$this->db_operations->delete_record('city_master', array('city_id' => $city_id));
		} else {
			redirect('loginctrl/logout');
		}
	}
/*/City Master */

/*State Master */
	public function state_master()
	{
		if(sessionExist()) {
			$record['state_data'] = $this->db_operations->get_recordlist("state_master");
			$this->load->view('pages/master/state_master', $record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function state_insert($state_id)
	{
		if(sessionExist()) {
			$form_data = $this->input->post();

			if($state_id == 0) {
				$cnt = $this->db_operations->get_cnt('state_master', ['state_name' => $form_data['state_name']]);
				if ($cnt != 0) {
					echo 2;
				} else {
					$form_data['state_created_at'] 	= date("Y-m-d H:i:s");
					$form_data['state_user_id'] 		= $_SESSION['user_id'];
					$result = $this->db_operations->data_insert('state_master', $form_data);
					echo (!empty($result)) ? 1 : 0;
				}
			} else {
				$cnt = $this->db_operations->get_cnt('state_master', ['state_id !=' => $state_id, 'state_name' => $form_data['state_name']]);
				if ($cnt != 0) {
					echo 2;
				} else {
					$form_data['state_updated_at'] 	= date("Y-m-d H:i:s");
					$form_data['state_update_id'] 	= $_SESSION['user_id'];
					echo $this->db_operations->data_update('state_master', $form_data, 'state_id', $state_id);
				}
			}
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function get_single_state($state_id)
	{
		if(sessionExist()) {
			$record = $this->db_operations->get_record("state_master", array("state_id" => $state_id));
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function state_delete($state_id)
	{
		if(sessionExist()) {
			$this->db_operations->delete_record('state_master', array('state_id' => $state_id));
		} else {
			redirect('loginctrl/logout');
		}
	}
/*/State Master */

/*Country Master */
	public function country_master()
	{
		if(sessionExist()) {
			$record['country_data'] = $this->db_operations->get_recordlist("country_master");
			$this->load->view('pages/master/country_master', $record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function country_insert($country_id)
	{
		if(sessionExist()) {
			$form_data = $this->input->post();

			if($country_id == 0) {
				$cnt = $this->db_operations->get_cnt('country_master', ['country_name' => $form_data['country_name']]);
				if ($cnt != 0) {
					echo 2;
				} else {
					$form_data['country_created_at'] 	= date("Y-m-d H:i:s");
					$form_data['country_user_id'] 		= $_SESSION['user_id'];
					$result = $this->db_operations->data_insert('country_master', $form_data);
					echo (!empty($result)) ? 1 : 0;
				}
			} else {
				$cnt = $this->db_operations->get_cnt('country_master', ['country_id !=' => $country_id, 'country_name' => $form_data['country_name']]);
				if ($cnt != 0) {
					echo 2;
				} else {
					$form_data['country_updated_at'] 	= date("Y-m-d H:i:s");
					$form_data['country_update_id'] 	= $_SESSION['user_id'];
					echo $this->db_operations->data_update('country_master', $form_data, 'country_id', $country_id);
				}
			}
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function get_single_country($country_id)
	{
		if(sessionExist()) {
			$record = $this->db_operations->get_record("country_master", array("country_id" => $country_id));
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function country_delete($country_id)
	{
		if(sessionExist()) {
			$this->db_operations->delete_record('country_master', array('country_id' => $country_id));
		} else {
			redirect('loginctrl/logout');
		}
	}
/*/Country Master */

/*Hsn Master */
	public function hsn_master()
	{
		if(sessionExist()) {
			$record['hsn_data'] = $this->db_operations->get_recordlist("hsn_master");
			$this->load->view('pages/master/hsn_master', $record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function hsn_insert($hsn_id = 0)
{
    if (!sessionExist()) {
        redirect('loginctrl/logout');
        return;
    }

    $form_data = $this->input->post();

    if (empty($form_data['hsn_code'])) {
        echo json_encode(['status' => 'error', 'message' => 'HSN code is required.']);
        return;
    }

    if ($hsn_id == 0) {
        // Insert new HSN
        $cnt = $this->db_operations->get_cnt('hsn_master', ['hsn_code' => $form_data['hsn_code']]);
        if ($cnt != 0) {
            echo json_encode(['status' => 'exists', 'message' => 'HSN code already exists.']);
        } else {
            $form_data['hsn_created_at'] = date("Y-m-d H:i:s");
            $form_data['hsn_user_id']    = $_SESSION['user_id'];

            $new_hsn_id = $this->db_operations->data_insert('hsn_master', $form_data);
            if ($new_hsn_id) {
                echo json_encode([
                    'status' => 'success',
                    'message' => 'HSN added successfully.',
                    'new_hsn_id' => $new_hsn_id,
                    'new_hsn_code' => $form_data['hsn_code']
                ]);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to add HSN.']);
            }
        }
    } else {
        // Update existing HSN
        $cnt = $this->db_operations->get_cnt('hsn_master', ['hsn_id !=' => $hsn_id, 'hsn_code' => $form_data['hsn_code']]);
        if ($cnt != 0) {
            echo json_encode(['status' => 'exists', 'message' => 'HSN code already exists.']);
        } else {
            $form_data['hsn_updated_at'] = date("Y-m-d H:i:s");
            $form_data['hsn_update_id']  = $_SESSION['user_id'];

            $updated = $this->db_operations->data_update('hsn_master', $form_data, 'hsn_id', $hsn_id);
            if ($updated) {
                echo json_encode([
                    'status' => 'success',
                    'message' => 'HSN updated successfully.',
                    'new_hsn_id' => $hsn_id,
                    'new_hsn_code' => $form_data['hsn_code']
                ]);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to update HSN.']);
            }
        }
    }
}


	public function get_single_hsn($hsn_id)
	{
		if(sessionExist()) {
			$record = $this->db_operations->get_record("hsn_master", array("hsn_id" => $hsn_id));
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function hsn_delete($hsn_id)
	{
		if(sessionExist()) {
			$this->db_operations->delete_record('hsn_master', array('hsn_id' => $hsn_id));
		} else {
			redirect('loginctrl/logout');
		}
	}
/*/Hsn Master */

/*Bank Rate Master */
	public function bank_rate_master()
	{
		if(sessionExist()) {
			$record['bank_rate_data'] = $this->db_operations->get_recordlist("bank_rate_master");
			$this->load->view('pages/master/bank_rate_master', $record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function add_update_bank_rate($bank_rate_id)
	{
		if(sessionExist()) {
			$form_data = $this->input->post();
			$form_data['bank_rate_date'] = date('Y-m-d', strtotime($form_data['bank_rate_date']));

			if($bank_rate_id == 0) {
				$cnt = $this->db_operations->get_cnt('bank_rate_master', ['bank_rate_date' => $form_data['bank_rate_date']]);
				if ($cnt != 0) {
					echo 2;
				} else {
					$form_data['bank_rate_created_at'] 	= date("Y-m-d H:i:s");
					$form_data['bank_rate_user_id'] 	= $_SESSION['user_id'];
					$form_data['bank_rate_updated_at'] 	= date("Y-m-d H:i:s");
					$form_data['bank_rate_update_id'] 	= $_SESSION['user_id'];

					$result = $this->db_operations->data_insert('bank_rate_master', $form_data);
					echo (!empty($result)) ? 1 : 0;
				}
			} else {
				$cnt = $this->db_operations->get_cnt('bank_rate_master', ['bank_rate_id !=' => $bank_rate_id, 'bank_rate_date' => $form_data['bank_rate_date']]);
				if ($cnt != 0) {
					echo 2;
				} else {
					$form_data['bank_rate_updated_at'] 	= date("Y-m-d H:i:s");
					$form_data['bank_rate_update_id'] 	= $_SESSION['user_id'];
					echo $this->db_operations->data_update('bank_rate_master', $form_data, 'bank_rate_id', $bank_rate_id);
				}
			}
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function get_single_bank_rate($bank_rate_id)
	{
		if(sessionExist()) {
			$record = $this->Mastermdl->get_single_bank_rate($bank_rate_id);
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function bank_rate_delete($bank_rate_id)
	{
		if(sessionExist()) {
			$this->db_operations->delete_record('bank_rate_master', array('bank_rate_id' => $bank_rate_id));
		} else {
			redirect('loginctrl/logout');
		}
	}
/*/Bank Rate Master */

/*USER Master */
	public function user_master()
	{
		if(sessionExist()) {
			$record['role'] 		= $this->config->item('role');
			$record['user_data'] 	= $this->db_operations->get_recordlist("user_master");

			$this->load->view('pages/master/user_master', $record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function get_role()
	{
		if(sessionExist()) {
			$record['role'] = $this->config->item('role');
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function user_insert($u_id)
	{
		if(sessionExist())
		{
			$form_data = $this->input->post();
			if($u_id == 0) {
				$cnt = $this->Mastermdl->get_cnt('user_master', array('user_name' => $form_data['user_name']));
				if ($cnt != 0) {
					echo 2;
				} else {
					$token = $this->generate_token(32);
					$form_data['user_token'] 		= $token;
					$user_password 					= $form_data['user_password'];
					$form_data['user_password'] 	= md5($form_data['user_password']);
					$form_data['user_date_create'] 	= date("Y-m-d H:i:s");

					$result = $this->db_operations->data_insert('user_master', $form_data);

					echo (!empty($result)) ? 1 : 0;
				}
			} else {
				if($form_data['user_password'] != "") {
					$form_data['user_password'] = md5($form_data['user_password']);
				} else {
					unset($form_data['user_password']);
				}

				$token = $this->generate_token(32);
				$form_data['user_token'] = $token;
				echo $this->db_operations->data_update('user_master', $form_data, 'user_id', $u_id);
			}
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function get_single_user($u_id)
	{
		if(sessionExist()) {
			$record = $this->db_operations->get_record("user_master", array("user_id" => $u_id));
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function user_delete($u_id)
	{
		if(sessionExist()) {
			$this->db_operations->delete_record('user_master', array('user_id' => $u_id));
			redirect(base_url('master/masterctrl/user_master'));
		} else {
			redirect('loginctrl/logout');
		}
	}
/*/USER Master */

/*Account Master */
	public function account_master($type)
	{
		if(sessionExist())
		{
			if($type == 0)
			{
				$record['label'] 	= "General Account";
				$record['link_id'] 	= "account";
			}
			else if($type == 5)
			{
				$record['label'] 	= "Customer Account";
				$record['link_id'] 	= "customer_account";
			}
			else if($type == 6)
			{
				$record['label'] 	= "Supplier Account";
				$record['link_id'] 	= "supplier_account";
			}
			else if($type == 23)
			{
				$record['label'] 	= "Brokers Account";
				$record['link_id'] 	= "broker_account";
			}


			$record['type'] = $type;

			$config = array();
			$this->config->load('extra');
			$config = $this->config->item('pagination');
			$config['per_page'] = 20;

			$config['total_rows'] = $this->Mastermdl->get_account_data_cnt($type);
			$config['base_url']   = base_url("master/masterctrl/account_master/".$type."?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['search_data'] 		= $this->config->item('account_search');


			$record['data'] 	= $this->Mastermdl->get_account_data($type,$config['per_page'],$offset);


			// $record['account_data'] = $this->Mastermdl->get_account_data($type);
			// echo "<pre>"; print_r($record); exit;
			 if($type == 5)
			{
				$this->load->view('pages/master/account_master', $record);
			}
			else if($type == 23)
			{
				$this->load->view('pages/master/broker_master', $record);
			}
			else if($type == 6)
			{
				$this->load->view('pages/master/supplier_master', $record);
			}

		} else {
			redirect('loginctrl/logout');
		}
	}

	public function account_insert($acc_id)
	{

		if(sessionExist()) {
			$form_data 		= $this->input->post();
			$files 			= $_FILES;
			$count 			= 0;
			$count1 		= 0;
			$sr_no 			= 0;

			$acc_diamond_type = isset($_POST['acc_diamond_type']) ? implode(',', $_POST['acc_diamond_type']) : 0;
			// echo "<pre>"; print_r($acc_diamond_type); exit;

			// echo "<pre>"; print_r($form_data);
			// echo "<pre>"; print_r($files); exit();
			if(isset($form_data['broker_photo']))
			{
				$count = count($form_data['broker_photo']);
			}
			for($i=0;$i<$count;$i++)
			{
				$sr_no = $sr_no + 1;
				$form_data['acc_brk_img_'.$sr_no] = $form_data['broker_photo'][$i];
			}

			if(isset($form_data['kyc_photo']))
			{
				$count1 = count($form_data['kyc_photo']);
			}
			for($j=0;$j<$count1;$j++)
			{
				$sr_no = $sr_no + 1;
				$form_data['acc_kyc_img_'.$sr_no] = $form_data['kyc_photo'][$i];
			}
			// echo "<pre>"; print_r($sr_no); exit();

			unset($form_data['broker_photo']);
			unset($form_data['kyc_photo']);
			if(!empty($_FILES['broker_img']['name']))
			{
				$count = count($_FILES['broker_img']['name']);
				for($i=0;$i<$count;$i++)
				{
					if($_FILES['broker_img']['error'][$i] == 0 && $sr_no < 5)
					{
						$_FILES['broker_img']['name']		= $files['broker_img']['name'][$i];
				        $_FILES['broker_img']['type']		= $files['broker_img']['type'][$i];
				        $_FILES['broker_img']['tmp_name']	= $files['broker_img']['tmp_name'][$i];
				        $_FILES['broker_img']['error']		= $files['broker_img']['error'][$i];
				        $_FILES['broker_img']['size']		= $files['broker_img']['size'][$i];

						$path =  $files['broker_img']['name'][$i];

						$ext = pathinfo($path, PATHINFO_EXTENSION);

						$fileName = time().'_'.$sr_no.'.'.$ext;
						$sr_no = $sr_no + 1;
						$form_data['acc_brk_img_'.$sr_no] = $fileName;
						unset($config);
						$config = array();
						$config['upload_path'] 		= 'public/uploads/brokers/';
						$config['allowed_types'] 	= 'gif|jpg|png|jpeg';
						$config['max_size']			= '102400';
						$config['file_name'] 		= $fileName;

						$this->upload->initialize($config);

						if(!$this->upload->do_upload('broker_img'))
						{
							echo $this->upload->display_errors();
						}
					}
				}
			}


			if(!empty($_FILES['kyc_img']['name']))
			{
				$count = count($_FILES['kyc_img']['name']);
				for($i=0;$i<$count;$i++)
				{
					if($_FILES['kyc_img']['error'][$i] == 0 && $sr_no < 5)
					{
						$_FILES['kyc_img']['name']		= $files['kyc_img']['name'][$i];
				        $_FILES['kyc_img']['type']		= $files['kyc_img']['type'][$i];
				        $_FILES['kyc_img']['tmp_name']	= $files['kyc_img']['tmp_name'][$i];
				        $_FILES['kyc_img']['error']		= $files['kyc_img']['error'][$i];
				        $_FILES['kyc_img']['size']		= $files['kyc_img']['size'][$i];

						$path =  $files['kyc_img']['name'][$i];

						$ext = pathinfo($path, PATHINFO_EXTENSION);

						$fileName = time().'_'.$sr_no.'.'.$ext;
						$sr_no = $sr_no + 1;
						$form_data['acc_kyc_img_'.$sr_no] = $fileName;
						unset($config);
						$config = array();
						if($form_data['acc_grp_id'] == 6){
							$config['upload_path'] 		= 'public/uploads/supplier_kyc/';
						}else{
							$config['upload_path'] 		= 'public/uploads/customer_kyc/';
						}
						$config['allowed_types'] 	= 'gif|jpg|png|jpeg|pdf';
						$config['max_size']			= '102400';
						$config['file_name'] 		= $fileName;

						$this->upload->initialize($config);

						if(!$this->upload->do_upload('kyc_img'))
						{
							echo $this->upload->display_errors();
						}
					}
				}
			}


			if($acc_id == 0)
			{
					
				if($form_data['acc_grp_id'] == 6){
					$form_data['acc_name'] = $form_data['acc_contact'];
				}
				
				$cnt = $this->Mastermdl->get_cnt('account_master', array('acc_name' => $form_data['acc_name'],'acc_grp_id' => $form_data['acc_grp_id']));

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

				if ($cnt != 0) {
					echo 2;
				} else
				{
					$form_data['acc_diamond_type'] 	= $acc_diamond_type;
					$form_data['acc_user_id'] 		= $_SESSION['user_id'];
					$form_data['acc_date_create'] 	= date("Y-m-d H:i:s");
					// echo "<pre>"; print_r($form_data); exit;

					$result = $this->db_operations->data_insert('account_master', $form_data);
					// $result = $this->Dhiaanmdl->dhiaan_account_insert('account_master',$form_data);
					//$result = $this->db2->db_operations->data_insert('account_master', $form_data);
					echo (!empty($result)) ? 1 : 0;
				}
			}
			else
			{
            //    echo "<pre>"; print_r($form_data);die;
				if($form_data['acc_status1'] == 1)
				{
					$record = $this->db_operations->get_record("account_master", array('acc_id' => $acc_id));
					if($record[0]['acc_status1']== 0)
					{
						$to = $record[0]['acc_email'];
						$subject = "demo Password for Login";
						$sixdigitrandom = rand(111111,999999);
						$form_data['acc_password'] 	= md5($sixdigitrandom);

						$msg1 = "";
                        $msg1 .= "Dear user,<br/><br/>";
                        $msg1 .= "Your Password for login to RUCHITA GEMS portal is ".$sixdigitrandom.".  Please do not share this Password."."<br/><br/>";
                        $msg1 .= "Regards,"."<br/>";
                        $msg1 .= "demo Team";
                        // $mresult = $this->mail_send_pass($to,$msg1,$subject);

					}

				}
				$form_data['acc_diamond_type'] 	= $acc_diamond_type;
				$form_data['acc_update_id'] 	= $_SESSION['user_id'];
				$form_data['acc_date_update'] 	= date("Y-m-d H:i:s");

				$img_data['acc_kyc_img_1'] 	= '';
				$img_data['acc_kyc_img_2'] 	= '';
				$img_data['acc_kyc_img_3'] 	= '';
				$img_data['acc_kyc_img_4'] 	= '';
				$img_data['acc_kyc_img_5'] 	= '';
				$img_data['acc_kyc_img_6'] 	= '';
				$img_data['acc_kyc_img_7'] 	= '';
				$img_data['acc_brk_img_1'] 	= '';
				$img_data['acc_brk_img_2'] 	= '';
				$img_data['acc_brk_img_3'] 	= '';
				$img_data['acc_brk_img_4'] 	= '';
				$img_data['acc_brk_img_5'] 	= '';
				$this->db_operations->data_update('account_master', $img_data, 'acc_id', $acc_id);
				// $this->Dhiaanmdl->dhiaan_data_update('account_master', $img_data, 'acc_id', $acc_id);

				// echo "<pre>"; print_r($form_data); exit;
				 // $this->Dhiaanmdl->dhiaan_data_update('account_master',$form_data,'acc_id', $acc_id);



				echo $this->db_operations->data_update('account_master', $form_data, 'acc_id', $acc_id);



			}
		} else {
			redirect('loginctrl/logout');
		}
	}


		public function mail_send_pass($to,$message,$subject)
        {
            $this->load->library('email');
            
            $config['mailtype']         = 'html';
            $config['charset']          = 'utf-8';
            $config['send_multipart']   = 'FALSE';
            $this->email->initialize($config);
            $this->email->set_newline("\r\n");
            $this->email->set_crlf( "\r\n" );

            $this->email->from('noreply@demo.com');

            $this->email->to($to);
            $this->email->subject($subject);
            $this->email->message($message);
        
            if(!$this->email->send())
            {
                $this->email->print_debugger();
                return false;
            }
            else
            {
                return true;
            }
        }

	public function get_account_assets()
	{
		if (sessionExist()) {
			$record['group_data'] 		= $this->Mastermdl->get_group_list();
			$record['broker_data'] 	 	= $this->Mastermdl->get_all_broker_data();
			$record['city_data'] 	 	= $this->Mastermdl->get_all_city_data();
			$record['state_data'] 	 	= $this->Mastermdl->get_all_state_data();
			$record['country_data'] 	= $this->Mastermdl->get_all_country_data();
			$record['type_data'] 	 	= $this->config->item('account_types');
			$record['priority_data'] 	= $this->config->item('buyer_priority');
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function get_single_account($acc_id)
	{
		if(sessionExist()) {
			$record['acc_data'] 	= $this->Mastermdl->get_single_acc_record($acc_id);
			$record['base_path'] 	= uploads('brokers');
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function account_delete($acc_id)
	{
		if(sessionExist()) {
			$record = $this->db_operations->get_record("account_master", array('acc_id' => $acc_id));

			if($record[0]['acc_grp_id'] == 3 || $record[0]['acc_grp_id'] == 4 || $record[0]['acc_grp_id'] == 9) {
				echo 2;
			}
			else
			{
				if($record[0]['acc_grp_id'] == 5)
				{
					$cnt = $this->db_operations->get_cnt('challan_master', ['cm_cust_id'=>$acc_id]);
					if($cnt != 0)
					{
						echo 2;
					}
					else
					{
						$this->db_operations->delete_record('account_master', array('acc_id' => $acc_id));
						// $this->Dhiaanmdl->dhiaan_delete_record('account_master', array('acc_id' => $acc_id));
					}
				}
				else if($record[0]['acc_grp_id'] == 23)
				{
					$cnt = $this->db_operations->get_cnt('challan_master', ['cm_broker_id'=>$acc_id]);
					if($cnt != 0)
					{
						echo 2;
					}
					else
					{
						$this->db_operations->delete_record('account_master', array('acc_id' => $acc_id));
						// $this->Dhiaanmdl->dhiaan_delete_record('account_master', array('acc_id' => $acc_id));
					}
				}
				else
				{
					echo 2;
				}


			}

		} else {
			redirect('loginctrl/logout');
		}
	}
/*/Account Master */

/*diamond master*/

    public function diamond_master()
	{
		if(sessionExist())
		{
			$checked = $this->input->post();
			if(!empty($checked['check_flag']))
			{
	        	$check_flags = implode(',', $checked['check_flag']);
	        }
	        else
	        {
	        	$check_flags = null;
	        }
			$config 				= array();
			$config 				= $this->config->item('pagination');
			$config['total_rows'] 	= $this->Mastermdl->get_all_diamond_data_cnt();
			$config['base_url'] 	= base_url("master/masterctrl/diamond_master?search=true");
			foreach ($_REQUEST as $key => $value)
			{
				if($key != 'search' && $key != 'offset')
				{
					if(is_array($value))
					{
						foreach ($value as $k => $v)
						{
							// echo "<pre>"; print_r($key);exit;

							$config['base_url'] .= "&" . $key. "%5B%5D=" .$v;
						}
					}
					else
					{
						$config['base_url'] .= "&" . $key . "=" .$value;
					}


				}
			}
			// echo "<pre>"; print_r($config); exit;
			$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->Mastermdl->get_all_diamond_data($config['per_page'],$offset,$check_flags);
			// echo "<pre>"; print_r($record['data']); exit();
			if(isset($_REQUEST['submit']) && $_REQUEST['submit'] == 'excel')
	        {
	        	// echo $check_flags;
	        	// exit;

	        	$record = $this->Mastermdl->get_all_diamond_data($config['per_page'],$offset, $check_flags);
	        	
	        	
	            $this->diamond_master_excel($record['excel_array']);
	        }
	        // echo "<pre>"; print_r($record); exit();
	        $this->load->view('pages/master/diamond_master', $record);

		}
		else
		{
			redirect('loginctrl/logout');
		}
	}
	
	public function import_diamond() 
	{
		if(sessionExist()) {
			$form_data = $this->input->post();
			$file_data = $_FILES;
			// echo "<pre>";print_r($form_data);
			// echo "<pre>";print_r($file_data);exit;

			if($file_data['diamond_import']['error'] == 0)
			{
				unset($config);
				$config = array();
				$config['upload_path']   = 'public/uploads/rapnet/';
				$config['allowed_types'] = 'xlsx|xls';
				$config['detect_mime']   = 'TRUE';
				$config['remove_spaces'] = 'TRUE';

				$file_name 	= trim($file_data['diamond_import']['name']);
				$ext 		= strtolower(substr($file_name, strrpos($file_name, '.') + 1));
				$filename 	= time().'.'.$ext;

				$config['file_name'] = $filename;

				$this->upload->initialize($config);

				if(!$this->upload->do_upload('diamond_import'))
				{
					$errors = $this->upload->display_errors();
					$record_array['error'] = $errors;
				}
				else
				{
					$filepath 	= "./public/uploads/rapnet/".$filename;

					// Identify the file type
					$inputFileType = IOFactory::identify($filepath);
					$reader = IOFactory::createReader($inputFileType);
					// Load the spreadsheet
					$spreadsheet = $reader->load($filepath);
					$sheet = $spreadsheet->getActiveSheet();
					// $arrayCount 	= count($sheet);
			
    				$data_array 	= [];
    				foreach ($sheet->getRowIterator() as $row)
					{

						if($row->getRowIndex() > 1)
						{
							$cellIterator = $row->getCellIterator();
							$cellIterator->setIterateOnlyExistingCells(false);
							foreach ($cellIterator as $cell)
							{
							   	//$cell->getRow().$cell->getColumn().$cell->getValue();
								$data_array[$cell->getRow()][$cell->getColumn()] = trim($cell->getFormattedValue(), " ");
								// echo "<pre>"; print_r($data_array); exit;
							}
						}
					}
								// echo "<pre>"; print_r($data_array); exit;

					$flag 			= 1;
					$add_cnt 		= 0;
					$edit_cnt 		= 0;
					$not_add_cnt 	= 0;
					$response 		= [];
					if(isset($data_array) && is_array($data_array) && !empty($data_array))
					{
						foreach ($data_array as $key => $value)
						{
							$dm_id 			= 0;
							$edit_result 	= 0;
							if((!empty($value['D']) && is_float(floatval($value['D']))))
							{
								$disc = 0;
								$code_cnt = $this->db_operations->get_cnt('diamond_master', ['dm_code'=>strval($value['B'])]);
								// echo "<pre>"; print_r($code_cnt); exit;
								$code_cnt = 0;
								if($code_cnt == 0) // add
								{
									if(!empty($value['S']))
									{
										if (strpos($value['S'], '.') !== false)
                                   		{
										   	$disc = $value['S'] * 100;
								
										}

									}
										$diamond_data = [];
								
    							    	$diamond_data['dm_date']			= !empty($value['A']) ? date('Y-m-d', strtotime($value['A'])) : '';
										$diamond_data['dm_code'] 			= trim(strval($value['B']));
										$diamond_data['dm_price_ct']		= trim($value['C']);
										$diamond_data['dm_pc_amt']			= trim($value['D']);
										$diamond_data['dm_dollar']			= trim($value['E']);
										$diamond_data['dm_dollar_amt']		= trim($value['F']);
										$diamond_data['dm_size']			= trim($value['G']);
										$diamond_data['dm_pcs']				= trim($value['H']);
										$diamond_data['dm_cpd']				= trim($value['I']);
										$diamond_data['dm_sh']				= strtoupper(trim($value['J']));
										$diamond_data['dm_lab']				= trim($value['K']);
										$diamond_data['dm_cert_no']			= trim($value['L']);
										$diamond_data['dm_carat']			= trim($value['M']);
										$diamond_data['dm_col']				= trim($value['N']);
										$diamond_data['dm_cla']				= trim($value['O']);
										$diamond_data['dm_cut']				= trim($value['P']);
										$diamond_data['dm_pol']				= trim($value['Q']);
										$diamond_data['dm_sym']				= trim($value['R']);
										$diamond_data['dm_fl']				= trim($value['S']);
										$diamond_data['dm_len']				= trim($value['T']);
										$diamond_data['dm_wid']				= trim($value['U']);
										$diamond_data['dm_hei']				= trim($value['V']);
										$diamond_data['dm_nat_lab_grown']	= trim($value['W']);
										$diamond_data['dm_disc']			= trim($value['X']);
										$diamond_data['dm_rap']				= trim($value['Y']);
										$diamond_data['dm_video_link']		= trim($value['Z']);
										$diamond_data['dm_r2net']			= trim($value['AA']);
										$diamond_data['dm_suspense']		= trim($value['AB']);
    							    	
								    	$diamond_data['dm_user_id']		= $_SESSION['user_id'];
								    	$diamond_data['dm_date_create']	= date("Y-m-d H:i:s");
								    	$diamond_data['dm_update_id']	= $_SESSION['user_id'];
								    	$diamond_data['dm_date_update']	= date("Y-m-d H:i:s");

	                                // echo "<pre>"; print_r($diamond_data); exit;
							    	$dm_id = $this->db_operations->data_insert('diamond_master', $diamond_data);
							    	if(!empty($dm_id))
							    	{
							    		$add_cnt = $add_cnt + 1;
							    	}
							    	else
							    	{
							    		$flag = 0;
							    	}
								}
								else // update
								{
									$avail_cnt = $this->db_operations->get_cnt('diamond_master', ['dm_code'=>$value['B'], 'dm_status'=>0]);
									$return_cnt = $this->db_operations->get_cnt('diamond_master', ['dm_code'=>$value['B'], 'dm_status'=>4]);
									if($avail_cnt != 0 || $return_cnt != 0)
									{
										if(!empty($value['S']))
										{
											$disc = $value['S'] * 100;
								// 			$disc = $disc + 6;
										}
										$diamond_data = [];
								
										$diamond_data['dm_date']			= !empty($value['A']) ? date('Y-m-d', strtotime($value['A'])) : '';
										$diamond_data['dm_code'] 			= trim(strval($value['B']));
										$diamond_data['dm_price_ct']		= trim($value['C']);
										$diamond_data['dm_pc_amt']			= trim($value['D']);
										$diamond_data['dm_dollar']			= trim($value['E']);
										$diamond_data['dm_dollar_amt']		= trim($value['F']);
										$diamond_data['dm_size']			= trim($value['G']);
										$diamond_data['dm_pcs']				= trim($value['H']);
										$diamond_data['dm_cpd']				= trim($value['I']);
										$diamond_data['dm_sh']				= strtoupper(trim($value['J']));
										$diamond_data['dm_lab']				= trim($value['K']);
										$diamond_data['dm_cert_no']			= trim($value['L']);
										$diamond_data['dm_carat']			= trim($value['M']);
										$diamond_data['dm_col']				= trim($value['N']);
										$diamond_data['dm_cla']				= trim($value['O']);
										$diamond_data['dm_cut']				= trim($value['P']);
										$diamond_data['dm_pol']				= trim($value['Q']);
										$diamond_data['dm_sym']				= trim($value['R']);
										$diamond_data['dm_fl']				= trim($value['S']);
										$diamond_data['dm_len']				= trim($value['T']);
										$diamond_data['dm_wid']				= trim($value['U']);
										$diamond_data['dm_hei']				= trim($value['V']);
										$diamond_data['dm_nat_lab_grown']	= trim($value['W']);
										$diamond_data['dm_disc']			= trim($value['X']);
										$diamond_data['dm_rap']				= trim($value['Y']);
										$diamond_data['dm_video_link']		= trim($value['Z']);
										$diamond_data['dm_r2net']			= trim($value['AA']);
										$diamond_data['dm_suspense']		= trim($value['AB']);
    							    	
								    	$diamond_data['dm_user_id']		= $_SESSION['user_id'];
								    	$diamond_data['dm_date_create']	= date("Y-m-d H:i:s");
								    	$diamond_data['dm_update_id']	= $_SESSION['user_id'];
								    	$diamond_data['dm_date_update']	= date("Y-m-d H:i:s");

								    	$edit_result = $this->db_operations->data_update('diamond_master', $diamond_data, 'dm_code', $value['B']);

								    	if(!empty($edit_result))
								    	{
								    		$edit_cnt = $edit_cnt + 1;
								    	}
								    	else
								    	{
								    		$flag = 0;
								    	}
									}
									else
									{
										$dm_data = $this->db_operations->get_record('diamond_master', ['dm_code'=>$value['B'], 'dm_status !='=>0]);

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

										$response['not_added'][$dm_data[0]['dm_id']]['dm_code'] = $dm_data[0]['dm_code'];
										$response['not_added'][$dm_data[0]['dm_id']]['dm_status'] = $dm_data[0]['dm_status'];

										$not_add_cnt = $not_add_cnt + 1;
									}
								}
							}
						}

						if($flag == 1)
						{
							if ($this->db->trans_status() === FALSE)
							{
							    $this->db->trans_rollback();
							    $response['resp'] = 0;
								$response['add_cnt'] = 0;
								$response['edit_cnt'] = 0;
								$response['not_add_cnt'] = 0;

							}
							else
							{
							    $this->db->trans_commit();
							    $response['resp'] = 1;
								$response['add_cnt'] = $add_cnt;
								$response['edit_cnt'] = $edit_cnt;
								$response['not_add_cnt'] = $not_add_cnt;
							}
						}
						else
						{
							$this->db->trans_rollback();
						    $response['resp'] = 0;
							$response['add_cnt'] = 0;
							$response['edit_cnt'] = 0;
							$response['not_add_cnt'] = 0;
						}

						echo json_encode($response);
					}
					else
					{
						// echo 2;
						$response['resp'] = 2;
						$response['add_cnt'] = $add_cnt;
						$response['edit_cnt'] = $edit_cnt;
						$response['not_add_cnt'] = $not_add_cnt;

						echo json_encode($response);
					}
				}
			}
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}

	public function get_single_diamond($dm_id) {
		$data = $this->Mastermdl->get_by_id($dm_id);
		echo json_encode($data);
	}

	public function save_diamond($dm_id)
{
    $post = $this->input->post();
    $code = trim($post['rg_dm_code']);

    // 🔍 1. CHECK IF STOCK ID EXISTS
    if ($this->Mastermdl->diamond_code_exists($code, $dm_id)) {
        echo json_encode([
            'status' => 'error',
            'message' => 'STOCK ID already exists. Please use a different one.'
        ]);
        return;
    }

    // 🆕 2. NEW ENTRY
    if ($dm_id == 0) {

        $new_id = $this->Mastermdl->diamond_add($post);

        $resp = [
            'status' => 'success',
            'message' => 'Diamond added successfully',
            'dm_id' => $new_id
        ];
    }

    // ✏️ 3. UPDATE ENTRY
    else {

        $this->Mastermdl->diamond_edit($dm_id, $post);

        $resp = [
            'status' => 'success',
            'message' => 'Diamond updated successfully',
            'dm_id' => $dm_id
        ];
    }
	// echo "<pre>"; print_r($resp); exit;

    echo json_encode($resp);
}


public function diamond_master_excel($excel_array)
{
    if (!sessionExist()) {
        redirect('loginctrl/logout');
        return;
    }

    // Increase memory and execution time
    ini_set('memory_limit', '512M');
    ini_set('max_execution_time', '300');

    // Clear output buffer
    if (ob_get_length()) {
        ob_end_clean();
    }

    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle("DIAMOND MASTER");

    // Title row
    $sheet->setCellValue('N1', 'DIAMOND MASTER');
    $sheet->setCellValue('P1', date('d-m-Y'));

    $rowCount = 2;

    foreach ($excel_array as $rowData) {
        $colCount = 1;

        foreach ($rowData as $cellValue) {
            $colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colCount);
            $sheet->getColumnDimension($colLetter)->setAutoSize(true);

            $cellCoordinate = $colLetter . $rowCount;

            // Column 20 (LENGTH) as string
            if ($colCount == 20) {
                $sheet->getCell($cellCoordinate)
                      ->setValueExplicit($cellValue, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
            } else {
                $sheet->setCellValue($cellCoordinate, $cellValue);
            }

            $colCount++;
        }

        $rowCount++;
    }

	if($_REQUEST['search_value_category'] == 0){
		$category = 'NON-CERTIFIED';
	}elseif($_REQUEST['search_value_category'] == 1){
		$category = 'CERTIFIED';
	}else{
		$category = 'ALL';
	}

    // Output Excel
    $filename = 'diamond_master_'.$category.'_'. date('dMY') . '.xlsx';
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="' . $filename . '"');
    header('Cache-Control: max-age=0');
    header('Expires: 0');
    header('Pragma: public');

    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}


	public function diamond_master_excel1($record)
	{
		if(sessionExist())
		{
			// echo "<pre>";print_r($record);exit();

			$spreadsheet = new Spreadsheet();
		    $sheet = $spreadsheet->setActiveSheetIndex(0);
            $sheet->setTitle("DIAMOND MASTER");
            $sheet->setCellValue('A1', date('d-m-Y'));
            $sheet->setCellValue('N1', 'DIAMOND MASTER');

            $sheet->setCellValue('B2', 'STOCK ID');
            $sheet->setCellValue('C2', 'SH');
            $sheet->setCellValue('D2', 'WT');
            $sheet->setCellValue('E2', 'COL');
            $sheet->setCellValue('F2', 'CLA');
            $sheet->setCellValue('G2', 'CUT');
            $sheet->setCellValue('H2', 'POL');
            $sheet->setCellValue('I2', 'SYM');
            $sheet->setCellValue('J2', 'FL');
            $sheet->setCellValue('K2', 'LAB');
            $sheet->setCellValue('L2', 'DISC');
            $sheet->setCellValue('M2', 'RAP');
            $sheet->setCellValue('N2', 'FROM TO DOLLAR');
            $sheet->setCellValue('O2', 'FROM TO PRICE/CRT');



            $rowCount = 5;
            foreach ($record as $key => $data)
            {
            	if($key == 0)
            	{
            		/*SET COLUMN WIDTH AND DATA*/
	                foreach(range('A','S') as $key => $columnID)
	                {
	                	/*set coulumn width*/
	                    $sheet->getColumnDimension($columnID)->setAutoSize(true);

	                    /*set column data*/
	                    $sheet->SetCellValue($columnID.$rowCount, $data[$key]);
	                }
            	}
            	else
            	{
            		/*SET COLUMN WIDTH AND DATA*/
	                foreach(range('A','S') as $key => $columnID)
	                {
	                	/*set coulumn width*/
		                    $sheet->getColumnDimension($columnID)->setAutoSize(true);

		                    /*set column data*/
		                    $sheet->SetCellValue($columnID.$rowCount,$data[$key]);

	                }
	                // exit();
            	}

                $rowCount++;
            }
            // exit;
            $filename='diamond_master_'.date('dMY').'.csv'; //save our workbook as this file name
            header('Content-Type: application/vnd.ms-excel'); //mime type
            header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
            header('Cache-Control: max-age=0'); //no cache
            // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
            $objWriter = new Xlsx($spreadsheet);
            // Write the Excel file to filename some_excel_file.xlsx in the current directory
            $objWriter->save('php://output');


		}
		else
		{
			redirect('loginctrl/logout');
		}
	}
	public function update_dollar_ppc()
	{
		$diamond_db_data = $this->db_operations->get_recordlist('diamond_master');
		$flag = 0;
		// echo "<pre>"; print_r($diamond_data); exit();
		foreach ($diamond_db_data as $key => $value)
		{
			if(strtoupper($value['dm_lab']) == 'GIA')
            {
                $sub_total = $value['dm_wt'] * $value['dm_rap'];

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

                $disc_amt = ($sub_total * $disc)/100;
                $diamond_data['dm_dollar'] = $sub_total - $disc_amt;
                $diamond_data['dm_price_ct'] = $diamond_data['dm_dollar'] / $value['dm_wt'];


            }
            elseif(strtoupper($value['dm_lab']) == 'IGI' || strtoupper($value['dm_lab']) == 'HRD')
            {
                $sub_total = $value['dm_wt'] * $value['dm_rap'];

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

                $disc_amt = ($sub_total * $disc)/100;
                $total_dollar = $sub_total - $disc_amt;

                $disc_amt = ($total_dollar * 2) / 100;
                $diamond_data['dm_dollar'] = $total_dollar - $disc_amt;
                $diamond_data['dm_price_ct'] = $diamond_data['dm_dollar'] / $value['dm_wt'];
            }
            else
            {
                $diamond_data['dm_dollar'] = 0;
                $diamond_data['dm_price_ct'] = 0;
            }

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

	    	if($result < 1)
	    	{
	    		$flag = 1;
	    	}
		}
		if($flag == 0)
		{
			echo "Data update successfully";
		}
		else
		{
			echo "Data not update successfully";
		}
	}

	public function diamond_delete($dm_id)
	{
		if(sessionExist()) {
			$cnt = $this->db_operations->get_cnt('diamond_master', ['dm_id'=>$dm_id, 'dm_status'=>0]);
			if($cnt != 0)
			{
				$this->db_operations->delete_record('diamond_master', array('dm_id' => $dm_id));
			}
			else
			{
				echo 2;
			}

		} else {
			redirect('loginctrl/logout');
		}
	}

	public function get_challan_data()
	{
		if(sessionExist()) {
			// echo "<pre>"; print_r($_GET); exit;
			$record = $this->Mastermdl->get_challan_data($_GET['dm_id'], $_GET['ct_id']);
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function get_challan_return_data()
	{
		if(sessionExist()) {
			// echo "<pre>"; print_r($_GET); exit;
			$record = $this->Mastermdl->get_challan_return_data($_GET['dm_id'], $_GET['crt_id']);
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function set_r2net()
	{
		if(sessionExist())
		{
			$r2net = $_GET['r2net'] == 0 ? 1 : 0;
			echo json_encode($this->db_operations->data_update('diamond_master', ['dm_r2net' => $r2net], 'dm_id', $_GET['dm_id']));
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}

	public function set_suspense()
	{
		if(sessionExist())
		{
			$suspense = $_GET['suspense'] == 0 ? 1 : 0;
			echo json_encode($this->db_operations->data_update('diamond_master', ['dm_suspense' => $suspense], 'dm_id', $_GET['dm_id']));
		}
		else
		{
			redirect('loginctrl/logout');
		}
	}

/*/diamond master*/

/* RapaPort Master */
	public function rapaport_master()
	{
		if(sessionExist()) {

			$config = array();
			$this->config->load('extra');
			$config = $this->config->item('pagination');
			$config['per_page'] = 10;

			$config['total_rows'] = $this->Mastermdl->get_rapaport_data_count();
			$config['base_url']   = base_url('master/masterctrl/rapaport_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['search_data'] 		= $this->config->item('rapaprt_search');
			$record['data'] 	= $this->Mastermdl->get_rapaport_data($config['per_page'],$offset);
			// echo "<pre>";print_r($record);exit();
			$this->load->view('pages/master/rapaport_master', $record);
		} else {
			redirect('loginctrl/logout');
		}
	}

/* /RapaPort Master */


/*Group master*/
	public function group_master()
	{
		if(sessionExist()) {
			$record['group_data'] = $this->db_operations->get_recordlist("group_master");

			$this->load->view('pages/master/group_master', $record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function group_insert($grp_id)
	{
		if(sessionExist())
		{
			$form_data = $this->input->post();
			// echo "<pre>";print_r($form_data);exit();
			if($grp_id == 0)
			{
				$cnt = $this->db_operations->get_cnt('group_master', array('grp_name' => $form_data['grp_name']));
				if ($cnt != 0)
				{
					echo 2;
				}
				else
				{
					$form_data['grp_user_id'] 	  = $_SESSION['user_id'];;
					$form_data['grp_update_id']   = $_SESSION['user_id'];;
					$form_data['grp_date_create'] = date("Y-m-d H:i:s");

					$result = $this->db_operations->data_insert('group_master', $form_data);
					echo (!empty($result)) ? 1 : 0;
				}
			}
			else
			{
				$cnt = $this->db_operations->get_cnt('group_master', array('grp_name' => $form_data['grp_name'], 'grp_id !=' => $grp_id));
				if ($cnt != 0)
				{
					echo 2;
				}
				else
				{
					$form_data['grp_update_id'] = $_SESSION['user_id'];;
					echo $this->db_operations->data_update('group_master', $form_data, 'grp_id', $grp_id);
				}
			}
		}
		else
		{
			redirect('loginctrl/logout');
		}



		$user_id = $this->session->userdata('user_id');

		if(!empty($user_id)){


		}
		else
			$this->load->view('pages/login');
	}


	public function get_dealers()
	{
		if(sessionExist()) {
			$record = array();
			echo json_encode($record);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function get_single_group($grp_id){
		if(sessionExist()) {
			$record = $this->db_operations->get_record("group_master", array("grp_id" => $grp_id));
			echo json_encode($record);

		} else {
			redirect('loginctrl/logout');
		}

	}

	public function group_delete($grp_id)
	{
		if(sessionExist()) {
			$this->db_operations->delete_record('group_master', array('grp_id' => $grp_id));
		} else {
			redirect('loginctrl/logout');
		}
	}
/*/group master*/
// =========== PRODUCT MASTER ===========

	public function product_master()
	{
		if(sessionExist()) {
			$data['product'] = $this->db_operations->get_recordlist("product_master");
			$this->load->view('pages/master/product_master', $data);
		} else {
			redirect('loginctrl/logout');
		}
	}

	public function pro_insert($pro_id)
	{
		if(sessionExist())
		{
			$form_data = $this->input->post();
			if($pro_id == 0)
			{
				$cnt = $this->Mastermdl->get_cnt('product_master',array("pro_name"=>$form_data['pro_name']));

				if($cnt != 0)
				{
					echo 2;
				}
				else
				{
					$form_data['pro_user_id'] = $_SESSION['user_id'];;
					$form_data['pro_update_id'] = $_SESSION['user_id'];;
					$form_data['pro_date_create'] = date("Y-m-d H:i:s");
					
					$result = $this->db_operations->data_insert("product_master",$form_data);
					if($result != '')
					{
						echo 1;
					}
					else
					{
						echo 0;
					}
				}
			}
			else
			{
				$cnt = $this->Mastermdl->get_cnt("product_master",array("pro_name"=>$form_data['pro_name'],"pro_id"=>$pro_id),array(0=>'pro_name',1=>'pro_id'));
				
				if($cnt[0]['cnt']!= 0)
				{
					echo 2;
				}
				else
				{
					$form_data['pro_update_id'] = $_SESSION['user_id'];;
					$form_data['pro_update_date'] = date("Y-m-d H:i:s");
					
					echo $this->db_operations->data_update('product_master',$form_data,'pro_id',$pro_id);
				}
			}
		}
		else
		{
			$this->load->view('pages/login');
		}
	}

	public function get_single_pro($pro_id)
	{
		if(sessionExist())
		{
			$record = $this->db_operations->get_record('product_master',array("pro_id"=>$pro_id));
			echo json_encode($record);
		}
		else
		{
			$this->load->view('pages/login');
		}
	}

	public function product_delete($pro_id)
	{
		if(sessionExist()) {
			$this->db_operations->delete_record('product_master', array('pro_id' => $pro_id));
		} else {
			redirect('loginctrl/logout');
		}
	}
	
	/******************************************************************/
	// 		LABEL PRINT

	public function label_print($id)
	{
		if(sessionExist())
		{
			$record['diamond'] = $this->Mastermdl->get_diamond_data($id);
			$this->load->view('pdfs/label_print', $record);	
		} else 
		{
			redirect('loginctrl/logout');
		}
	}

    public function diamond_delete_data($dm_id)
	{
		if(sessionExist()) {
			$cnt = $this->db_operations->get_cnt('diamond_master', ['dm_id'=>$dm_id, 'dm_status'=>0]);
			if($cnt != 0)
			{
				echo json_encode($this->db_operations->delete_record('diamond_master', array('dm_id' => $dm_id)));
			}
			else
			{

				 return false;
			}

		} else {
			redirect('loginctrl/logout');
		}
	}


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


}
	
?>