<?php
   header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Security-Policy: default-src 'self';");
   require APPPATH . '/libraries/REST_Controller.php';
   use Restserver\Libraries\REST_Controller;
     
class Purchase extends REST_Controller {
    
	  /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function __construct() {
       parent::__construct();
       $this->load->database();
    }
       
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
	public function index_get($id = 0,$date = "",$tdate="",$supplier = "")
	{
	    $index = 0;
	    if(!empty($date)){
	        $date =$this->db->escape_str($date);
	    }
	    if(!empty($tdate)){
	        $tdate =$this->db->escape_str($tdate);
	    }
	    if(!empty($supplier)){
	        $supplier =$this->db->escape_str($supplier);
	    }
	    if(empty($tdate)){
	        $tdate = $date;
	    }
	    $sql = "SELECT * FROM PurchaseHeader LEFT OUTER JOIN Supplier ON PurchaseHeader.SupplierId = Supplier.SupplierId " 
	           ."WHERE ((PurchaseHeader.PurchaseDate BETWEEN '".$date."' AND DATE_ADD('".$tdate."', INTERVAL 1 DAY)) " 
	           ."OR ('".$date."' = '')) AND ((Supplier.SupplierName LIKE '%".rawurldecode($supplier)."%') OR ('".$supplier."'='')) AND ((PurchaseHeader.PurchaseHeaderId = ".$id.") OR (".$id."=0)) AND IsDeleted = 0";
        $purchaseHead = $this->db->query($sql)->result();
        $data = null;
        foreach ($purchaseHead as $pHead){
            $pDets = $this->db->query("SELECT PurchaseDetails.PurchaseDetId,PurchaseDetails.PurchaseHeaderId, PurchaseDetails.ItemId, Item.ItemName,PurchaseDetails.PurchaseDetQty,PurchaseDetails.PurchasePrice ItemPrice,PurchaseDetails.TotalPrice 
FROM PurchaseDetails JOIN Item ON PurchaseDetails.ItemId = Item.ItemId WHERE PurchaseDetails.PurchaseHeaderId=".$pHead->PurchaseHeaderId)->result();
            $data[$index] = array(
                'PurchaseHeaderId' => $pHead->PurchaseHeaderId,
                'PurchaseVoucherNo' => $pHead->PurchaseVoucherNo,
                'SupplierId' => $pHead->SupplierId,
                'SupplierName' => $pHead->SupplierName,
                'SupplierAddress' => $pHead->SupplierAddress,
                'SupplierPhone' => $pHead->SupplierPhone,
                'PurchaseDate' => $pHead->PurchaseDate,
                'PurchaseAmount' => $pHead->PurchaseAmount,
                'TransportCost' => $pHead->TransportCost,
                'PurchaseRemark' => $pHead->PurchaseRemark,
                'IsReceived' => $pHead->IsReceived,
                'PaymentMethodId' => $pHead->PaymentMethodId,
                'PurchaseDetail' => $pDets);
            
            $index++;
        }
     
        $this->response($data, REST_Controller::HTTP_OK);
	}
      
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function index_post($type)
    {
        if($type==='new'){
            $input = $this->input->post();
            $pHeader = array(
                    'PurchaseHeaderId' => $input['PurchaseHeaderId'],
                    'PurchaseVoucherNo' => $this->db->escape_str($input['PurchaseVoucherNo']),
                    'SupplierId' => $input['SupplierId'],
                    'PurchaseDate' => $input['PurchaseDate'],
                    'PurchaseAmount' => $input['PurchaseAmount'],
                    'TransportCost' => $input['TransportCost'],
                    'PurchaseRemark' => $this->db->escape_str($input['PurchaseRemark']),
                    'IsReceived' => intval($input['IsReceived']),
                    'IsDeleted' => 0,
                    'PaymentMethodId' => $input['PaymentMethodId'],
                    'CreatedDateTime' => date("Y-m-d H:i:s"),
                    'CreatedBy' => $input['CreatedBy']
            );
            $this->db->insert('PurchaseHeader',$pHeader);
            $insert_id = $this->db->insert_id(); 
            
            foreach ($input['PurchaseDetail'] as $rowDet) {
                $pDet = array(
                        'PurchaseHeaderId' => $insert_id,
                        'PurchaseDetId' => '0',
                        'ItemId' => $rowDet['ItemId'],
                        'PurchasePrice' => $rowDet['PurchasePrice'],
                        'PurchaseDetQty' => $rowDet['PurchaseDetQty'],
                        'TotalPrice' => $rowDet['TotalPrice'],
                        'PurchaseDetRemark' => ''
                );
                
                $this->db->insert('PurchaseDetails',$pDet);
            }
            $this->response(['Purchase created successfully.'], REST_Controller::HTTP_OK);
        }
        else if ($type==='update'){
            $input = $this->input->post();
            $pHeader = array(
                    'PurchaseHeaderId' => $input['PurchaseHeaderId'],
                    'PurchaseVoucherNo' => $this->db->escape_str($input['PurchaseVoucherNo']),
                    'SupplierId' => $input['SupplierId'],
                    'PurchaseDate' => $input['PurchaseDate'],
                    'PurchaseAmount' => $input['PurchaseAmount'],
                    'TransportCost' => $input['TransportCost'],
                    'PurchaseRemark' => $this->db->escape_str($input['PurchaseRemark']),
                    'IsReceived' => intval($input['IsReceived']),
                    'IsDeleted' => 0,
                    'PaymentMethodId' => $input['PaymentMethodId'],
                    'CreatedDateTime' => date("Y-m-d H:i:s"),
                    'CreatedBy' => $input['CreatedBy']
            );
            $this->db->update('PurchaseHeader', $pHeader, array('PurchaseHeaderId'=>$input['PurchaseHeaderId']));
            $this->db->delete('PurchaseDetails', array('PurchaseHeaderId'=>$input['PurchaseHeaderId']));
            foreach ($input['PurchaseDetail'] as $rowDet) {
                $pDet = array(
                        'PurchaseHeaderId' => $insert_id,
                        'PurchaseDetId' => '0',
                        'ItemId' => $rowDet['ItemId'],
                        'PurchasePrice' => $rowDet['PurchasePrice'],
                        'PurchaseDetQty' => $rowDet['PurchaseDetQty'],
                        'TotalPrice' => $rowDet['TotalPrice'],
                        'PurchaseDetRemark' => ''
                );
                
                $this->db->insert('PurchaseDetails',$pDet);
            }
         
            $this->response(['Purchase updated successfully.'], REST_Controller::HTTP_OK);
        }else if ($type==='delete') {
            $input = $this->input->post();
            $pHeader = array(
                    'IsDeleted' => 1,
                    'CreatedDateTime' => date("Y-m-d H:i:s")
            );
            $this->db->update('PurchaseHeader', $pHeader, array('PurchaseHeaderId'=>$input['PurchaseHeaderId']));
            
            $this->response(['Purchase delete successfully.'], REST_Controller::HTTP_OK);
        }
        
         
        
    } 
     
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function index_put($id)
    {
        $input = $this->put();
        $this->db->update('products', $input, array('id'=>$id));
     
        $this->response(['Product updated successfully.'], REST_Controller::HTTP_OK);
    }
     
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function index_delete($id)
    {
        $this->db->delete('products', array('id'=>$id));
       
        $this->response(['Product deleted successfully.'], REST_Controller::HTTP_OK);
    }
    	
}