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

class Outlet extends CI_Controller {

	function __construct()
    {
        parent::__construct();
        error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
        
        $tastname = $this->uri->segment("2");
        
        if($tastname!="" && $tastname!="checklogin")
        {
			if(!$this->session->userdata('outlettLoggedIn'))
			{
				redirect("outlet");
				exit;
			}
		}

		$this->lguserinfo = $this->session->userdata('outlettLoggedIn');
		$this->clientid = $this->lguserinfo["sessCLIENTID"];
		$this->company = $this->lguserinfo["sessCompanyname"];
		$this->outletid = $this->lguserinfo["sessOUTLETID"];		
		$this->outletname = $this->lguserinfo["sessOTLName"];
		$this->userid= $this->lguserinfo["sessID"];
		$this->load->model('outlet_model');
		$this->load->model('common_model');
		$this->load->library('Ajax_pagination');
		$this->load->library("email");
		$this->perPage = 100;
		
    }

	function index()
	{
		if($this->session->userdata('outlettLoggedIn'))
		{
			redirect("outlet/dashboard");
		}
		else
		{
			$this->load->view('outlet/login');
		}
	}
	function dashboard()
	{
		if($this->session->userdata('outlettLoggedIn'))
		{
			$data['main_content'] = 'dashboard';
			$this->load->view('outlet/common/main.inc.php',$data);
		}
		else
		{
			$this->load->view('outlet/login');
		}
	}
	function checklogin()
	{
		if($this->session->userdata('outlettLoggedIn'))
		{
			redirect("outlet/dashboard");
		}
		else
		{
			$username = $this->input->post("username");
			$userpass = $this->input->post("userpass");
			if($username!="" && $userpass!="")
			{
				if($this->outlet_model->checklogin()==true)
				{
					redirect("outlet/dashboard");
				}
				else
				{
					$this->session->set_flashdata("message", "Invalid username or password!");
					$this->session->set_flashdata("msgclass", "alert-danger");
					redirect("outlet");
					exit;
				}
			}
			else
			{
				redirect("outlet");
				exit;
			}
		}
	}
/* admin defaults */
	function delcomm()
	{
		if($this->lguserinfo["sessType"]=="manager")
		{
			$tablnameprefix = $this->uri->segment(3);
			$rsrcid = $this->uri->segment(4);
			if($rsrcid!="" && $tablnameprefix!="")
			{
				$rsrcid = decodeValue($rsrcid);
				$tablname = $tablnameprefix;
				if($result = $this->common_model->delcomm($rsrcid, $tablname))
				{
					$this->session->set_flashdata('message',"Info. deleted succesfully!");
					$this->session->set_flashdata('alerttype',"alert-success");
				}
				else
				{
					$this->session->set_flashdata('message',"Something went wrong, please try again!");
					$this->session->set_flashdata('alerttype',"alert-danger");
				}
			}
			else
			{
				$this->session->set_flashdata('message',"Something went wrong, please try again!");
				$this->session->set_flashdata('alerttype',"alert-danger");
			}
			redirect($this->agent->referrer());
			exit;
		}
		else
		{
			$this->load->view("outlet");
		}
	}


	
    
	function updateinfo()
	{
		$data["info4edit"] = $this->common_model->getinfo($this->lguserinfo["sessID"], "users");
		$data["pgheading"] = "Update Info.";
		$data['main_content'] = "updateinfo";
		$this->load->view('outlet/common/main.inc.php',$data);
	}

	function manageupdate()
	{
		$rsrcid = $this->input->post("rsrcid");
		$name = $this->input->post("name");
		$email = $this->input->post("email");
		$mobile = $this->input->post("mobile");
		if($rsrcid>0 && $name!="" && $email!="" && $mobile!="")
		{
			$data = array(
				"fld_name" => $name,
				"fld_email" => $email,
				"fld_mobile" => $mobile,
"fld_updatedby" => $this->lguserinfo["sessID"],
"fld_updatedon" => date("Y-m-d H:i:s")
			);
			$resourceid = $this->common_model->managedata($data, "users", $rsrcid);
			if($resourceid>0)
			{
				$this->session->set_flashdata("message","Info. successfully updated!");
				$this->session->set_flashdata('alerttype',"alert-success");
			}
			else
			{
				$this->session->set_flashdata("message","Sorry, something went wrong, please try again!");
				$this->session->set_flashdata('alerttype',"alert-danger");
			}
		}
		else
		{
			$this->session->set_flashdata("message", "Please fill mandatory fields!");
			$this->session->set_flashdata('alerttype', "alert-danger");
		} 
		redirect("outlet/updateinfo");
		exit;
	}	

	function changepass()
	{
		$data["pgheading"] = "Change Password";
		$data['main_content'] = "changepass";
		$this->load->view('outlet/common/main.inc.php',$data);
	}

	function managepass()
	{
		$currpass = $this->input->post("currpass");
		$userpass = $this->input->post("userpass");
		$cuserpass = $this->input->post("cuserpass");
		if($currpass!="" && $userpass!="" && $cuserpass!="")
		{
			if($userpass==$cuserpass)
			{
				$data = array(
					"fld_userpass" => md5($userpass)
				);
				$responsecode = $this->outlet_model->manageuserpass($data, $currpass);
				if($responsecode=="success")
				{
					$this->session->set_flashdata("message","Password successfully changed!");
					$this->session->set_flashdata('alerttype',"alert-success");
				}
				elseif($responsecode=="notmatched")
				{
					$this->session->set_flashdata("message","Current password not matched, try again!");
					$this->session->set_flashdata('alerttype',"alert-danger");
				}
				else
				{
					$this->session->set_flashdata("message","Something went wrong, try again!");
					$this->session->set_flashdata('alerttype',"alert-danger");
				}
			}
			else
			{
				$this->session->set_flashdata("message", "New password and confirm password not matched, try again!");
				$this->session->set_flashdata('alerttype', "alert-danger");
			}
		}
		else
		{
			$this->session->set_flashdata("message", "Please fill mandatory fields!");
			$this->session->set_flashdata('alerttype', "alert-danger");
		} 
		redirect("outlet/changepass");
		exit;
	}

    function changestatus()
    {
		$pid = $this->input->post("pid");
		$stype = $this->input->post("stype");
		$status = $this->input->post("status");
		$newstatus = "";
		$addstatus = "";
		if($pid!="" && $stype!="" && $status!="")
		{
			if($status == "active")
			{
				$newstatus = "inactive";
				$addstatus = "no";
			}
			elseif($status == "inactive")
			{
				$newstatus = "active";
				$addstatus = "yes";
			}
			$data = array(
			   'fld_status' => $newstatus
			);
			
			$tablename = "tbl_" . $stype;
			$this->db->where('fld_id',$pid);
			$this->db->update($tablename, $data);
		}
		echo trim($newstatus);
	}	

	function logout()
	{
        $last_login = date('Y-m-d H:i:s');
        $last_login_ip = $_SERVER['REMOTE_ADDR'];
        $admuserid = $this->session->userdata('outlettLoggedIn')['sessID'];
                
        $data = array(
            'fld_lastlogin' => $last_login,
            'fld_lastloginip'   => $last_login_ip
        );
		
		$this->db->where('fld_id',$admuserid);
        $this->db->update('tbl_users',$data);
		$this->session->unset_userdata('outlettLoggedIn');
		redirect("outlet");
		exit;
	}
	/* end admin defaults */

