<?php

class Invoices   extends CI_Controller {
    
    var $tablename = ORDERS;
    var $tablename2 = ORDERDETAILS;
    var $primarykey = "OrderID";
        
    
    public function index(){               
        $data['current'] = "orders";                  
        $data['orders'] = $this->general->getAllRecordsWhere($this->tablename,array(),"$this->primarykey","asc");
        $this->load->view(ADMINFOLDER."/invoices",$data);
    }
    
    
    
    public function AddItem(){
        $this->load->library('form_validation');
         
        $this->form_validation->set_rules('txt_title', 'Product Title', 'trim');        
        
        $data['message'] = "";
		
        if ($this->form_validation->run() == TRUE)
	{         
            
            $Data = array(            
                "CategoryName"          => $this->input->post("txt_title"),
                "Description"           => $this->input->post("txt_desc"),               
                "FGID"          => $this->input->post("txt_type"),                
                "is_active"             => $this->input->post("txt_active"),                 
                "date_added"            => date("Y-m-d H:i:s"),
                "date_modified"         => date("Y-m-d H:i:s")
            );
                   
            
            
            $this->general->insertRecord($this->tablename, $Data);       
                                                                                                                        
            $data['message'] = "Invoice Added Successfully";
        }
            
       
        $this->load->view(ADMINFOLDER."/addorder",$data);
    }
    
    
    public function searchproduct()
    {
        $keyword = $_POST["keyword"];
        $result = "";
        
        if($keyword != "")
        {
        $query = "select *
                from ed_products                 
                where ProductID = '.$keyword.' OR ProductName COLLATE UTF8_GENERAL_CI like '%".$keyword."%' limit 5";
        
        $products = $this->general->get_query_result($query);
        
        foreach($products as $row)
        {
          $result .= "<li><a href=\"#\" id=\"pro_$row->ProductID\"  onclick=\"addproduct(".$row->ProductID.")\">".$row->ProductName."</a></li>";  
        }
        }
        echo $result;
    }
    
    public function addproducttolist()
    {
        $keyword = $_POST["id"];
        $quantity = $_POST["quan"];
        $result = "";
        
        if($keyword != "")
        {
        $query = "select *
                from ed_products                 
                where ProductID = $keyword";
        
        $products = $this->general->get_query_result($query);
        
        foreach($products as $row)
        {          
            
          $result = "<tr class=\"odd gradeX\" id=\"prow_$row->ProductID\">                                                                
                        <td id=\"proid_$row->ProductID\">$row->ProductID</td>                                                                
                        <td><img src=\"".base_url()."images/products/".$this->ImageProcess->returnThumb($row->Picture)."?".date("Y-m-d-H:i:s")."\"></td>
                        <td>$row->ProductName</td>
                        <td id=\"quan_$row->ProductID\">$quantity</td>
                        <td id=\"price_$row->ProductID\">$row->UnitPrice</td>    
                        <td id=\"total_$row->ProductID\">$row->UnitPrice</td>    
                        <td><a href=\"#\" onclick=\"deleteproduct($row->ProductID)\">delete</a></td>
                </tr>";
        }
        }
        echo $result;
    }
    
    
    public function  addorder()
    {
        $prohtml = $_POST["prohtml"];
        
        //====================================        
        	
	$DOM = new DOMDocument();
	$DOM->loadHTML($prohtml);
	
	$Header = $DOM->getElementsByTagName('th');
	$Detail = $DOM->getElementsByTagName('td');

    //#Get header name of the table
	foreach($Header as $NodeHeader) 
	{
		$aDataTableHeaderHTML[] = trim($NodeHeader->textContent);
	}
	//print_r($aDataTableHeaderHTML); die();

	//#Get row data/detail table without header name as key
	$i = 0;
	$j = 0;
	foreach($Detail as $sNodeDetail) 
	{
		$aDataTableDetailHTML[$j][] = trim($sNodeDetail->textContent);
		$i = $i + 1;
		$j = $i % count($aDataTableHeaderHTML) == 0 ? $j + 1 : $j;
	}
	//print_r($aDataTableDetailHTML); die();
	
	//#Get row data/detail table with header name as key and outer array index as row number
	for($i = 0; $i < count($aDataTableDetailHTML); $i++)
	{
		for($j = 0; $j < count($aDataTableHeaderHTML); $j++)
		{
			$aTempData[$i][$aDataTableHeaderHTML[$j]] = $aDataTableDetailHTML[$i][$j];
		}
	}
	$aDataTableDetailHTML = $aTempData; unset($aTempData);
	//print_r($aDataTableDetailHTML); die();
        
        // add order
          $Data = array(            
                "CustomerID"            => $this->session->userdata("AdminID"),
                "OrderDate"             => date("Y-m-d H:i:s"),               
                "SalesTax"              => "0.05",                
                "Timestamp"             => date("Y-m-d H:i:s"),                 
                "Paid"                  => 1,                
                "PaymentDate"           => date("Y-m-d H:i:s"),                
                "is_active"             => 1,                 
                "date_added"            => date("Y-m-d H:i:s"),
                "date_modified"         => date("Y-m-d H:i:s")
            );
                                           
            $this->general->insertRecord(ORDERS, $Data);  
            
            $orderid = $this->db->insert_id();
            
            // add order details
            foreach ($aDataTableDetailHTML as $pro)
            {
               
                    $Data2 = array(            
                    "OrderID"               => $orderid,
                    "ProductID"             => $pro["ID"],               
                    "Price"                 => $pro["Price"],                
                    "Quantity"              => $pro["Quantity"],                 
                    "Discount"              => 0,                
                    "Total"                 => $pro["Total"],                
                    "BillDate"              => date("Y-m-d H:i:s"),
                    "is_active"             => 1,                 
                    "date_added"            => date("Y-m-d H:i:s"),
                    "date_modified"         => date("Y-m-d H:i:s")
                    );

                    $this->general->insertRecord(ORDERDETAILS, $Data2);                                           
            }
        // ===================================
        
        
        echo $orderid;        
    }
    
    
    public function printorder($orderid)
    {      
        $query = "select od.*,p.ProductName
                from ed_orderdetails od
                LEFT JOIN ed_products p ON od.ProductID = p.ProductID
                where OrderID = $orderid";
        
        $orderdetails = $this->general->get_query_result($query);
        
        $order = $this->general->getRecordWhere(ORDERS,array("OrderID"=>$orderid),"OrderID","desc");
        
        $html = "<p>Order ID : $orderid</p><p>Order Date : $order->OrderDate</p> 
            <table id=\"example\" class=\"table table-striped table-bordered\" cellspacing=\"0\" width=\"100%\" border=\"1\">
						<thead>
							<tr>
                                                                <th>ID</th>                                                                
								<th>Product Title</th>							
								<th>Quantity</th>
                                                                <th>Price</th>
                                                                <th>Total</th>								
							</tr>
						</thead>
						<tbody id=\"tbodycont\">";
        $totalamount = 0;
        foreach ($orderdetails as $row)
        {
            $html.="<tr class=\"odd gradeX\" id=\"prow_$row->OrderDetailID\">                                                                
                        <td id=\"proid_$row->OrderDetailID\">$row->ProductID</td>                                                                                        
                        <td>$row->ProductName</td>
                        <td id=\"quan_$row->OrderDetailID\">$row->Quantity</td>
                        <td id=\"price_$row->OrderDetailID\">$row->Price</td>    
                        <td id=\"total_$row->OrderDetailID\">$row->Total</td>                            
                </tr>";
            
            $totalamount+=$row->Total;            
        }
        
        $html.= "<tr class=\"odd gradeX\" id=\"prow_final\"><td colspan=\"4\"></td><td><b>Total :</b> $totalamount</td></tr>";
        $html.= "</tbody></table>";
        
        
        echo $html;
    }

