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

class Quotations extends CI_Controller {

    var $main_menu_name = "quotations";
	var $sub_menu_name = "quotations";

	public function __construct()
	{
		parent::__construct();

		
		$this->load->model('Quotations_Model');
		$this->load->model('Supplier_Model');
		$this->load->model('Warehouse_Model');
		$this->load->model('Common_Model');
		$this->load->model('Tax_Rates_Model');
		$this->load->model('Customer_Model');
		$this->load->model('Sequerty_Model');
		$this->load->model('User_Model');
			$this->load->model('Sales_Model');
		$this->load->library('email');
		
		
	}
	
	//Quotations list page load
	public function index()
	{
		$data['quotations'] = $this->Quotations_Model->get_all_quotations();
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
        $this->load->view('quotations',$data);
	}	
	
	
	public function send_email_data($qts_id)
	{
	    $qts_details= $this->Quotations_Model->get_qts_info($qts_id);
		
		//get sale item list
		$qts_item_list= $this->Quotations_Model->get_qts_item_list_by_qts_id($qts_id);
		
		$customer_details= $this->Customer_Model->get_customer_info($qts_details['customer_id']);
		$warehouse_details= $this->Warehouse_Model->get_warehouse_info($qts_details['warehouse_id']);
		
		$base_url=asset_url();
		$msg='';
		$msg='<style type="text/css">
		td{
			padding:5px;
		}
		</style>';
		
		$msg.="<img src=\"$base_url/images/email_header.jpg\" width=\"50%\" > ";
		$msg.="<h2 style=\"text-align:left\">Quotation</h2>";
		$msg.="<table style=\"width:50%;\">";
		$msg.="<tr style=\"padding:10px\">";
		$msg.="<td colspan=\"4\" style=\"text-align:right\">No : </td>";
		$msg.="<td style=\"text-align:left\"> ".$qts_details['qts_reference_no']."  </td>";
		$msg.="</tr>";
		$msg.="<tr>";
		$msg.="<td colspan=\"4\" style=\"text-align:right\">Date : </td>";
		$msg.="<td style=\"text-align:left\"> ".date('d/M/Y', strtotime($qts_details['qts_datetime']))."  </td>";
		$msg.="</tr>";
		$msg.="<tr>";
		$msg.="<tr>";
		$msg.="<td style=\"text-align:center; font-weight: bold;\"> Qty. </td>";
		$msg.="<td style=\"text-align:center; font-weight: bold;\"> Description  </td>";
		$msg.="<td style=\"text-align:center; font-weight: bold;\"> Unite Price  </td>";
		$msg.="<td style=\"text-align:center; font-weight: bold;\"> Discount  </td>";
		$msg.="<td style=\"text-align:center; font-weight: bold;\"> Subtotal  </td>";
		$msg.="</tr>";
		

 
		$tmpcount=0;
		foreach ($qts_item_list as $row)
		{
			$tmpcount++;
			$msg.="<tr>";
			$msg.="<td style=\"text-align:center\"> ".number_format($row['quantity'], 0, '.', '')."  </td>";
			$msg.="<td> $row[product_name]</td>";
			$msg.="<td style=\"text-align:right\">".number_format($row['unit_price'], 2, '.', ',')."   </td>";
			$msg.="<td style=\"text-align:right\">" .number_format($row['discount_val'], 2, '.', ',')."  </td>";
			$msg.="<td style=\"text-align:right\"> ".$row['gross_total']."  </td>";
			$msg.="</tr>";
		}
		
		$msg.="<tr>";
		$msg.="<td colspan=\"4\" style=\"text-align:right\">Order Discount</td>";
		$msg.="<td style=\"text-align:right\"> ".number_format($qts_details['qts_inv_discount_amount'], 2, '.', ',')."  </td>";
		$msg.="</tr>";
		$msg.="<tr>";
		$msg.="<td colspan=\"4\" style=\"text-align:right; font-weight: bold;\">Total Amount </td>";
		$msg.="<td style=\"text-align:right; font-weight: bold;\"> ".number_format($qts_details['qts_total'], 2, '.', ',')."  </td>";
		$msg.="</tr>";
  
		$msg.="</table>";
		
		
		
		return $msg;
		
		
		
		$data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();
        return $this->load->view('models/quotations_print',$data);
        
	    
	   // return "Smart Phone System";
	}
	