	/* start mgmt functions*/
	function gifts()
	{
		$mgmtname = 'gifts';
		$tasktype = $this->uri->segment("3");
		if($tasktype=="manage")
		{
			$rsrcid = $this->uri->segment("4");
			$data["pgheading"] = "Add Gift";
			$data["rsrcid"] = 0;
			if($rsrcid!="")
			{
				$rsrcid = decodeValue($rsrcid);
				if($data["info4edit"] = $this->common_model->getinfo($rsrcid, $mgmtname))
				{
					$data["rsrcid"] = $rsrcid;
					$data["pgheading"] = "Modify Gift Info.";
				}
			}
			$data["productlist"] = $this->common_model->getprodlistbycattype('gift');
				
			$data['mgmtname'] = $mgmtname;
			$data['main_content'] = "manage".$mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
		elseif($tasktype=="managedata")
		{
			$flashdatamsg =  "Please fill mandatory fields!";
			$flashdatacls = 'alert-danger';
				//predata($_REQUEST); exit;
				$rsrcid = $this->input->post("rsrcid");
				$productid = $this->input->post("productid");
				$fromvalue = $this->input->post("fromvalue");
				$tovalue = $this->input->post("tovalue");
				if($productid!=""&& $fromvalue>0 && $tovalue>0 )
				{
					$slug = url_title($name, 'dash', true);
					$data = array(
						"fld_outletid" => $this->outletid,
						"fld_clientid" => $this->clientid,
						"fld_userid" => $this->userid,
						"fld_productid" => $productid,
						"fld_fromvalue" => $fromvalue,					
						"fld_tovalue" => $tovalue,
						"fld_updatedby" => $this->lguserinfo["sessID"],
						"fld_updatedon" => date("Y-m-d H:i:s")
						
					);
					if($rsrcid=="" || $rsrcid==0)
					{
						$data["fld_datetime"] = date("Y-m-d H:i:s");
					}
					$resourceid = $this->common_model->managedata($data, $mgmtname, $rsrcid);
					
					if($resourceid>0)
					{
						$flashdatacls =  'alert-success';
						if($rsrcid>0)
						{
							$flashdatamsg =  ucfirst($mgmtname)." info. successfully modified!";
						}
						else
						{
							$flashdatamsg =  ucfirst($mgmtname)." info. successfully added!";							
						}						 
					}
					elseif($resourceid==0)
					{
						$flashdatamsg =  "Sorry, info. you are looking for not found in our record!";
					}
					elseif($resourceid<0)
					{
						$flashdatamsg =  "Sorry, info. already exists!";
					}
				}

				$this->session->set_flashdata("message", $flashdatamsg);
				$this->session->set_flashdata('alerttype', $flashdatacls);

				redirect("outlet/".$mgmtname);
				exit;
		}
		else // for listing
		{			
			$totalRec = $this->common_model->listjoindata($mgmtname,"count", '');

			//pagination configuration
			$config['base_url']    = base_url().'outlet/'.$mgmtname;
			$config['total_rows']  = $totalRec;
			$config['per_page']    = $this->perPage;
			$config['target']    = $this->perPage;
			
			//get the list data
			$pageid = $this->uri->segment(3);
			if($pageid=="" || $pageid==0)
			{
				$pageid = 1;
			}
			$start = ($pageid - 1) * $this->perPage;
			
			$config['uri_segment'] =  $start;
			$config['num_links'] = 5;
			$this->ajax_pagination->initialize($config);
			
			$data['results'] = $this->common_model->listjoindata($mgmtname,"list", array('limit'=>$this->perPage,'start'=>$start));
			
			$data['main_content'] = $mgmtname;
			$data['mgmtname'] = $mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
	}
	function orders()
	{			
		$tasktype = $this->uri->segment("3");
		if($tasktype=="customer" || $tasktype=="product" || $tasktype=="category" || $tasktype=="brand" || $tasktype=="producttype")
		{
			if($tasktype=="customer")
			{
				$mgmtname = 'customers';
				$mgmttbl = 'customers';
				$rdurl = 'outlet/customers';
			}
			elseif($tasktype=="product")
			{
				$mgmtname = 'products';
				$mgmttbl = 'products';
				$rdurl = 'outlet/products';
			}
			elseif($tasktype=="producttype")
			{
				$mgmtname = 'products';
				$mgmttbl = 'products';
				$rdurl = 'outlet/products';
			}
			elseif($tasktype=="category")
			{
				$mgmtname = 'category';
				$mgmttbl = 'category';
				$rdurl = 'outlet/category';
			}
			elseif($tasktype=="brand")
			{
				$mgmtname = 'brand';
				$mgmttbl = 'brand';
				$rdurl = 'outlet/brand';
			}
			$rsrcid = $this->uri->segment("4");
			
			$data["rsrcid"] = 0;
			if($rsrcid!="")
			{
				if($tasktype=="producttype")
				{
					
					$data["info4edit"] = arrProductType()[$rsrcid];
				}
				else
				{
					$rsrcid = decodeValue($rsrcid);
					$data["info4edit"] = $this->common_model->getinfo($rsrcid, $mgmttbl);
				}
				if($data["info4edit"])
				{
					$fromdt = trim($this->input->get("fromdate"));
					$todt = trim($this->input->get("todate"));
					if($fromdt!="")
					{
						 $fromdate = convertdateFormat($fromdt,'Y-m-d');
						 $data['fromdate'] = $fromdate;
					}
					if($todt!="")
					{				
						$todate = convertdateFormat($todt,'Y-m-d');
						$data['todate'] = $todate;
					}

					if($fromdt=="" && $todt=="")
					{
						$data['fromdate'] = date('Y-m-d');
						$data['todate'] = date('Y-m-d');
					}

					$data["rsrcid"] = $rsrcid;
					if($tasktype=="customer")
					{
						 $data["pgheading"] = $data["info4edit"]->fld_mobile." > View Orders";
						 $fldname ='fld_customerid';
						 
					}
					elseif($tasktype=="category")
					{
						 $data["pgheading"] = $data["info4edit"]->fld_name." > View Orders";
						 $fldname ='fld_catid';
					}
					elseif($tasktype=="brand")
					{
						 $data["pgheading"] = $data["info4edit"]->fld_name." > View Orders";
						 $fldname ='fld_brandid';
					}
					elseif($tasktype=="product")
					{
						 $data["pgheading"] = $data["info4edit"]->fld_name." > View Orders";
						 $fldname ='fld_productid';
							if($data["info4edit"]->cattype=='gift')
							{
								$fldname ='fld_gprodid';
							}
							
					}
					elseif($tasktype=="producttype")
					{
						 $data["pgheading"] = $data["info4edit"]." > View Orders";
						 $fldname ='fld_type';
					}
					if($tasktype=="producttype")
					{					
						
						$data["page_url"] = base_url().'outlet/orders/'.$tasktype."/".$rsrcid;
					}
					else
					{
						$data["page_url"] = base_url().'outlet/orders/'.$tasktype."/".encodeValue($rsrcid);
						
					}
					//$totalRec = $this->common_model->listordersdata("count", '',$fldname,$rsrcid);
					$totalRec = $this->common_model->listallordersdata("count", '',$fldname,$rsrcid);

					//pagination configuration
					$config['base_url']    = $data["page_url"];
					$config['total_rows']  = $totalRec;
					$config['per_page']    = $this->perPage;
					$config['target']    = $this->perPage;
					
					//get the list data
					$pageid = $this->uri->segment(5);
					if($pageid=="" || $pageid==0)
					{
						$pageid = 1;
					}
					$start = ($pageid - 1) * $this->perPage;
					
					$config['uri_segment'] =  $start;
					$config['num_links'] = 5;
					$this->ajax_pagination->initialize($config);
					
					//$data['results'] = $this->common_model->listordersdata("list", array('limit'=>$this->perPage,'start'=>$start),$fldname,$rsrcid);
					$data['results'] = $this->common_model->listallordersdata("list", array('limit'=>$this->perPage,'start'=>$start),$fldname,$rsrcid);
					$data["billerlist"] = $this->common_model->getlistbywhere('users', 'fld_id,fld_name','fld_name asc','fld_outletid="'.$this->outletid.'" and fld_type="operator"');	
					//$data['main_content'] = $tasktype.'orders';
					$data['tasktype'] = $tasktype;
					$data['main_content'] = 'orders';
					$data['mgmtname'] = $mgmtname;
					$this->load->view('outlet/common/main.inc.php',$data);
				}
				else
				{
					redirect($rdurl);
					exit;
				}
			}
			else
			{
				redirect($rdurl);
				exit;
			}
			
		}
		
		
	}
	function customers()
	{
			$mgmtname = 'customers';		
			$fromdt = trim($this->input->get("fromdate"));
			$todt = trim($this->input->get("todate"));
			if($fromdt!="")
			{
				 $fromdate = convertdateFormat($fromdt,'Y-m-d');
				 $data['fromdate'] = $fromdate;
			}
			if($todt!="")
			{				
				$todate = convertdateFormat($todt,'Y-m-d');
				$data['todate'] = $todate;
			}

			if($fromdt=="" && $todt=="")
			{
				$data['fromdate'] = date('Y-m-d');
				$data['todate'] = date('Y-m-d');
			}								
			$totalRec = $this->common_model->listcustomerdata("count", '');

			//pagination configuration
			$config['base_url']    = base_url().'outlet'.$mgmtname;
			$config['total_rows']  = $totalRec;
			$config['per_page']    = $this->perPage;
			$config['target']    = $this->perPage;
			
			//get the list data
			$pageid = $this->uri->segment(3);
			if($pageid=="" || $pageid==0)
			{
				$pageid = 1;
			}
			$start = ($pageid - 1) * $this->perPage;
			
			$config['uri_segment'] =  $start;
			$config['num_links'] = 5;
			$this->ajax_pagination->initialize($config);
			
			$data['results'] = $this->common_model->listcustomerdata("list", array('limit'=>$this->perPage,'start'=>$start));
			$data["billerlist"] = $this->common_model->getlistbywhere('users', 'fld_id,fld_name','fld_name asc','fld_outletid="'.$this->outletid.'" and fld_type="operator"');
			$data['main_content'] = $mgmtname;
			$data['mgmtname'] = $mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		
		
	}

	function billing()
	{
		$mgmtname = 'billing';
		$mgmttbl = 'billing';
		$tasktype = $this->uri->segment("3");		
		if($tasktype=="printbill" || $tasktype=="view")
		{
				$rsrcid = $this->uri->segment("4");				
				if($rsrcid!="")
				{
					$rsrcid = decodeValue($rsrcid);
					if($data["info4view"] = $this->common_model->getinfo($rsrcid, $mgmttbl))
					{
						$data["dbuserinfo"] = $this->common_model->getinfo($data["info4view"]->fld_userid, "users");
						$data["transinfo4view"] = $this->common_model->getbillinginfolist($rsrcid);						
						$data["rsrcid"] = $rsrcid;
						$data["pgheading"] = "View ".ucfirst($mgmtname)." Info.";
					}
				}
				//predata($data["info4edit"]);
				
				$data['tasktype'] = $tasktype;
				$data['mgmtname'] = $mgmtname;
				$data['main_content'] = "view".$mgmtname;
				if($tasktype=='view')
				{
					$this->load->view("outlet/view".$mgmtname,$data);
				}
				else
				{
					$this->load->view("outlet/view".$mgmtname,$data);
				}
			
		}		
		elseif($tasktype=="cancelorder")
		{
			$rsrcid = $this->uri->segment("4");			
			$data["rsrcid"] = 0;
			if($rsrcid!="")
			{
				 $rsrcid = decodeValue($rsrcid);
				if($data["info4edit"] = $this->common_model->getinfo($rsrcid,$mgmtname))
				{					
					$cancellation_reason = $this->input->post("cancellation_reason");
					$remarks = $this->input->post("remarks");
					if($cancellation_reason!="" && $remarks!="")
					{
						$data2 = array(
							"fld_cancelrequestby" => $this->userid,
							"fld_cancellation_reason" => $cancellation_reason,
							"fld_cancellation_remarks" => $remarks,
							"fld_status" => 'pending',
							"fld_cancellationdate" => date("Y-m-d H:i:s"),
							"fld_updatedby" => $this->lguserinfo["sessID"],
							"fld_updatedon" => date("Y-m-d H:i:s")	
						);				
						
						if($this->common_model->updatedata($mgmtname, $rsrcid, $data2))
						{
							$flashdatacls =  'btn btn-success';
							$flashdatamsg =  "Order cancellation request submited!";
						}
						else
						{
							$flashdatacls =  'btn btn-danger';
							$flashdatamsg =  "something went wrong, Please try again!";
						}
						
						$this->session->set_flashdata("message2", $flashdatamsg);
						$this->session->set_flashdata('alerttype2', $flashdatacls);
						redirect("outlet/".$mgmtname."/cancelorder/".encodeValue($rsrcid));
						exit;
					}

					$data["pgheading"] = "Cancel Order";
					$data["rsrcid"] = $rsrcid;
					//predata($data["info4edit"]); 
					$data['mgmtname'] = $mgmtname;
					$data['main_content'] = "cancelorder";
					$this->load->view('outlet/common/popup.inc.php',$data);
				}
				else
				{
					redirect("outlet/".$mgmtname);
					exit;
				}
			}
			else
			{
				redirect("outlet/".$mgmtname);
				exit;
			}
		}
		elseif($tasktype=="exportcsv" || $tasktype=="exportpdf")
		{				
					
					$outletid = $this->outletid;
					$outletinfo = $this->common_model->getinfo($outletid,'outlets');		
					//predata($outletinfo);
					$filedate = date('d-M-Y', strtotime($data['fromdate']));
					$filename = "billing_".$filedate;
					if($outletinfo->fld_name!="")
					{

						$filename = $outletinfo->fld_name."_billing_".$filedate;
					}		
					
					$results = $this->common_model->listbillingdata("list", '');					

					$previousstockdate = dfltdtFormat(date('d-M-Y', strtotime('-1 day', strtotime($data['fromdate']))));
					if($tasktype=="exportcsv")
					{
						ob_end_clean();	
						$headerrow = 0;
						// Set headers for file name, MIME type, and caching
						header("Content-type: application/csv");
						header("Content-Disposition: attachment; filename=\"".$filename.".csv\"");
						header("Pragma: no-cache");
						header("Expires: 0");
						$fh = fopen('php://output', 'w');
						$rowtitle = array(
													
							"invoiceno" => 'Invoice',
							"customer" => 'Customer',							
							"discount" => 'Discount/Gifts',
							"amount" => 'Amount',

						);

						$rowindex = 0;
						foreach($results as $row)
						{
								$rowindex++;
								$discount ="";
								$pdiscount ="";
								$hightlightcls ="";
								$dicountinfo="";
								if($row['fld_discount']>0)
								{
									$discount = $row['fld_discount'];	
									$amount = $row['fld_netamount']+$discount;
									$pdiscount  = ($discount/$amount)*100;
									$dicountinfo  = round($discount,2) ." (" .round($pdiscount,2). "%)";							

								}
								else if($row['fld_gqty']>0)
								{
									$dicountinfo = $row['giftname'];
									
								}
								$customer = "";
								if($row['fld_name']!="")
								{
									$customer = $row['fld_name'];
								}
								if($row['fld_mobile']!="")
								{
									$customer = $row['fld_mobile'];
								}
								if($row['fld_mobile']!="" && $row['fld_name']!="")
								{
									$customer = $row['fld_name']." <br> ".$row['fld_mobile'];
								}
								$billdate = "";
								if($row['fld_billdate'])
								{
									$billdate = date("d-M-Y", strtotime($row['fld_billdate']));
								}
								$postedon = "";
								if($row['fld_datetime'])
								{
									$postedon = date("d-M-Y", strtotime($row['fld_datetime']));
								}
								$status  = arrOrderStatus()[$row['fld_status']];
								$invoiceinfo = "";
								
								if($row['fld_billno'])
								{
									$invoiceinfo = $row['fld_billno']." " .$billdate;
								}
								if($status)
								{
									$invoiceinfo .= " ,". $status;
								}
								$rowvalue = array(
								
									
									"invoice" => $invoiceinfo,
									"customer" => $customer,									
									"discount" => $dicountinfo,
									"amount" => $row['fld_netamount'],

								);

								if($headerrow<1)
								{							
									$headerrow = 1;
									$mycustomheader = array_values($rowtitle);
									fputcsv($fh, $mycustomheader);
								}
								fputcsv($fh, $rowvalue);
						}
						fclose($fh);
					}
					elseif($tasktype=="exportpdf")
					{
$htmlcode ='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">

<head>
<title>TCPDF Examples</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="TCPDF is a PHP class for generating PDF documents on the fly" />
<meta name="author" content="Nicola Asuni" />
<meta name="keywords" content="Examples, TCPDF, PDF, PHP class" />
</head>

<body>

<table border="1" cellspecing="5" cellpadding="5">
		 
                <tbody>
                	<tr>
                    	<th width="10%">SRNo.</th>                    
                    	<th width="30%" align="center">Invoice</th>                   	
                    	<th width="30%" align="center">Customer</th>
						<th width="16%" align="center">Discount/Gifts</th>
						<th width="14%"  align="center">Amount</th>
                    </tr>
                    ';
					

					if(is_array($results) && count(array_filter($results))>0)
					{
						$rowindex = 0;

						foreach($results as $row)
						{
								$rowindex++;
								$discount ="";
								$pdiscount ="";
								$hightlightcls ="";
								$dicountinfo="";
								if($row['fld_discount']>0)
								{
									$discount = $row['fld_discount'];	
									$amount = $row['fld_netamount']+$discount;
									$pdiscount  = ($discount/$amount)*100;
									$dicountinfo  = round($discount,2) ." (" .round($pdiscount,2). "%)";					

								}
								else if($row['fld_gqty']>0)
								{
									$dicountinfo = $row['giftname'];
									
								}
								$customer = "";
								if($row['fld_name']!="")
								{
									$customer = $row['fld_name'];
								}
								if($row['fld_mobile']!="")
								{
									$customer = $row['fld_mobile'];
								}
								if($row['fld_mobile']!="" && $row['fld_name']!="")
								{
									$customer = $row['fld_name']." <br> ".$row['fld_mobile'];
								}
								$billdate = "";
								if($row['fld_billdate'])
								{
									$billdate = date("d-M-Y", strtotime($row['fld_billdate']));
								}
								$postedon = "";
								if($row['fld_datetime'])
								{
									$postedon = date("d-M-Y", strtotime($row['fld_datetime']));
								}
								$status  = arrOrderStatus()[$row['fld_status']];
								$invoiceinfo = "";
								
								if($row['fld_billno'])
								{
									$invoiceinfo = $row['fld_billno']." <br>" .$billdate;
								}
								if($status)
								{
									$invoiceinfo .= " <br>". $status;
								}
								$rowvalue = array(
									"index" => $rowindex,
									
									"invoice" => $invoiceinfo,
									"customer" => $customer,									
									"discount" => $dicountinfo,
									"amount" => $row['fld_amount'],
								);
					
$htmlcode .='<tr>
<td width="10%">'.$rowindex.'</td>

<td width="30%" align="center">'.$invoiceinfo.'</td>
<td width="30%" align="center">'.$customer.'</td> 
<td width="16%" align="center">'.$dicountinfo.'</td>
<td width="14%" align="center">'.$row['fld_netamount'].'</td>

</tr>';

                	
                   
						}
					}
					
                    
                    $htmlcode .='</tbody>
                </table>

</body>
</html>';

				$this->load->library('Pdf');
				$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
				$pdf->SetTitle('');
				$pdf->setPrintHeader(false);
				$pdf->setPrintFooter(false);
				$pdf->SetHeaderMargin(30);
				$pdf->SetTopMargin(20);
				$pdf->setFooterMargin(20);
				$pdf->SetAutoPageBreak(true,15);
				$pdf->SetAuthor('Author');
				$pdf->SetDisplayMode('real', 'default');
				$pdf->AddPage();
				//$pdf->Write(5, 'CodeIgniter TCPDF Integration');
				$pdf->writeHTML($htmlcode, true, false, false, false, '');
				//$pdf->Output('stockstatus_'.date('Ymdhsi').'.pdf', 'I');
				$pdf->Output($filename.'.pdf', 'D');
					}
				
		}
		else
		{
				
			$fromdt = trim($this->input->get("fromdate"));
			$todt = trim($this->input->get("todate"));
			if($fromdt!="")
			{
				 $fromdate = convertdateFormat($fromdt,'Y-m-d');
				 $data['fromdate'] = $fromdate;
			}
			if($todt!="")
			{				
				$todate = convertdateFormat($todt,'Y-m-d');
				$data['todate'] = $todate;
			}

			if($fromdt=="" && $todt=="")
			{
				$data['fromdate'] = date('Y-m-d');
				$data['todate'] = date('Y-m-d');
			}
			$totalRec = $this->common_model->listbillingdata("count", '');

			//pagination configuration
			$config['base_url']    = base_url().'outlet/'.$mgmtname;
			$config['total_rows']  = $totalRec;
			$config['per_page']    = $this->perPage;
			$config['target']    = $this->perPage;
			
			//get the list data
			$pageid = $this->uri->segment(3);
			if($pageid=="" || $pageid==0)
			{
				$pageid = 1;
			}
			$start = ($pageid - 1) * $this->perPage;
			
			$config['uri_segment'] =  $start;
			$config['num_links'] = 5;
			$this->ajax_pagination->initialize($config);
			
			$data['results'] = $this->common_model->listbillingdata("list", array('limit'=>$this->perPage,'start'=>$start));
		
			
			
		
			$data['main_content'] = $mgmtname;
			$data['mgmtname'] = $mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
		
	}
	
	function stockreceived()
	{
		$mgmtname = 'stockreceived';
		$mgmttbl = 'transaction';
		
		$tasktype = $this->uri->segment("3");
		if($tasktype=="confirm")
		{
			$flashdatamsg =  "Please fill mandatory fields!";
			$flashdatacls = 'alert-danger';
			$rsrcid = $this->uri->segment("4");
			if($rsrcid!="")
			{
				$rsrcid = decodeValue($rsrcid);
				if($this->outlet_model->acknowledgestock($rsrcid))
				{
						$flashdatacls =  'alert-success';
						$flashdatamsg =  " Stock confirmed!";
				}
			}

			$this->session->set_flashdata("message", $flashdatamsg);
			$this->session->set_flashdata('alerttype', $flashdatacls);			
			redirect("outlet/".$mgmtname."/?".$_SERVER['QUERY_STRING']);
			exit;
			
		}
		elseif($tasktype=="view" || $tasktype=="print")
		{
				$rsrcid = $this->uri->segment("4");
				
				if($rsrcid!="")
				{
					$rsrcid = decodeValue($rsrcid);
					if($data["info4view"] = $this->common_model->getstockreceivedinfo($rsrcid))
					{
						$data["transinfo4view"] = $this->common_model->gettransinfolist($rsrcid);
						
						$data["rsrcid"] = $rsrcid;
						$data["pgheading"] = "View Stock Received Info.";
					}
				}
				$data['tasktype'] = $tasktype;
				
				$data['mgmtname'] = $mgmtname;
				$data['main_content'] = "view".$mgmtname;
				$this->load->view('outlet/common/popup.inc.php',$data);
			
		}
		else // for listing
		{		
			$fromdt = trim($this->input->get("fromdate"));
			$todt = trim($this->input->get("todate"));
			if($fromdt!="")
			{
				 $fromdate = convertdateFormat($fromdt,'Y-m-d');
				 $data['fromdate'] = $fromdate;
			}
			if($todt!="")
			{				
				$todate = convertdateFormat($todt,'Y-m-d');
				$data['todate'] = $todate;
			}

			if($fromdt=="" && $todt=="")
			{
				$data['fromdate'] = date('Y-m-d');
				$data['todate'] = date('Y-m-d');
			}			
			 $totalRec = $this->outlet_model->liststockreceiveddata("count", '');

			//pagination configuration
			$config['base_url']    = base_url().'outlet/'.$mgmtname;
			$config['total_rows']  = $totalRec;
			$config['per_page']    = $this->perPage;
			$config['target']    = $this->perPage;
			
			//get the list data
			$pageid = $this->uri->segment(3);
			if($pageid=="" || $pageid==0)
			{
				$pageid = 1;
			}
			$start = ($pageid - 1) * $this->perPage;
			
			$config['uri_segment'] =  $start;
			$config['num_links'] = 5;
			$this->ajax_pagination->initialize($config);
			
			$data['results'] = $this->outlet_model->liststockreceiveddata("list", array('limit'=>$this->perPage,'start'=>$start));
			$data["warehouselist"] = $this->common_model->getlist('warehouse', 'fld_id,fld_name','fld_name');
			$data["outletlist"] = $this->outlet_model->getotheroutletlist();
			$data["productlist"] = $this->common_model->getprodlistbycattype('normal');
			
			$data['main_content'] = $mgmtname;
			$data['mgmtname'] = $mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
	}
	function stocktransfer()
	{
		$mgmtname = 'stocktransfer';
		$mgmttbl = 'transaction';
		
		$tasktype = $this->uri->segment("3");
		if($tasktype=="manage")
		{
			$rsrcid = $this->uri->segment("4");
			$data["pgheading"] = "Add Stock Transfer";
			$data["rsrcid"] = 0;
			if($rsrcid!="")
			{
				$rsrcid = decodeValue($rsrcid);
				if($data["info4edit"] = $this->outlet_model->getstockinfo($rsrcid,'o2o'))
				{
					$data["rsrcid"] = $rsrcid;
					$data["pgheading"] = "Modify Stock Transfer Info.";
				}
			
										
			}
			
			$data["productlist"] = $this->common_model->getoutletstocklist($this->outletid);
			
			$data["outletlist"] = $this->outlet_model->getotheroutletlist();
			

			$data['mgmtname'] = $mgmtname;
			$data['main_content'] = "manage".$mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
		elseif($tasktype=="managedata")
		{
			$flashdatamsg =  "Please fill mandatory fields!";
			$flashdatacls = 'alert-danger';
				//predata($_REQUEST); exit;
				$rsrcid = $this->input->post("rsrcid");
				
				$outletid = decodeValue($this->input->post("outletid"));

				$refdate = $this->input->post("refdate");				
				$refno = $this->input->post("refno");

				$productid = $this->input->post("productid");
				$qty = $this->input->post("qty");
				$price = $this->input->post("price");
				$productttotalamount = $this->input->post("productttotalamount");
				$producttotalrows = $this->input->post("producttotalrows");
				
				if($outletid>0 && $refno!="" && $refdate!="" && $producttotalrows>0)
				{	
					$rtnvalps= $this->outlet_model->checkproductstock($this->outletid,$productid,$qty_case,$qty_bottle);
					//predata($rtnvalps); exit;
					 $rtnvalpscnt=count($rtnvalps);					
					$productinfo ="";
					if($rtnvalpscnt>0)
					{	
						$indexno=1;
						foreach($rtnvalps as $row)
						{							
							if($productinfo!="")
							{
								
								if($rtnvalpscnt==$indexno)
								{
									$productinfo .=" and ". $row['name'];
								}
								else
								{
									$productinfo .=",  ". $row['name'];
								}
							}
							else
							{
								$productinfo = $row['name'];
							}
							$indexno++;
						}
						$flashdatamsg  ='Error: the following product(s) are not in stock:
										- '.$productinfo.' ';
						$flashdatacls =  'alert-danger';
						$this->session->set_flashdata("message", $flashdatamsg);
						$this->session->set_flashdata('alerttype', $flashdatacls);
						
						redirect('outlet/'.$mgmtname."?". $_SERVER['QUERY_STRING']);
						exit;						
					}
					else
					{
					
						$resourceid = $this->outlet_model->managestock($this->input->post(),'o2o'); //exit;
						
						if($resourceid>0)
						{
							$flashdatacls =  'alert-success';
							if($rsrcid>0)
							{
								$flashdatamsg =  " Stock Transfer info. successfully modified!";
							}
							else
							{
								$flashdatamsg =  " Stock Transfer info. successfully added!";							
							}						 
						}
						elseif($resourceid==0)
						{
							$flashdatamsg =  "Sorry, info. you are looking for not found in our record!";
						}
						elseif($resourceid<0)
						{
							$flashdatamsg =  "Sorry, Challan NO. already exists!";
						}
					}
				}

				$this->session->set_flashdata("message", $flashdatamsg);
				$this->session->set_flashdata('alerttype', $flashdatacls);
				
				redirect("outlet/".$mgmtname."?". $_SERVER['QUERY_STRING']);
				exit;
		}
		elseif($tasktype=="view" || $tasktype=="print")
		{
				$rsrcid = $this->uri->segment("4");
				
				if($rsrcid!="")
				{
					$rsrcid = decodeValue($rsrcid);
					if($data["info4view"] = $this->common_model->getstocktransferinfo($rsrcid,'outlet'))
					{
						$data["transinfo4view"] = $this->common_model->gettransinfolist($rsrcid);
						
						$data["rsrcid"] = $rsrcid;
						$data["pgheading"] = "View Stock Transfer";
					}
				}
				$data['tasktype'] = $tasktype;			
				$data['mgmtname'] = $mgmtname;
				$data['main_content'] = "view".$mgmtname;
				$this->load->view('outlet/common/popup.inc.php',$data);
			
		}
		else // for listing
		{			
			$fromdt = trim($this->input->get("fromdate"));
			$todt = trim($this->input->get("todate"));
			if($fromdt!="")
			{
				 $fromdate = convertdateFormat($fromdt,'Y-m-d');
				 $data['fromdate'] = $fromdate;
			}
			if($todt!="")
			{				
				$todate = convertdateFormat($todt,'Y-m-d');
				$data['todate'] = $todate;
			}

			if($fromdt=="" && $todt=="")
			{
				$data['fromdate'] = date('Y-m-d');
				$data['todate'] = date('Y-m-d');
			}			
			 $totalRec = $this->outlet_model->liststockdata("count", '','o2o');

			//pagination configuration
			$config['base_url']    = base_url().'outlet/'.$mgmtname;
			$config['total_rows']  = $totalRec;
			$config['per_page']    = $this->perPage;
			$config['target']    = $this->perPage;
			
			//get the list data
			$pageid = $this->uri->segment(3);
			if($pageid=="" || $pageid==0)
			{
				$pageid = 1;
			}
			$start = ($pageid - 1) * $this->perPage;
			
			$config['uri_segment'] =  $start;
			$config['num_links'] = 5;
			$this->ajax_pagination->initialize($config);
			
			$data['results'] = $this->outlet_model->liststockdata("list", array('limit'=>$this->perPage,'start'=>$start),'o2o');
			
			$data["outletlist"] = $this->outlet_model->getotheroutletlist();
			$data["productlist"] = $this->common_model->getprodlistbycattype('normal');
			
			$data['main_content'] = $mgmtname;
			$data['mgmtname'] = $mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
	}
	function wstocktransfer()
	{
		$mgmtname = 'wstocktransfer';
		$mgmttbl = 'transaction';
		
		$tasktype = $this->uri->segment("3");
		if($tasktype=="manage")
		{
			$rsrcid = $this->uri->segment("4");
			$data["pgheading"] = "Add Stock Transfer";
			$data["rsrcid"] = 0;
			if($rsrcid!="")
			{
				$rsrcid = decodeValue($rsrcid);
				if($data["info4edit"] = $this->outlet_model->getstockinfo($rsrcid,'o2w'))
				{
					$data["rsrcid"] = $rsrcid;
					$data["pgheading"] = "Modify Stock Transfer Info.";
				}

								
			}
			
			$data["productlist"] = $this->common_model->getoutletstocklist($this->outletid);
			
			$data["warehouselist"] = $this->common_model->getlist('warehouse', 'fld_id,fld_name','fld_name');
			

			$data['mgmtname'] = $mgmtname;
			$data['main_content'] = "manage".$mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
		elseif($tasktype=="managedata")
		{
			$flashdatamsg =  "Please fill mandatory fields!";
			$flashdatacls = 'alert-danger';
				//predata($_REQUEST); exit;
				$rsrcid = $this->input->post("rsrcid");
				
				$warehouseid = decodeValue($this->input->post("warehouseid"));

				$refdate = $this->input->post("refdate");				
				$refno = $this->input->post("refno");

				$productid = $this->input->post("productid");
				$qty = $this->input->post("qty");
				$price = $this->input->post("price");
				$productttotalamount = $this->input->post("productttotalamount");
				$producttotalrows = $this->input->post("producttotalrows");
				
				if($warehouseid>0 && $refno!="" && $refdate!="" && $producttotalrows>0)
				{	
					$rtnvalps= $this->outlet_model->checkproductstock($this->outletid,$productid,$qty_case,$qty_bottle);
					//predata($rtnvalps); exit;
					 $rtnvalpscnt=count($rtnvalps);					
					$productinfo ="";
					if($rtnvalpscnt>0)
					{	
						$indexno=1;
						foreach($rtnvalps as $row)
						{							
							if($productinfo!="")
							{
								
								if($rtnvalpscnt==$indexno)
								{
									$productinfo .=" and ". $row['name'];
								}
								else
								{
									$productinfo .=",  ". $row['name'];
								}
							}
							else
							{
								$productinfo = $row['name'];
							}
							$indexno++;
						}
						$flashdatamsg  ='Error: the following product(s) are not in stock:
										- '.$productinfo.' ';
						$flashdatacls =  'alert-danger';
						$this->session->set_flashdata("message", $flashdatamsg);
						$this->session->set_flashdata('alerttype', $flashdatacls);
						
						redirect('outlet/'.$mgmtname."?". $_SERVER['QUERY_STRING']);
						exit;						
					}
					else
					{
					
						$resourceid = $this->outlet_model->managestock($this->input->post(),'o2w'); //exit;
						
						if($resourceid>0)
						{
							$flashdatacls =  'alert-success';
							if($rsrcid>0)
							{
								$flashdatamsg =  " Stock Transfer info. successfully modified!";
							}
							else
							{
								$flashdatamsg =  " Stock Transfer info. successfully added!";							
							}						 
						}
						elseif($resourceid==0)
						{
							$flashdatamsg =  "Sorry, info. you are looking for not found in our record!";
						}
						elseif($resourceid<0)
						{
							$flashdatamsg =  "Sorry, Challan NO. already exists!";
						}
					}
				}

				$this->session->set_flashdata("message", $flashdatamsg);
				$this->session->set_flashdata('alerttype', $flashdatacls);
				
				redirect("outlet/".$mgmtname."?". $_SERVER['QUERY_STRING']);
				exit;
		}
		elseif($tasktype=="view" || $tasktype=="print")
		{
				$rsrcid = $this->uri->segment("4");
				
				if($rsrcid!="")
				{
					$rsrcid = decodeValue($rsrcid);
					if($data["info4view"] = $this->common_model->getstocktransferinfo($rsrcid,'o2w'))
					{
						$data["transinfo4view"] = $this->common_model->gettransinfolist($rsrcid);
						
						$data["rsrcid"] = $rsrcid;
						$data["pgheading"] = "View Stock Transfer";
					}
				}
				
				$data['tasktype'] = $tasktype;			
				$data['mgmtname'] = $mgmtname;
				$data['main_content'] = "view".$mgmtname;
				$this->load->view('outlet/common/popup.inc.php',$data);
			
		}
		else // for listing
		{			
			$fromdt = trim($this->input->get("fromdate"));
			$todt = trim($this->input->get("todate"));
			if($fromdt!="")
			{
				 $fromdate = convertdateFormat($fromdt,'Y-m-d');
				 $data['fromdate'] = $fromdate;
			}
			if($todt!="")
			{				
				$todate = convertdateFormat($todt,'Y-m-d');
				$data['todate'] = $todate;
			}

			if($fromdt=="" && $todt=="")
			{
				$data['fromdate'] = date('Y-m-d');
				$data['todate'] = date('Y-m-d');
			}			
			 $totalRec = $this->outlet_model->liststockdata("count", '','o2w');

			//pagination configuration
			$config['base_url']    = base_url().'outlet/'.$mgmtname;
			$config['total_rows']  = $totalRec;
			$config['per_page']    = $this->perPage;
			$config['target']    = $this->perPage;
			
			//get the list data
			$pageid = $this->uri->segment(3);
			if($pageid=="" || $pageid==0)
			{
				$pageid = 1;
			}
			$start = ($pageid - 1) * $this->perPage;
			
			$config['uri_segment'] =  $start;
			$config['num_links'] = 5;
			$this->ajax_pagination->initialize($config);
			
			$data['results'] = $this->outlet_model->liststockdata("list", array('limit'=>$this->perPage,'start'=>$start),'o2w');
			
			$data["outletlist"] = $this->outlet_model->getotheroutletlist();
			$data["productlist"] = $this->common_model->getprodlistbycattype('normal');
			
			$data['main_content'] = $mgmtname;
			$data['mgmtname'] = $mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
	}
function testbills()
	{

$this->db->select("*");
$this->db->where("fld_status!=",'cancelled');
$this->db->where("(DATE_FORMAT(fld_datetime,'%Y-%m-%d') >= '2023-03-16' and DATE_FORMAT(fld_datetime,'%Y-%m-%d') <= '2023-03-16')");
$this->db->order_by('fld_id', 'asc');
$results = $this->db->get("tbl_billing");
//echo $this->db->last_query(); exit;

$this->db->select("fld_billingid, sum(fld_qty*fld_price) as subtotal");
$this->db->group_by("fld_billingid");
$results2 = $this->db->get("tbl_billinginfo");
//echo $this->db->last_query(); exit;
$arrbillsinfo = array();
foreach($results2->result() as $row)
{
	$arrbillsinfo[$row->fld_billingid] = $row->subtotal;
}

$this->db->select("fld_billingid, sum(fld_qty*fld_price) as subtotal");
$this->db->group_by("fld_billingid");
$results3 = $this->db->get("tbl_billinginfo_1");
//echo $this->db->last_query(); exit;
$arrbillsinfo2 = array();
foreach($results3->result() as $row3)
{
	$arrbillsinfo2[$row3->fld_billingid] = $row3->subtotal;
}
$gtotal = 0;
$gtotal2 = 0;
$index = 1;
//predata($arrbillsinfo2);
echo '<table border="1">';
foreach($results->result() as $row)
{
	echo '<tr>';
	echo '<td>' . $index . '</td>';
	echo '<td>' . $row->fld_billno . '</td>';
	echo '<td>' . $row->fld_netamount . '</td>';
	
	$total = 0;
	if($arrbillsinfo[$row->fld_id]) $total = $arrbillsinfo[$row->fld_id];
	$gtotal += $row->fld_netamount;
	$gtotal02 += $total;


	if($total>0)
	{
		echo '<td>' . $total . '</td>';
	}
	else
	{
		$total2 = 0;
		if($arrbillsinfo2[$row->fld_id]) $total2 = $arrbillsinfo2[$row->fld_id];	
		//$gtotal02 += $total2;
		echo '<td> T2: ' . $total2 . '</td>';
	}
	
	$diff = $row->fld_netamount - $total;
	$diffamt = "";
	if($diff>0) $diffamt = $diff;
	
	echo '<td>' . $diff . '</td>';
	echo '<td>' . $row->fld_datetime . '</td>';
	echo '</tr>';
	$index++;
}
echo '</table>';

echo "<br><br>Total: " . $gtotal . " => " . $gtotal02;
	}	
	function stockstatus()
	{
		$mgmtname = 'stockstatus';
		$mgmttbl = 'transaction';
		$tasktype = $this->uri->segment("3");
			$fromdt = trim($this->input->get("fromdate"));
			$todt = trim($this->input->get("todate"));
			if($fromdt!="")
			{
				 $fromdate = convertdateFormat($fromdt,'Y-m-d');
				 $data['fromdate'] = $fromdate;
			}
			if($todt!="")
			{				
				$todate = convertdateFormat($todt,'Y-m-d');
				$data['todate'] = $todate;
			}

			if($fromdt=="" && $todt=="")
			{
				$data['fromdate'] = date('Y-m-d');
				$data['todate'] = date('Y-m-d');
			}
		if($tasktype=="exportcsv")
		{
			
			$results = $this->common_model->listoutletsstock("list", '',$this->outletid);
			
					$previousstockdate = dfltdtFormat(date('d-M-Y', strtotime('-1 day', strtotime($data['fromdate']))));
					//$results = $this->common_model->listoutletsstock("list", '',$this->outletid);
					$outletinfo = $this->common_model->getinfo($this->outletid,'outlets');
					//predata($outletinfo); exit;
					ob_end_clean();					

					$filename = "OutletStock_". $outletinfo->fld_name;
					$headerrow = 0;
					// Set headers for file name, MIME type, and caching
					header("Content-type: application/csv");
					header("Content-Disposition: attachment; filename=\"".$filename.".csv\"");
					header("Pragma: no-cache");
					header("Expires: 0");
					$fh = fopen('php://output', 'w');
					$datatext = 'Date: '.dfltdtFormat($data['fromdate']).' to '. dfltdtFormat($data['todate']);
					
					
					$rowheading1 = array(					
						"name" => 'Stock Sales Report'
					);

					$rowheading2 = array(					
						"name" => $datatext
					);

						$tot_previousstock =0;
						$tot_incoming =0;
						$tot_stocktransfer =0;
						$tot_soldqty =0;
						$tot_mrp =0;
						$tot_mrpvalue =0;
						$tot_avgprice =0;
						$tot_soldvalue =0;
						$tot_instock =0;

					$rowtitle = array(
					
						"name" => 'Item',
						"previousstock" => 'Opening Stock',
						"incoming" => 'Stock IN',
						"stocktransfer" => 'Stock Transferred',
						"qtysold" => 'Sold Qty',
						"mrpamount" => 'Mrp',
						"mrpamount" => 'Mrp Amount',
						"mrpamount" => 'Avg. Selling Price',
						"soldamount" => 'Sold Value',
						"instock" => 'Stock Left',
					);
					foreach($results as $row)
					{
							$soldqty = $row['soldqty'];
							$mrp = $row['mrp'];
							$mrpvalue = ($soldqty*$mrp);
							$avgprice = 0;
							$soldvalue = 0;
							if($row['totprice']>0 && $row['soldqty']>0)
							{
								$avgprice = ($row['totprice']/$soldqty);
								$soldvalue = ($soldqty*$avgprice);
							}
						$rowvalue = array(
							"name" => $row['name'],
							"previousstock" => round($row['previousstock'],2),
							"incoming" => round($row['incoming'],2),
							"stocktransfer" => round($row['stocktransfer'],2),
							"soldqty" => round($soldqty,2),
							"mrp" => round($mrp,2),
							"mrpvalue" => round($mrpvalue,2),
							"avgprice" => round($avgprice,2),
							"soldvalue" => round($soldvalue,2),
							"instock" => round($row['instock'],2)

						);
						if($headerrow<1)
						{	
							$headerrow = 1;
							$mycustomheader1 = array_values($rowheading1);
							fputcsv($fh, $mycustomheader1);
							$mycustomheader2 = array_values($rowheading2);
							fputcsv($fh, $mycustomheader2);
							$mycustomheader = array_values($rowtitle);
							fputcsv($fh, $mycustomheader);
						}
						fputcsv($fh, $rowvalue);

						$tot_previousstock +=$row['previousstock'];
						$tot_incoming +=$row['incoming'];
						$tot_stocktransfer +=$row['stocktransfer'];
						$tot_soldqty +=$soldqty;
						$tot_mrp +=$mrp;
						$tot_mrpvalue +=$mrpvalue;
						$tot_avgprice +=$avgprice;
						$tot_soldvalue +=$soldvalue;
						$tot_instock +=$row['instock'];						
					}
					$totalrowdata = array(					
						"total" => 'Total',
						"totinvoces" => $tot_previousstock,
						"tot_incoming" => $tot_incoming,
						"tot_stocktransfer" => $tot_stocktransfer,
						"tot_soldqty" => $tot_soldqty,
						"tot_mrp" => $tot_mrp,
						"tot_mrpvalue" => $tot_mrpvalue,
						"tot_avgprice" => $tot_avgprice,
						"tot_soldvalue" => ceil($tot_soldvalue),
						"tot_instock" => $tot_instock

					);
					$mytotalrowdata = array_values($totalrowdata);
					fputcsv($fh, $mytotalrowdata);

					$rowfooter = array(					
						"totinvoces" => 'Total No. of Bills:',
						"totinvoces2" => $row['totinvoces']

					);
					$myrowfooter = array_values($rowfooter);
					fputcsv($fh, $myrowfooter);
					$rowfooter2 = array(					

						"totspecialdiscount" => 'Total of Special Discount:',
						"totspecialdiscount2" => $row['totspecialdiscount']
					);
					$myrowfooter2 = array_values($rowfooter2);
					fputcsv($fh, $myrowfooter2);
					fclose($fh);
				
		}
		elseif($tasktype=="exportpdf")
		{
			$results = $this->common_model->listoutletsstock("list", '',$this->outletid);
			
$previousstockdate = dfltdtFormat(date('d-M-Y', strtotime('-1 day', strtotime($data['fromdate']))));
			
			
$htmlcode ='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">

<head>
<title>TCPDF Examples</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="TCPDF is a PHP class for generating PDF documents on the fly" />
<meta name="author" content="Nicola Asuni" />
<meta name="keywords" content="Examples, TCPDF, PDF, PHP class" />
</head>

<body>

<h3 style="text-align:center;">Stock Sales Report</h3>
<h3 style="text-align:center;">Date: '.dfltdtFormat($data['fromdate']).' to '. dfltdtFormat($data['todate']).'</h3>

<table border="1" cellspecing="5" cellpadding="5">
		 
                <tbody>
                	<tr style="vertical-align:top;">
                    	<th width="5%" style="vertical-align:top;">SRNo.</th>                    	
                    	<th width="15%" style="vertical-align:top;">Item</th>
						<th width="9%" style="vertical-align:top;">Opening<br>Stock</th>
                    	<th width="9%" style="vertical-align:top;" class="text-center">Stock<br> IN</th>
                    	<th width="9%" style="vertical-align:top;" class="text-center">Stock<br> Transferred</th>
                    	<th width="9%"  style="vertical-align:top;"class="text-center">Sold<br> Qty</th>
                    	<th width="8%"  style="vertical-align:top;" class="text-center">Mrp</th>
                    	<th width="9%" style="vertical-align:top;" class="text-center">Mrp<br> Value</th>
                    	<th width="9%" style="vertical-align:top;" class="text-center">Avg.<br> Selling<br> Price</th>
                    	<th width="9%" style="vertical-align:top;" class="text-center">Sold<br> Value</th>
                        <th width="9%"style="vertical-align:top;" class="text-right">Stock<br> Left</th>
                    </tr>
                   ';
					

					if(is_array($results) && count(array_filter($results))>0)
					{
						$rowindex = 0;
						$instock = 0;
						$tot_previousstock =0;
						$tot_incoming =0;
						$tot_stocktransfer =0;
						$tot_soldqty =0;
						$tot_mrp =0;
						$tot_mrpvalue =0;
						$tot_avgprice =0;
						$tot_soldvalue =0;
						$tot_instock =0;
						foreach($results as  $row)
						{
							$rowindex++;
							$soldqty = $row['soldqty'];
							$mrp = $row['mrp'];
							$mrpvalue = ($soldqty*$mrp);
							$avgprice = 0;
							$soldvalue = 0;
							if($row['totprice']>0 && $row['soldqty']>0)
							{
								$avgprice = ($row['totprice']/$soldqty);
								$soldvalue = ($soldqty*$avgprice);
							}
					
$htmlcode .='<tr>
<td width="5%">'.$rowindex.'</td>
<td width="15%">'.$row['name'].'</td>
<td width="9%" align="center">'.round($row['previousstock'],2).'</td>
<td  width="9%" align="center">'.round($row['incoming'],2).'</td>
<td width="9%" align="center">'.round($row['stocktransfer'],2).'</td>               
<td width="9%" align="center">'.round($soldqty,2).'</td>               
<td width="8%" align="center">'.round($mrp,2).'</td>               
<td width="9%" align="center">'.round($mrpvalue,2).'</td>               
<td width="9%" align="center">'.round($avgprice,2).'</td>
<td width="9%" align="center">'.round($soldvalue,2).'</td>
<td width="9%" align="center">'.round($row['instock'],2).'</td>
</tr>';

$tot_previousstock +=$row['previousstock'];
$tot_incoming +=$row['incoming'];
$tot_stocktransfer +=$row['stocktransfer'];
$tot_soldqty +=$soldqty;
$tot_mrp +=$mrp;
$tot_mrpvalue +=$mrpvalue;
$tot_avgprice +=$avgprice;
$tot_soldvalue +=$soldvalue;
$tot_instock +=$row['instock'];                 
						}

$htmlcode .='<tr>
	
	<td width="20%" colspan="2"><strong>Total</strong></td>
	<td width="9%" align="center">'. round($tot_previousstock,2).'</td>
	<td   width="9%" align="center">'. round($tot_incoming,2).'</td>
	<td  width="9%" align="center">'. round($tot_stocktransfer,2).'</td>
	<td  width="9%" align="center">'. round($tot_soldqty,2).'</td>
	<td   width="8%" align="center">'. round($tot_mrp,2).'</td>
	<td  width="9%" align="center">'. round($tot_mrpvalue,2).'</td>
	<td  width="9%" align="center">'. round($tot_avgprice,2).'</td>
	<td  width="9%" align="center">'. ceil($tot_soldvalue).'</td>
	<td  width="9%" align="center"> <strong>'. $tot_instock.'</strong></td>
</tr>';
					}
					
                    
                    $htmlcode .='</tbody>
                </table>
<h3 style="text-align:center;">Total No. of Bills: '.round($row['totinvoces'],2).'</h3>
<h3 style="text-align:center;">Total of Special Discount: '.round($row['totspecialdiscount'],2).'</h3>

</body>
</html>';
				$this->load->library('Pdf');
				$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
				$pdf->SetTitle('Stock Sales Report');
				$pdf->setPrintHeader(false);
				$pdf->setPrintFooter(false);
				$pdf->SetHeaderMargin(30);
				$pdf->SetTopMargin(20);
				$pdf->setFooterMargin(20);
				$pdf->SetAutoPageBreak(true,15);
				$pdf->SetAuthor('Author');
				$pdf->SetDisplayMode('real', 'default');
				$pdf->AddPage();
				//$pdf->Write(5, 'CodeIgniter TCPDF Integration');
				$pdf->writeHTML($htmlcode, true, false, false, false, '');
				//$pdf->Output('stockstatus_'.date('Ymdhsi').'.pdf', 'I');
				$pdf->Output('stockstatus_'.date('Ymdhsi').'.pdf', 'D');
		}
		else
		{				
			
			
			$totalRec = $this->common_model->listoutletsstock("count", '',$this->outletid);

			//pagination configuration
			$config['base_url']    = base_url().'outlet/'.$mgmtname;
			$config['total_rows']  = $totalRec;
			$config['per_page']    = $this->perPage;
			$config['target']    = $this->perPage;
			
			//get the list data
			$pageid = $this->uri->segment(3);
			if($pageid=="" || $pageid==0)
			{
				$pageid = 1;
			}
			$start = ($pageid - 1) * $this->perPage;
			
			$config['uri_segment'] =  $start;
			$config['num_links'] = 5;
			$this->ajax_pagination->initialize($config);
			
			$data['results'] = $this->common_model->listoutletsstock("list", array('limit'=>$this->perPage,'start'=>$start),$this->outletid);
			
			$data["catlist"] = $this->common_model->getlist('category', 'fld_id,fld_name','fld_name');
			$data["brandlist"] = $this->common_model->getlist('brand', 'fld_id,fld_name','fld_name');		
			$data['main_content'] = $mgmtname;
			$data['mgmtname'] = $mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
		
	}
	
	function removecommonrow()
	{
		$response = "failed";
		$task = $this->input->get_post("task");
		$rowid = $this->input->get_post("rowid");
		if($task=="product" || $task=="demandproduct")
		{
			if($rowid>0)
			{
				if($task=="product") { $tablename ='transactioninfo' ; }
				elseif($task=="demandproduct") { $tablename ='demandinfo' ; }
				
				
				if($this->common_model->delinfocomm($rowid, $tablename))
				{
					$response = "success";
				}
			}
		}

		echo $response;
	}


	function products()
	{
		$mgmtname = 'products';
		$tasktype = $this->uri->segment("3");
		$totalRec = $this->common_model->listproductdata("count", '','','','','','7,30');

		//pagination configuration
		
		if($tasktype=="price")
		{
			$config['base_url']    = base_url().'outlet/'.$mgmtname."/price/";
		}
		else
		{
			$config['base_url']    = base_url().'outlet/'.$mgmtname;
		}
		$config['total_rows']  = $totalRec;
		$config['per_page']    = $this->perPage;
		$config['target']    = $this->perPage;
		
		//get the list data
		if($tasktype=="price")
		{
			$pageid = $this->uri->segment(4);
		}
		else
		{
			$pageid = $this->uri->segment(3);
		}
		
		if($pageid=="" || $pageid==0)
		{
			$pageid = 1;
		}
		$start = ($pageid - 1) * $this->perPage;
		
		$config['uri_segment'] =  $start;
		$config['num_links'] = 5;
		$this->ajax_pagination->initialize($config);
		$data['startlist'] = $start+1;
		if($tasktype=="price")
		{
			$data['tasktype'] = $tasktype;
			$data['results'] = $this->common_model->listproductdata("list", array('limit'=>$this->perPage,'start'=>$start),'price','stock','category','','');	
		}
		else
		{
			$minqty = $this->input->get_post("minqty");
			$prodid = $this->input->get_post("prodid");
            $minqtyid = $this->input->get_post("minqtyid");
            
			if($minqty!="" && $prodid!="")
            {
				for($i=0;$i<count($prodid);$i++)
				{				
							
					if($minqtyid[$i]>0)
					{
						$dbdata = array(				  					  
						  'fld_minqty'=> $minqty[$i],
							"fld_updatedby" => $this->lguserinfo["sessID"],
							"fld_updatedon" => date("Y-m-d H:i:s")							
						);	
						$this->common_model->updatedata('prodminqty', $minqtyid[$i], $dbdata);
					}
					else
					{
						$dbdata = array(				  					  
						  'fld_minqty'=> $minqty[$i],			  
						  'fld_clientid'=> $this->clientid,			  
						  'fld_userid'=> $this->userid,			  
						  'fld_outletid'=> $this->outletid,			  
						  'fld_productid'=> $prodid[$i],		  
						  'fld_datetime'=> date("Y-m-d H:i:s"),
						"fld_updatedby" => $this->lguserinfo["sessID"],
						"fld_updatedon" => date("Y-m-d H:i:s")							
						);	
						$this->db->insert('tbl_prodminqty', $dbdata);
							//$mcatid = $this->db->insert_id();
					}
						
				}
				
				$this->session->set_flashdata('message',"Min. Qty updated succesfully!");
				$this->session->set_flashdata('alerttype',"alert-success");
			 }
			$data['results'] = $this->common_model->listproductdata("list", array('limit'=>$this->perPage,'start'=>$start),'','stock','category','brand','7,30');
		}			
		 
		//predata($data['results']); exit;
		$data["catlist"] = $this->common_model->getlistbywhere('category', 'fld_id,fld_name','fld_name asc','fld_type="normal"');
			
		$data["brandlist"] = $this->common_model->getlist('brand', 'fld_id,fld_name','fld_name');
		$data['main_content'] = $mgmtname;
		$data['mgmtname'] = $mgmtname;
		$this->load->view('outlet/common/main.inc.php',$data);		
	}	

	function report()
	{	
		$fromdt = trim($this->input->get("fromdate"));
		$todt = trim($this->input->get("todate"));
		if($fromdt!="")
		{
			 $fromdate = convertdateFormat($fromdt,'Y-m-d');
			 $data['fromdate'] = $fromdate;
		}
		if($todt!="")
		{				
			$todate = convertdateFormat($todt,'Y-m-d');
			$data['todate'] = $todate;
		}

		if($fromdt=="" && $todt=="")
		{
			$data['fromdate'] = date('Y-m-d');
			$data['todate'] = date('Y-m-d');
		}		
		$tasktype = $this->uri->segment("3");
		if($tasktype=="sale")
		{
			$totalRec = $this->common_model->listordertotalreport("count", '');

			//pagination configuration
			$config['base_url']    = base_url().'outlet/report/'.$tasktype;
			$config['total_rows']  = $totalRec;
			$config['per_page']    = $this->perPage;
			$config['target']    = $this->perPage;
			
			//get the list data
			$pageid = $this->uri->segment(2);
			if($pageid=="" || $pageid==0)
			{
				$pageid = 1;
			}
			$start = ($pageid - 1) * $this->perPage;
			
			$config['uri_segment'] =  $start;
			$config['num_links'] = 5;
			$this->ajax_pagination->initialize($config);
			
			$data['results'] = $this->common_model->listordertotalreport("list", array('limit'=>$this->perPage,'start'=>$start));
			$data["billerlist"] = $this->common_model->getlistbywhere('users', 'fld_id,fld_name','fld_name asc','fld_outletid="'.$this->outletid.'" and fld_type="operator"');
			
			$data['tasktype'] = $tasktype;
			$data['main_content'] = $tasktype.'report';
			$data['pgheading'] = ucfirst($tasktype). ' Report';
			$this->load->view('outlet/common/main.inc.php',$data);		
			
		}
		elseif($tasktype=="invoices")
		{
			 //$userid = decodeValue($this->uri->segment("5"));
			 $userid = decodeValue($this->input->get("billerid"));
			if($userid>0)
			{
				if($data["info4edit"] = $this->common_model->getinfo($userid, 'users'))
				{
					$data["userid"] = $userid;					
					 $data["pgheading"] = $data["info4edit"]->fld_name." > View Invoices Report";
										
						
				}
			}
			
					$fldname ='fld_userid';
					$totalRec = $this->common_model->listordersdata("count", '',$fldname,$userid);

					
					//pagination configuration
					$config['base_url']    = base_url().'outlet/report/'.$tasktype;
					$config['total_rows']  = $totalRec;
					$config['per_page']    = $this->perPage;
					$config['target']    = $this->perPage;
					
					//get the list data
					$pageid = $this->uri->segment(2);
					if($pageid=="" || $pageid==0)
					{
						$pageid = 1;
					}
					$start = ($pageid - 1) * $this->perPage;
					
					$config['uri_segment'] =  $start;
					$config['num_links'] = 5;
					$this->ajax_pagination->initialize($config);
					
					$data['results'] = $this->common_model->listordersdata("list", array('limit'=>$this->perPage,'start'=>$start),$fldname,$userid);
					$tasktypeexport = $this->uri->segment("4");
					if($tasktypeexport=="exportcsv" || $tasktypeexport=="exportpdf")
					{
						
						//$outletinfo = $this->common_model->getinfo($outletid,'outlets');		
						//predata($outletinfo);
						$filedate = date('d-M-Y', strtotime($data['fromdate']));
						$filename = "invoices_".$filedate;
						if($data["info4edit"]->fld_name!="")
						{

							$filename = $data["info4edit"]->fld_name."_invoices_".$filedate;
						}		
					
						$results = $data['results'];					

						$previousstockdate = dfltdtFormat(date('d-M-Y', strtotime('-1 day', strtotime($data['fromdate']))));
							if($tasktypeexport=="exportcsv")
							{
								ob_end_clean();	
								$headerrow = 0;
								// Set headers for file name, MIME type, and caching
								header("Content-type: application/csv");
								header("Content-Disposition: attachment; filename=\"".$filename.".csv\"");
								header("Pragma: no-cache");
								header("Expires: 0");
								$fh = fopen('php://output', 'w');
								$rowtitle = array(
									
								
									"biller" => 'Biller',
									"invoiceno" => 'Invoice',
									"date" => 'Date',
									"amount" => 'Amount',

								);
								$rowindex = 0;
								$totalamount = 0;
								foreach($results as $row)
								{
									$rowindex++;
									$rowvalue = array(
										
										
										"biller" => $row->billername,
										"invoice" => $row->fld_billno,
										"date" => date("d-M-Y", strtotime($row->fld_billdate)),
										"amount" => $row->fld_netamount,

									);

									if($headerrow<1)
									{							
										$headerrow = 1;
										$mycustomheader = array_values($rowtitle);
										fputcsv($fh, $mycustomheader);
									}
									fputcsv($fh, $rowvalue);
									$totalamount += $row->fld_netamount; 
								}
								if($totalamount>0)
								{
									$rowvalue = array(
										
										
										"biller" => "",
										"invoice" => "",
										"date" => "Total",
										"amount" => number_format($totalamount,2),

									);
									fputcsv($fh, $rowvalue);
								}
								fclose($fh);
							}
							elseif($tasktypeexport=="exportpdf")
							{
								
$htmlcode ='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">

<head>
<title>TCPDF Examples</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="TCPDF is a PHP class for generating PDF documents on the fly" />
<meta name="author" content="Nicola Asuni" />
<meta name="keywords" content="Examples, TCPDF, PDF, PHP class" />
</head>

<body>

<table border="1" cellspecing="5" cellpadding="5">
		 
                <tbody>
                	<tr>
                    	<th width="10%">SRNo.</th>
                    	
                    	<th width="30%">Biller</th>                   	
                    	<th width="20%">Invoice</th>
						<th width="14%">Date</th>
						<th width="26%" align="right">Amount</th>
                    </tr>
                   ';
					

					if(is_array($results) && count(array_filter($results))>0)
					{
						$rowindex = 0;
						$totalamount = 0;

						foreach($results as $row)
						{
							$rowindex++;
					
$htmlcode .='<tr>
<td width="10%">'.$rowindex.'</td>

<td width="30%">'.$row->billername.'</td>
<td width="20%">'.$row->fld_billno.'</td> 
<td width="14%" >'.date("d-M-Y", strtotime($row->fld_billdate)).'</td>
<td width="26%" align="right">'.$row->fld_netamount.'</td>

</tr>';

    $totalamount += $row->fld_netamount;            	
                   
						}
$htmlcode .='<tr>

<td width="74%"  align="right">Total</td>
<td width="26%" align="right">'.number_format($totalamount,2).'</td>

</tr>';
					}
					
                    
                    $htmlcode .='</tbody>
                </table>

</body>
</html>';

							$this->load->library('Pdf');
							$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
							$pdf->SetTitle('');
							$pdf->setPrintHeader(false);
							$pdf->setPrintFooter(false);
							$pdf->SetHeaderMargin(30);
							$pdf->SetTopMargin(20);
							$pdf->setFooterMargin(20);
							$pdf->SetAutoPageBreak(true,15);
							$pdf->SetAuthor('Author');
							$pdf->SetDisplayMode('real', 'default');
							$pdf->AddPage();
							//$pdf->Write(5, 'CodeIgniter TCPDF Integration');
							$pdf->writeHTML($htmlcode, true, false, false, false, '');
							//$pdf->Output('stockstatus_'.date('Ymdhsi').'.pdf', 'I');
							$pdf->Output($filename.'.pdf', 'D');
						}
					}
					else
					{
						$data["config_base_url"] = $config['base_url'] ;
						$data["billerlist"] = $this->common_model->getlistbywhere('users', 'fld_id,fld_name','fld_name asc','fld_outletid="'.$this->outletid.'" and fld_type="operator"');
						$data['tasktype'] = $tasktype;
						$data['main_content'] = $tasktype.'report';
						
						$this->load->view('outlet/common/main.inc.php',$data);
					}					
					
					

			
		}
		else
		{	
			redirect('outlet/dashboard');
			exit;
		}
		
		
	}
	function odemands()
	{
		$mgmtname = 'odemands';
		$mgmttbl = 'demand';
		
		$tasktype = $this->uri->segment("3");

		if($tasktype=="manage")
		{
			$rsrcid = $this->uri->segment("4");
			$data["pgheading"] = "Add Demand";
			$data["rsrcid"] = 0;
			if($rsrcid!="")
			{
				$rsrcid = decodeValue($rsrcid);
				if($data["info4edit"] = $this->common_model->getdemandinfo($rsrcid,'w2a'))
				{
					$data["rsrcid"] = $rsrcid;
					$data["pgheading"] = "Modify Demand Info.";
				}
			}
			//predata($data["info4edit"]); exit;
			//$data["productlist"] = $this->common_model->getoutletstocklist($this->outletid);
			$data["productlist"] = $this->common_model->getlist('products', 'fld_id,fld_name','fld_name');
			$data["warehouselist"] = $this->common_model->getlist('warehouse', 'fld_id,fld_name','fld_name');
			

			$data['mgmtname'] = $mgmtname;
			$data['main_content'] = "manage".$mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
		elseif($tasktype=="managedata")
		{
				$flashdatamsg =  "Please fill mandatory fields!";
				$flashdatacls = 'alert-danger';
				
				$rsrcid = $this->input->post("rsrcid");				
				$outletid = $this->outletid;
				$warehouseid = $this->input->post("warehouseid");
				$refdate = $this->input->post("refdate");				
				$refno = $this->input->post("refno");
				$productid = $this->input->post("productid");
				$qty_case = $this->input->post("qty_case");
				$qty_bottle = $this->input->post("qty_bottle");				
				$producttotalrows = $this->input->post("producttotalrows");
				
				if($warehouseid>0 && $refdate!="" && $producttotalrows>0)
				{
						$resourceid = $this->outlet_model->managedemind($this->input->post(),'o2w');
						
						if($resourceid>0)
						{
							$flashdatacls =  'alert-success';
							if($rsrcid>0)
							{
								$flashdatamsg =  "Demand info. successfully modified!";
							}
							else
							{
								$flashdatamsg =  "Demand successfully added!";							
							}						 
						}
						elseif($resourceid==0)
						{
							$flashdatamsg =  "Sorry, info. you are looking for not found in our record!";
						}
						elseif($resourceid<0)
						{
							$flashdatamsg =  "Sorry, info. already exists!";
						}					
				}

				$this->session->set_flashdata("message", $flashdatamsg);
				$this->session->set_flashdata('alerttype', $flashdatacls);
				if($_SERVER['QUERY_STRING']!="")
				{
					redirect("outlet/".$mgmtname."?". $_SERVER['QUERY_STRING']);
				}
				else
				{
					redirect("outlet/".$mgmtname);
				}
				exit;
		}
		elseif($tasktype=="view" || $tasktype=="print")
		{
				$rsrcid = $this->uri->segment("4");
				
				if($rsrcid!="")
				{
					$rsrcid = decodeValue($rsrcid);
					if($data["info4view"] = $this->common_model->getinfo($rsrcid,$mgmttbl))
					{
						$data["transinfo4view"] = $this->common_model->getdemandinfolist($rsrcid);
						
						$data["rsrcid"] = $rsrcid;
						$data["pgheading"] = "View Demand Info.";
					}
				}
				$data['tasktype'] = $tasktype;				
				$data['mgmtname'] = $mgmtname;
				$data['main_content'] = "view".$mgmtname;
				$this->load->view('outlet/common/popup.inc.php',$data);
			
		}		
		else // for listing
		{		
			
			$fromdt = trim($this->input->get("fromdate"));
			$todt = trim($this->input->get("todate"));
			if($fromdt!="")
			{
				 $fromdate = convertdateFormat($fromdt,'Y-m-d');
				 $data['fromdate'] = $fromdate;
			}
			if($todt!="")
			{				
				$todate = convertdateFormat($todt,'Y-m-d');
				$data['todate'] = $todate;
			}

			if($fromdt=="" && $todt=="")
			{
				$data['fromdate'] = date('Y-m-d');
				$data['todate'] = date('Y-m-d');
			}
			 $totalRec = $this->common_model->listdemanddata("count", '','o2w');

			//pagination configuration
			$config['base_url']    = base_url().'outlet/'.$mgmtname;
			$config['total_rows']  = $totalRec;
			$config['per_page']    = $this->perPage;
			$config['target']    = $this->perPage;
			
			//get the list data
			$pageid = $this->uri->segment(3);
			if($pageid=="" || $pageid==0)
			{
				$pageid = 1;
			}
			$start = ($pageid - 1) * $this->perPage;
			
			$config['uri_segment'] =  $start;
			$config['num_links'] = 5;
			$this->ajax_pagination->initialize($config);
			
			$data['results'] = $this->common_model->listdemanddata("list", array('limit'=>$this->perPage,'start'=>$start),'o2w');
			
			$data["warehouselist"] = $this->common_model->getlist('warehouse', 'fld_id,fld_name','fld_name');
			$data["outletlist"] = $this->common_model->getlist('outlets', 'fld_id,fld_name','fld_name');

			$data['mgmttbl'] = $mgmttbl;
			$data['main_content'] = $mgmtname;
			$data['mgmtname'] = $mgmtname;
			$this->load->view('outlet/common/main.inc.php',$data);
		}
	}
	function dayoff()
	{
		$mgmtname = 'dayoff';		
		$tasktype = $this->uri->segment("3");
		if($tasktype=="manage")
		{
			$rsrcid = $this->uri->segment("4");
			
			$data["rsrcid"] = 0;
			if($rsrcid!="")
			{
				$rsrcid = decodeValue($rsrcid);
				if($data["info4edit"] = $this->common_model->getinfo($rsrcid, $mgmtname))
				{
					$data["billerinfo"] = $this->common_model->getinfo($data["info4edit"]->fld_userid, 'users');
					$data["rsrcid"] = $rsrcid;
					$data["pgheading"] = "Modify Day Close Info.";
					$data['mgmtname'] = $mgmtname;
					$data['main_content'] = "manage".$mgmtname;
					$this->load->view('outlet/common/main.inc.php',$data);
				}
				else
				{
					redirect('outlet/'.$mgmtname);
					exit;
				}
			}
			else
			{
					redirect('outlet/'.$mgmtname);
					exit;
			}

		}
		elseif($tasktype=="managedata")
		{
			$flashdatamsg =  "Please fill mandatory fields!";
			$flashdatacls = 'alert-danger';
				//predata($this->input->post()); exit;
				$rsrcid = $this->input->post("rsrcid");
				if($rsrcid=="" || $rsrcid==0) // for new
				{
					$amount = $this->common_model->getdayoffsale($this->outletid,$this->userid);
				}
				else
				{
					$amount = $this->input->post("totalamt");
				}

				
				$cash = $this->input->post("cash");
				$cc = $this->input->post("cc");
				$upi = $this->input->post("upi");
				$nameaccount = $this->input->post("nameaccount");
				$naremarks = $this->input->post("naremarks");
				$payamount = ($cash+$cc+$upi+$nameaccount);
				if($amount>0 && $cash!="" && $cc!="" && $upi!="" && $nameaccount!="")
				{
					if($amount==$payamount)
					{
							$data = array(
								"fld_cash" => $cash,
								"fld_cc" => $cc,
								"fld_upi" => $upi,
								"fld_nameaccount" => $nameaccount,
								"fld_naremarks" => $naremarks,
								"fld_updatedby" => $this->lguserinfo["sessID"],
								"fld_updatedon" => date("Y-m-d H:i:s")
							);
							$this->db->where("fld_id",$rsrcid);
							$this->db->update("tbl_dayoff", $data);
							//echo $this->db->last_query();
							$resourceid = $rsrcid;
						
						
						
						if($resourceid>0)
						{
							$flashdatacls =  'alert-success';
							if($rsrcid>0)
							{
								$flashdatamsg =  "Data info. successfully modified!";
							}
							else
							{
								$flashdatamsg =  " Data info. successfully added!";							
							}						 
						}
						elseif($resourceid==0)
						{
							$flashdatamsg =  "Sorry, info. you are looking for not found in our record!";
						}
						elseif($resourceid<0)
						{
							$flashdatamsg =  "Sorry, info. already exists!";
						}
					}
					else
					{
						$flashdatamsg =  "Sorry, payment info. should match total amount";
					}
				}
					$this->session->set_flashdata("message", $flashdatamsg);
					$this->session->set_flashdata('alerttype', $flashdatacls);
					if($rsrcid=="" || $rsrcid==0) // for new
					{
						redirect('outlet/'.$mgmtname."/print/".encodeValue($resourceid));
						exit;
					}
					else
					{
						redirect('outlet/'.$mgmtname."?". $_SERVER['QUERY_STRING']);
						exit;
					}
				
				
		}	
		elseif($tasktype=="view"  || $tasktype=="print")
		{
				$rsrcid = $this->uri->segment("4");
				if($rsrcid!="")
				{
					$rsrcid = decodeValue($rsrcid);
					if($data["info4view"] = $this->common_model->getdayoffinfo($rsrcid, $mgmtname))
					{
						$data["rsrcid"] = $rsrcid;
						$data["pgheading"] = "View Day Close Receipt Info.";
						$data["outletinfo"] = $this->common_model->getinfo($this->outletid, 'outlets');
					}
				}
				   
				if($this->session->flashdata("message")!="" && $this->session->flashdata("alerttype")!="" && $tasktype=="print")
				{
					$this->session->set_flashdata("message", $this->session->flashdata("message"));
					$this->session->set_flashdata('alerttype',$this->session->flashdata("alerttype"));			 
				}
        
				
				$data['tasktype'] = $tasktype;
				$data['mgmtname'] = $mgmtname;
				$data['main_content'] = "view".$mgmtname;
				$this->load->view("outlet/view".$mgmtname,$data);
				//$this->load->view('outlet/common/popup.inc.php',$data);
							
				
		}		
		else // for listing
		{
			
			$fromdt = trim($this->input->get("fromdate"));
			$todt = trim($this->input->get("todate"));
			if($fromdt!="")
			{
				 $fromdate = convertdateFormat($fromdt,'Y-m-d');
				 $data['fromdate'] = $fromdate;
			}
			if($todt!="")
			{				
				$todate = convertdateFormat($todt,'Y-m-d');
				$data['todate'] = $todate;
			}

			if($fromdt=="" && $todt=="")
			{
				$data['fromdate'] = date('Y-m-d');
				$data['todate'] = date('Y-m-d');
			}
				$totalRec = $this->common_model->listdayoffreport("count", '');
				//pagination configuration
				$config['base_url']    = $data["page_url"];
				$config['total_rows']  = $totalRec;
				$config['per_page']    = $this->perPage;
				$config['target']    = $this->perPage;
				
				//get the list data
				$pageid = $this->uri->segment(4);
				if($pageid=="" || $pageid==0)
				{
					$pageid = 1;
				}
				$start = ($pageid - 1) * $this->perPage;
				
				$config['uri_segment'] =  $start;
				$config['num_links'] = 5;
				$this->ajax_pagination->initialize($config);
				
				$data['results'] = $this->common_model->listdayoffreport("list", array('limit'=>$this->perPage,'start'=>$start));
				$data["billerlist"] = $this->common_model->getlistbywhere('users', 'fld_id,fld_name','fld_name asc','fld_outletid="'.$this->outletid.'" and fld_type="operator"');	
				
				$data['main_content'] = 'dayoff';
				$data['mgmtname'] = $mgmtname;
				$this->load->view('outlet/common/main.inc.php',$data);
		}
	}
}