    public function editItem($id){
        $this->load->library('form_validation');
         
        $this->form_validation->set_rules('txt_title', 'Category Title', 'trim|required');
        $this->form_validation->set_rules('txt_desc', 'Category Description', 'trim');
        
        $data['message'] = "";
		
        if ($this->form_validation->run() == TRUE)
	{                        
            
            $slug = $this->general->SEF_URLS($this->input->post("txt_title"));
            $Data = array(       
                "$this->primarykey" 	=> $id,
                "CategoryName"          => $this->input->post("txt_title"),
                "Description"           => $this->input->post("txt_desc"),
                "slug"                  => $slug,
                "FGID"                  => $this->input->post("txt_type"),
                "is_active"             => $this->input->post("txt_active"),                                 
                "date_modified"         => date("Y-m-d H:i:s")
            );
                        
            if($this->session->userdata("pid") != "")
            {
                $Data["PCategoryID"] = $this->session->userdata("pid");
            }
            
            $this->general->updateRecord($this->tablename, $Data , "$this->primarykey");       
                        
            
            $tablename = $this->tablename;
            $imagefieldid = $id;
            $imagefieldslist = array("pic");


            // ==================== upload image
            $inputName      = "txt_image";            
            if(isset($_FILES[$inputName]) &&  $_FILES[$inputName]['name'] != ""){                                                                                  
            $oldimagename   = "old_image_image";                                    
            $imagefolder    = "categories";                                   
            $updatedfield   = "pic";                        
            $imageWidth     = "400";
            $imageHeight    = "400";
            $thumbimageWidth     = "100";
            $thumbimageHeight    = "100";             
            $resultimage = $this->ImageProcess->imageUpload($oldimagename,$slug,$imagefolder,$imageWidth,$imageHeight,$thumbimageWidth,$thumbimageHeight,$inputName,$tablename,$updatedfield,$imagefieldslist,$imagefieldid, $this->primarykey);            
            }
            // ===================================
                        
                        
                        
            $data['message'] = "Category Updated Successfully";
        }
            
        $data['record'] = $this->general->getRecordWhere($this->tablename,array("$this->primarykey"=>$id), "$this->primarykey","desc");    
        $this->load->view(ADMINFOLDER."/editcategory",$data);                       
    }
    
                
    public function delete($id){        
        $newsRecord = $this->general->getRecordWhere($this->tablename, array("$this->primarykey"=>$id));
			if(count($newsRecord)){
				                            
                                
                                                if(file_exists("images/categories/".$newsRecord->pic)){
                                                @unlink("images/categories/".$newsRecord->pic);
                                                }
                                            
                                                if(file_exists("images/categories/".$this->ImageProcess->returnThumb($newsRecord->pic))){
                                                @unlink("images/categories/".$this->ImageProcess->returnThumb($newsRecord->pic));
                                                }
                                                                            

				$this->db->query("DELETE FROM ".$this->tablename." WHERE $this->primarykey = $id");
				$data['message'] = $this->general->generateMessage("Record Deleted Successfully !!!", "green");
			}else{
				$data['message'] = $this->general->generateMessage("No record found with the specified id.", "red");
			}        
                        
            if($this->session->userdata("pid") != "")
            {                
                $this->viewSubCategory($this->session->userdata("pid"));
            }
            else {  $this->index();  }
            
    }
    
                   
}