	public function send_email()
	{
		$qts_id=$this->input->get('qts_id');
		$cus_email=$this->input->get('cus_email');
		$data['qts_item_list']= $this->Quotations_Model->get_qts_item_list_by_qts_id($qts_id);
		$data['qts_details']= $this->Quotations_Model->get_qts_info($qts_id);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['qts_details']['warehouse_id']);
		
		
		 $msg="Smart Phone System";
		 $subject="New Qutation";
		 $email=$cus_email;//'sanath.sallelanka@gmail.com';
		 //send email start 
		 $body='Test Email';// $CI->load->view('employer/employer_email/'.$page_name, $email_data, TRUE);
		 
		 $body=$this->send_email_data($qts_id);
		// echo "$body";
					
                    $config= array(
                        'protocol' => 'smtp', // 'mail', 'sendmail', or 'smtp'
                        'smtp_host' => 'mail.smartphone.salleepos.com.lk',
                        'smtp_port' => 587,
                        'smtp_user' => '_mainaccount@smartphone.salleepos.com.lk',
                        'smtp_pass' => 'Sallelanka#987',
                        'mailtype' => 'text', //plaintext 'text' mails or 'html'
                        'smtp_timeout' => '5', //in seconds
                        'charset' => 'iso-8859-1',
                        'wordwrap' => TRUE
                    );
                    $this->load->library('email', $config);
                    $this->email->set_newline("\r\n");
                    //$this->email->from('mail.smartphone.salleepos.com.lk@server.salleepos.com.lk'); // change it to yours
                    $this->email->from('mail.smartphone.salleepos.com.lk@server.salleepos.com.lk'); // change it to yours
                    $this->email->to($email); // change it to yours
                    $this->email->subject($subject);
                    $this->email->set_mailtype("html");
                    $this->email->message($body);
					$status=0;
					
					if($email){
                    if ($this->email->send()) {
						 
                   //     $email_status = 1;
                      //  print_r($this->email->print_debugger()); 
					  $status=1;
                   }
					}
                //  else {
						
                   //     $email_status = 0;
                      //  print_r($this->email->print_debugger());  
                  //  }
                  //  echo "Test:".$email_status;
                    
