<?php
class Login extends CI_Controller
{
	function __construct()
	{
		parent::__construct();
	}

	function index()
	{
		if($this->Employee->is_logged_in())
		{
			$this->opening_balance_generate();
			redirect('/sales');
		}
		else
		{
			$this->form_validation->set_rules('username', 'lang:login_undername', 'callback_login_check');
			$this->form_validation->set_error_delimiters('<div class="error">', '</div>');

			if($this->form_validation->run() == FALSE)
			{
				$this->load->view('login');
			}
			else
			{
				$this->create_stock_moves_reprint();
				$this->opening_balance_generate();
				redirect('/sales');
			}

		}
	}

	function create_stock_moves_reprint(){
		
		//$sql_drop="DROP TABLE IF EXISTS `stock_moves_reprint`";
		//$this->db->query($sql_drop);

		$sql_create="CREATE TABLE IF NOT EXISTS `stock_moves_reprint` (
  `trans_id` int(11) NOT NULL AUTO_INCREMENT,
  `stock_id` char(20) NOT NULL DEFAULT '',
  `loc_code` char(5) NOT NULL DEFAULT '',
  `price` double NOT NULL DEFAULT '0',
  `standard_cost` double NOT NULL DEFAULT '0',
  `visible` tinyint(1) NOT NULL DEFAULT '1',
  `lot_no` int(10) DEFAULT '0',
  `is_imported` smallint(6) NOT NULL DEFAULT '0',
  `swatch_code` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`trans_id`))";
		$this->db->query($sql_create);


		$count_query=$this->db->query("SELECT COUNT(*) AS total_data FROM stock_moves_reprint");

		$count=$count_query->row()->total_data;
		if(intval($count)==0){
			$query_moves = $this->db->query("SELECT 
		stock_id,
		  loc_code,
		  price,
		  standard_cost,
		  visible,
		  lot_no,
		  is_imported,
		  swatch_code
		  FROM stock_moves AS a WHERE price!=0 AND standard_cost!=0
		  GROUP BY a.stock_id,a.price ORDER BY a.price ASC,a.lot_no DESC");

			$insert_query="INSERT INTO stock_moves_reprint (
		stock_id,
		  loc_code,
		  price,
		  standard_cost,
		  visible,
		  lot_no,
		  is_imported,
		  swatch_code) VALUES
		";

			foreach ($query_moves->result() as $row_compare) {
				$row_compare_implode=array();
				foreach ($row_compare as $key => $value) {
					$row_compare_implode[]=$value;
				}
				if(count($row_compare_implode)){
					$insert_query.='(';
					$insert_query.="'".implode("','",$row_compare_implode)."'";
					$insert_query.='),';
				}
			}

			$insert_query=substr($insert_query, 0, -1)."";
			$this->db->query($insert_query);
		}
	}

	function getData_shawpon_opening_range_all($start_date)
	{

		$sql_item="SELECT b.stock_id,b.description,
IF(b.item_size_id> 0, CONCAT(b.stock_id,' - ',b.description,' - ',p.size), CONCAT(b.stock_id,' - ',b.description)) AS item_description,
IF(b.item_size_id> 0,p.size, '') AS item_size,
a.description AS cat_description,
b.category_id,
b.gender

FROM stock_master AS b
LEFT JOIN stock_category AS a ON a.category_id=b.category_id
LEFT JOIN pos_item_sizes AS p ON b.item_size_id=p.id
WHERE b.no_sale=0 ";

		$item_inventory_array=array();
		$stock_ids=array();

		$query = $this->db->query($sql_item);
		foreach ($query->result() as $row) {
			$item_inventory_array[$row->stock_id]=$row;
			$stock_ids[]=$row->stock_id;
		}

		$str="'".implode("','",$stock_ids)."'";


		$sql="SELECT
c.stock_id,
c.lot_no,
SUM(c.qty) AS sum_qty,
c.price,
c.standard_cost,
c.type

FROM stock_moves AS c 
WHERE c.loc_code='".LOCATION_CODE."' AND c.tran_date<'".$start_date."' AND c.receive_date<'".$start_date."' AND c.stock_id!='' AND c.stock_id IN(".$str.") AND c.qty !=0  GROUP BY stock_id,lot_no,c.price ,c.type ORDER BY c.stock_id ASC,c.lot_no ASC,c.price ASC";


		$report_data_current_inventory=array();///////////////////////////////////////
		$latest_price=array();

		$search_perice_array=array();

		$sql_search="SELECT stock_id,price,lot_no,standard_cost FROM stock_moves_of_edit_data
							 ORDER BY  edit_date ASC ";

		$result_search =$this->db->query($sql_search);


		foreach ($result_search->result() as $row_search) {
			$search_perice_array[$row_search->stock_id][$row_search->lot_no]=$row_search->price;
		}

		$stock_in_array=array();
		$stock_out_array=array();

		$query = $this->db->query($sql);
		foreach ($query->result() as $row) {

			if (array_key_exists($row->stock_id,$item_inventory_array)){
				if($row->type!='201'){//////////////MODYFY/////////////////
					$search_perice=0;
					if(isset($search_perice_array[$row->stock_id][$row->lot_no])){
						$search_perice=intval($search_perice_array[$row->stock_id][$row->lot_no]);
						if($search_perice!=0){
							$row->price=$search_perice;
						}
					}
					if(isset($stock_in_array[$row->stock_id.$row->lot_no])){
						if($stock_in_array[$row->stock_id.$row->lot_no]>=$row->price){
							$stock_in_array[$row->stock_id.$row->lot_no]=$row->price;
						}
					}else{
						$stock_in_array[$row->stock_id.$row->lot_no]=$row->price;
					}
				}else{
					$stock_out_array[$row->stock_id.$row->lot_no]=$row->price;
				}
				$row->description=trim($item_inventory_array[$row->stock_id]->description);
				$row->cat_description=trim($item_inventory_array[$row->stock_id]->cat_description);
				$row->category_id=trim($item_inventory_array[$row->stock_id]->category_id);
				$row->gender=trim($item_inventory_array[$row->stock_id]->gender);
				$report_data_current_inventory[]=$row;

			}
		}


		$stock_items_gender = array(
		'fabric' => _("Fabric"),
		'male' => _("Male"),
		'female' => _("Female"),
		'boy' => _("Boy"),
		'girl' => _("Girl"),
		'newlook' => _("New Look"),
		'others' => _("Others"),
		'' => _("Miscellaneous"),
		'school' => _("School Fabric"),
		);


		$unique_items_temp=array();
		$unique_items=array();



		foreach ($report_data_current_inventory as $key => $value) {
			$input_price=0;
			if(isset($stock_in_array[$value->stock_id.$value->lot_no])){
				$input_price=intval($stock_in_array[$value->stock_id.$value->lot_no]);

			}else{
				$input_price=intval($stock_out_array[$value->stock_id.$value->lot_no]);
			}
			$unique_items_temp[$stock_items_gender[$value->gender]][$value->cat_description][$value->description]['qty_total']+=$value->sum_qty;
			$unique_items_temp[$stock_items_gender[$value->gender]][$value->cat_description][$value->description]['price_total']+=number_format($value->sum_qty*$input_price,2,".","");
		}

		return $unique_items_temp;

	}

	function summary_stock_transactions_for_sms_today($start_date, $end_date){
		$receive_qty=0;
		$receive_price=0;
		$opening_qty=0;
		$opening_price=0;

		$query = $this->db->query("SELECT SUM(b.qty) AS qty,b.price
FROM stock_moves AS b
WHERE b.loc_code='".LOCATION_CODE."' AND b.receive_date='".$start_date."' AND b.receive_qty>0
GROUP BY b.stock_id,b.lot_no,b.price");

		foreach ($query->result() as $row) {
			$receive_qty+= $row->qty;
			$receive_price+= ($row->qty*$row->price);
		}

		//	$this->load->model('reports/Summary_sales');
		//$model = $this->Summary_sales;
		$report_data_opening = $this->getData_shawpon_opening_range_all($start_date);


		foreach ($report_data_opening as $key_gender => $value_gender) {
			foreach ($value_gender as $key_cat_description => $value_cat_description) {
				foreach ($value_cat_description as $key_description => $value_description) {
					$opening_qty+=$value_description['qty_total'];
					$opening_price+=number_format($value_description['price_total'],2,".","");
				}
			}
		}
		$data['receive_qty']=$receive_qty;
		$data['receive_price']=$receive_price;
		$data['opening_qty']=$opening_qty;
		$data['opening_price']=$opening_price;
		return $data;
	}

	function opening_balance_generate(){
		$filename_for_save="opening_balance_".date("Y_m_d").".txt";
		$filename = "pdf_report/report_file_runtime/".$filename_for_save;
		if (!file_exists($filename)) {


			$dir="pdf_report/report_file_runtime";
			$dirHandle = opendir($dir);
			while ($file = readdir($dirHandle)) {
				if($file!="index.php") {
					$str_pos=strpos($file,'ing_balance_');
					if($str_pos>0){
						if($file!=$filename) {
							unlink($dir."/".$file);
						}
					}
				}
			}
			closedir($dirHandle);


			$current_date=date("Y-m-d");
			$transaction_data=$this->summary_stock_transactions_for_sms_today($current_date,$current_date);

			/*	last year	*/
			$last_year_total_sale=0;
			$last_year_total_qty=0;
			$lastYear = date("Y-m-d", strtotime("-1 years"));

			$sql_sales="SELECT  SUM(vat_enable_price) AS total_sale_amount,SUM(quantity_purchased) As total_qty FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$lastYear."' AND location='".LOCATION_CODE."')";

			$query_sale = $this->db->query($sql_sales);
			foreach ($query_sale->result() as $row) {
				$last_year_total_sale=$row->total_sale_amount;
				$last_year_total_qty=$row->total_qty;
			}
			$data['stock_in_qty']=$transaction_data['receive_qty'];
			$data['stock_in_amount']=$transaction_data['receive_price'];
			$data['opening_qty']=$transaction_data['opening_qty'];
			$data['opening_amount']=$transaction_data['opening_price'];
			$data['last_year_total_sale']=$last_year_total_sale;
			$data['last_year_total_qty']=$last_year_total_qty;


			$obj=fopen($filename, 'w');
			fwrite($obj, print_r(serialize($data), TRUE));
			fclose($obj);
		}
		return true;
	}


	function login_check($username)
	{
		$password = $this->input->post("password");

		if(!$this->Employee->login($username,$password))
		{
			$this->form_validation->set_message('login_check', $this->lang->line('login_invalid_username_and_password'));
			return false;
		}
		return true;
	}
}
?>