             //   return $email_status;
		 

		 
		  $st = array('status' =>$status,'validation' => validation_errors());
         echo json_encode($st);
	}
	
	//Quotations details view
	public function view()
	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = '';
		
		//get sale id
		$qts_id=$this->uri->segment('3');
		$data['qts_item_list']= $this->Quotations_Model->get_qts_item_list_by_qts_id($qts_id);
		$data['qts_details']= $this->Quotations_Model->get_qts_info($qts_id);
		
	
		$data['customer_details']= $this->Customer_Model->get_customer_info($data['qts_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['qts_details']['warehouse_id']);		
		$data['sale_payments_list']= $this->Quotations_Model->get_qts_payments_by_quotations_id($qts_id);
		$data['qts_id']=$qts_id;
        $this->load->view('quotations_view',$data);
	}

	//Quotations add page
	public function add_qts_payments()
	{
		$qts_pymnt_amount=$this->input->post('qts_pymnt_amount');
		$qts_id=$this->input->post('qts_id');
		$qts_pymnt_ref_no=$this->input->post('qts_pymnt_ref_no');
		$qts_pymnt_paying_by=$this->input->post('qts_pymnt_paying_by');
		$qts_pymnt_date_time=$this->input->post('qts_pymnt_date_time');
		$qts_pymnt_date_time_send=date('Y-m-d H:i:s', strtotime($qts_pymnt_date_time));
		$qts_pymnt_cheque_no=$this->input->post('qts_pymnt_cheque_no');
		$qts_pymnt_crdt_card_no=$this->input->post('qts_pymnt_crdt_card_no');
		$qts_pymnt_crdt_card_holder_name=$this->input->post('qts_pymnt_crdt_card_holder_name');
		$qts_pymnt_crdt_card_month=$this->input->post('qts_pymnt_crdt_card_month');
		$qts_pymnt_crdt_card_year=$this->input->post('qts_pymnt_crdt_card_year');
		$qts_pymnt_crdt_card_type=$this->input->post('qts_pymnt_crdt_card_type');
		$qts_type = $this->input->post('qts_type');

		$qts_pymnt_note=$this->input->post('qts_pymnt_note');
		$user_id=$this->session->userdata('ss_user_id');
		$qts_pymnt_added_date_time=date("Y-m-d H:i:s");
		$qts_pymnt_id='';
		
        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('qts_pymnt_amount', 'Amount', 'required');
		if($qts_pymnt_paying_by=='Credit Card'){
			$this->form_validation->set_rules('qts_pymnt_crdt_card_type', 'Card Type', 'required');
			$this->form_validation->set_rules('qts_pymnt_crdt_card_no', 'Credit Card No', 'required');
			$this->form_validation->set_rules('qts_pymnt_crdt_card_holder_name', 'Holder Name', 'required');
			$this->form_validation->set_rules('qts_pymnt_crdt_card_month', 'Month', 'required');
			$this->form_validation->set_rules('qts_pymnt_crdt_card_year', 'Year', 'required');
		}
		if($qts_pymnt_paying_by=='Cheque'){
			$this->form_validation->set_rules('qts_pymnt_cheque_no', 'Cheque No', 'required');
		}
		$this->form_validation->set_rules('qts_id', 'System Error', 'required');


        if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
			$data=array(
				'qts_pymnt_amount'=>$qts_pymnt_amount,	
				'qts_pymnt_ref_no'=>$qts_pymnt_ref_no,
				'qts_pymnt_paying_by'=>$qts_pymnt_paying_by,
				'qts_pymnt_date_time'=>$qts_pymnt_date_time_send,
				'qts_pymnt_note'=>$qts_pymnt_note,
				'user_id'=>$user_id,
				'qts_id'=>$qts_id,
				'qts_pymnt_added_date_time'=>$qts_pymnt_added_date_time,
				'qts_pymnt_cheque_no'=>$qts_pymnt_cheque_no,
				'qts_pymnt_crdt_card_no'=>$qts_pymnt_crdt_card_no,
				'qts_pymnt_crdt_card_holder_name'=>$qts_pymnt_crdt_card_holder_name,
				'qts_pymnt_crdt_card_type'=>$qts_pymnt_crdt_card_type,
				'qts_pymnt_crdt_card_month'=>$qts_pymnt_crdt_card_month,
				'qts_pymnt_crdt_card_year'=>$qts_pymnt_crdt_card_year,
				'qts_payment_type' => $qts_type
			);
			
               if ($this->Quotations_Model->save_qts_payments($data,$qts_pymnt_id)) {
                    $st = array('status' =>1,'validation' =>'Done!');
                    echo json_encode($st);
               } else {
                    $st = array('status' =>0,'validation' =>'error occurred please contact your system administrator');
                    echo json_encode($st);
               }
		}
	}	
	
	//Quotations payment page 
	public function payments()
	{
        $data['qts_id'] = $this->input->get('id');
        $data['qts_type'] = $this->input->get('qts_type');
        $this->load->view('models/quotations_payment',$data);	
	}
	
	//Quotations save 
	//Quotations item save
	//Add quotations items to 54 table
	public function save_quotations()
	{
	    
	  
		
	//	print_r($this->input->post());
		$qts_type=$this->input->post('qts_type');
		 // echo "qts_type:$qts_type";
		$warehouse_id=$this->input->post('warehouse_id');
		$customer_id=$this->input->post('customer_id');
		$rowCount=$this->input->post('rowCount');
		$type_code='';
		if($qts_type=='Quotations') $type_code='Q';
		if($qts_type=='Sales Advance') $type_code='SA';
		
		//$qts_reference_no=$this->input->post('qts_reference_no');
				//start get next referance no
				$warehouse_id=$this->session->userdata('ss_warehouse_id');
				//echo "warehouse_id:$warehouse_id";
				$warehouse_dtls=$this->Warehouse_Model->get_warehouse_info($warehouse_id);
				//print_r($warehouse_dtls);
				$warehouse_code=$warehouse_dtls['code'];
				$warehouse_last_id=(1+$this->Common_Model->get_next_warehouse_and_type_ref_no($warehouse_id,'warehouse_id','warehouse_last_id','quotations',$qts_type));
				
				//
				
				$qts_reference_no=$warehouse_code."/$type_code/".sprintf("%04d",$warehouse_last_id);
				//end get next referance no
				
		$qts_datetime_1=$this->input->post('qts_datetime');
		$qts_datetime=date('Y-m-d H:i:s', strtotime($qts_datetime_1));
		
		$qts_inv_discount=$this->input->post('qts_inv_discount');
		
		
		
		
		$qts_total=$this->input->post('qts_total');
		
		
		$qts_inv_discount_amount=$this->input->post('qts_inv_discount_amount');
		$qts_datetime_created=date('Y-m-d H:i:s');
		
		$error='';
		$disMsg='';
		$lastid='';
		$qts_id='';
		
		if(!$error){
			$data=array(
				'qts_reference_no'=>$qts_reference_no,
				'warehouse_id'=>$warehouse_id,
				'customer_id'=>$customer_id,
				'warehouse_id'=>$warehouse_id,
				'qts_datetime'=>$qts_datetime,
				
				'qts_inv_discount'=>$qts_inv_discount,
				'qts_total'=>$qts_total,
				'qts_type'=>$qts_type,
				'warehouse_last_id'=>$warehouse_last_id,
				
				'qts_datetime_created'=>$qts_datetime_created,
				'qts_inv_discount_amount'=>$qts_inv_discount_amount,
				
			);
			//print_r($data);
			$_insert=$this->Quotations_Model->save_quotations($data,$qts_id);
			$lastid=$this->db->insert_id();
			$qts_id=$lastid;
			$disMsg='Quotation successfully added';
			
			//insert sale item data
			$row=$this->input->post('row');
			$rowCount=$this->input->post('rowCount');
			$data_item=array();
			for($i=1; $i<=$rowCount; $i++){
				if(isset($row[$i]['product_id'][0]))
				{
					
				$data_item=array(
					'qts_id'=>$qts_id,
					'product_id'=>$row[$i]['product_id'][0],
					'quantity'=>$row[$i]['qty'][0],
					'discount'=>$row[$i]['discount'][0],
					'unit_price'=>$row[$i]['unit_price'][0]+$row[$i]['item_price_p'][0],
					'discount_val'=>$row[$i]['discount_val'][0], 
					'gross_total'=>$row[$i]['gross_total'][0]
				);
				$this->Quotations_Model->save_quotations_item($data_item);
				
				//add reford for f4 table
				$type='sale';
				$ref_id=$qts_id;
				$product=$row[$i]['product_id'][0];
				$quantity=$row[$i]['qty'][0];
				$unit_cost=$row[$i]['unit_price'][0];
				$this->Common_Model->add_fi_table($type,$ref_id,$product,$quantity,$unit_cost);
				}
			}
		
		}else {
			
			$disMsg='Please select these before adding any product:'.$disMsg;
		}	
		
		$this->session->set_flashdata('message', 'Quotation successfully added!');
		
		echo json_encode(array('qts_id'=>$lastid,'error'=>$error,'disMsg'=>$disMsg,));
	}

	//Quotations reference no jenarate	
	public function get_next_ref_no(){
		$query=$this->Quotations_Model->get_next_ref_no();
		$result = $query->row();
		//print_r($result);
		$qts_reference_no=sprintf("%05d", $result->qts_id+1);
		$qts_reference_no=$qts_reference_no;
		echo json_encode(array('qts_reference_no'=>$qts_reference_no));
	}
	
	//Quotations ger avalable product qty
	public function get_avalable_product_qty(){
		$product_id=$this->input->get('product_id');
		$warehouse_id=$this->input->get('warehouse_id');
		
		$data['total']=$this->Quotations_Model->get_avalable_product_qty($product_id,$warehouse_id);
		echo json_encode(array('remmnaingQty'=>$data['total']));
	}

	//Quotations add form
    public function quotations_add()
    {
		
		//echo "111111";
		//die();
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'quotations_add';
		
		//get suppliers list
		$data['suppliers'] = $this->Supplier_Model->get_all_supplier();
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['tax_rates_list'] = $this->Tax_Rates_Model->get_all_tax_rates();
		$data['customer_list'] = array();//$this->Customer_Model->get_all_customers();
		$data['status_list'] = $this->Common_Model->get_all_status();
		
        $this->load->view('quotations_add',$data);
    }
	
	//Quotations product items get
	 public function suggestions($value='')
    {
		$term=$this->input->get('term');
		$data['quotations'] = $this->Quotations_Model->get_products_suggestions($term);
		$json = array();
		//echo "Count:".count($data['quotations']);
		//print_r($data['quotations']);
		foreach ($data['quotations'] as $row)
		{
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_id=$row['product_id'];
			$product_price=$row['product_price'];
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			$extraName.=", Selling Price: ".number_format($product_price, 2, '.', ',');
			if($product_part_no) $extraName.=", Part No: $product_part_no";
			if($product_oem_part_number) $extraName.=", Product Model: $product_oem_part_number";
			
			 $json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $row['product_price'],
					'product_part_no'=> $row['product_part_no'],
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName"
                    );
					array_push($json,$json_itm);
		}		
		echo json_encode($json);		
    }
	
	//Sale details page
	public function qts_details()
	{
		
		$qts_id=$this->input->get('qts_id');
		$data['qts_details']= $this->Quotations_Model->get_qts_info($qts_id);
		
		//get sale item list
		$data['qts_item_list']= $this->Quotations_Model->get_qts_item_list_by_qts_id($qts_id);
		
		$data['customer_details']= $this->Customer_Model->get_customer_info($data['qts_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['qts_details']['warehouse_id']);
		
		$data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();
        $this->load->view('models/quotations_print',$data);
	}	
	
	//Quotations list
	public function list_quotations()
	{
	$requestData= $_REQUEST;
	$search_key=$this->input->post('search');
	$search_key_val=$search_key['value'];

	$start=$this->input->post('start');

	$length=$this->input->post('length');
	$warehouse_id=$this->input->post('warehouse_id');
	$srh_user_id=$this->input->post('srh_user_id');
	$srh_from_date=$this->input->post('srh_from_date');
	$srh_to_date=$this->input->post('srh_to_date');
	$qts_type=$this->input->post('qts_type');
	
	$columns = array( 
		0 =>'qts_id', 
		1 => 'qts_id',
		2=> 'qts_id',
		3 =>'qts_id', 
		4 => 'qts_id',
		5=> 'qts_id'
	);
	
	$data = array();
	$quotations = $this->Quotations_Model->get_all_quotations($start,$length,$search_key_val,$srh_user_id,$warehouse_id,$srh_from_date,$srh_to_date,$qts_type);
	$totalData = $this->Quotations_Model->get_all_quotations($start,$length,$search_key_val,$srh_user_id,$warehouse_id,$srh_from_date,$srh_to_date,$qts_type,'get_count');
	$totalFiltered = $totalData;  
	
	foreach ($quotations as $row){
		$nestedData=array(); 
		$qts_id=$row['qts_id'];
		$total_paid_amount='';
		$nestedData[] =display_date_time_format($row['qts_datetime']);
		$nestedData[] = $row['qts_reference_no'];
		$nestedData[] = $row['qts_type'];
		$nestedData[] = $row['cus_name'];
		
		$nestedData[] = number_format($row['qts_total'], 2, '.', ',');
		
		
		
		//$nestedData[] = $row['qts_id'];
		$actionTxtDisble='';
		$actionTxtEnable='';
		$actionTxtUpdate='';
		$actionTxtDelete='';
		
		$url=base_url("quotations/qts_details?qts_id=$qts_id");
		$actionTxtUpdate='<a onClick="fbs_click('.$row['qts_id'].')" data-toggle="modal" href="#" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="clip-zoom-in-2"></i></a> &nbsp;';
		
		$actionTxtViewDetails='<a href="'.base_url().'quotations/view/'.$qts_id.'" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-file-text-o"></i></a> &nbsp;';
		
	///add_sales//0/21074/13
	$add_sale_link='';
	if($row['qts_type']=='Sales Advance')
	{
		$add_sale_link=' <li><a href="'.base_url().'sales/add_sales/'.$qts_id.'"><i class="fa fa-file-text-o"></i> Add Sale</a></li>';
		//$add_sale_link='';
	}
	$nestedData[] = '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="'.base_url().'quotations/view/'.$qts_id.'"><i class="fa fa-file-text-o"></i> Details</a></li>'.$add_sale_link.'
                            <li><a onClick="fbs_click('.$row['qts_id'].')" data-toggle="modal" href="#" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-print"></i> Print Quotation</a></li>
							
                            </ul></div>';
	
	$data[] = $nestedData;
}

	$json_data = array(
			//"draw"            => intval( $requestData['draw'] ),  
			"recordsTotal"    => intval( $totalData ),  
			"recordsFiltered" => intval( $totalFiltered ),
			"data"            => $data 
			);

	echo json_encode($json_data); 
	}
}