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

class Daraz_order extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
	}

    public function xss_html_filter($input){
        return $this->security->xss_clean(html_escape($input));
    }

    public function index(){
        $this->permission_check('import_daraz');
        $data=$this->data;
        $data['page_title']='Daraz Orders';
        $this->load->view('import/import_daraz_orders', $data);
    }

    public function import_daraz_orders_csv() {
        extract($this->xss_html_filter(array_merge($this->data)));
        $filename = $_FILES["import_file"]["name"];
        
        if($_FILES['import_file']['size'] > 0)
        {   
            
            $config['upload_path']          = './uploads/csv/daraz_orders';
            $config['allowed_types']        = 'csv';
            $this->load->library('upload', $config);

            if ( ! $this->upload->do_upload('import_file')){
                    $error = array('error' => $this->upload->display_errors());
                    print($error['error']);
                    exit();
            }
            else{
                    $file_name=$this->upload->data('file_name');
            }
            
            $csv_file = fopen('uploads/csv/daraz_orders/'.$file_name,"r");
            $duplicate_val = array();
            $dup_count = 0; 
            // $this->db->trans_begin();
            $j=1;
            while(($importdata1 = fgetcsv($csv_file, NULL, ",")) !== FALSE){
                if($j++==1){ continue; }
                
                $importdata1=$this->xss_html_filter($importdata1);

                $s_OrderNumber = trim($importdata1[8]);
                $qs_dup="SELECT COUNT(id) AS o_id_count FROM db_daraz_orders WHERE OrderNumber='$s_OrderNumber';";
                $q_dup=$this->db->query($qs_dup);
                $o_id_count=$q_dup->row()->o_id_count;
                if($o_id_count>0){
                    $dup_count++;
                    array_push($duplicate_val,intval($s_OrderNumber));
                }
            }
            fclose($csv_file);
            if($dup_count>0){
                echo 'duplicate<<>>';
                echo json_encode($duplicate_val);
            }else{
                $query_batch_id =$this->db->query("SELECT IFNULL(MAX(batchid),0)+1 AS s_batch_id FROM db_daraz_orders");
                $batch_id=$query_batch_id->row()->s_batch_id;

                $file = fopen('uploads/csv/daraz_orders/'.$file_name,"r");
                //Save flag
                $flag='true';
                $this->db->trans_begin();
                $i=1;
                while(($importdata = fgetcsv($file, NULL, ",")) !== FALSE){
                    if($i++==1){ continue; }
                    
                    $importdata=$this->xss_html_filter($importdata);

                    $OrderItemId=trim($importdata[0]);
                    $OrderType=($importdata[1]);
                    $OrderFlag=trim($importdata[2]);
                    $DarazId=trim($importdata[3]);
                    $SellerSKU=trim($importdata[4]);
                    $DarazSKU=trim($importdata[5]);
                    $Cre_dat = $importdata[6];
                    $cr_date = strtotime($Cre_dat);
                    $Createdat = date('Y-m-d H:i:s', $cr_date);
                    $up_dat = $importdata[7];
                    $up_date = strtotime($up_dat);
                    $Updatedat = date('Y-m-d H:i:s',$up_date);
                    $OrderNumber = trim($importdata[8]);
                    $InvoiceRequired = trim($importdata[9]);
                    $CustomerName = trim($importdata[10]);
                    $CustomerEmail1 = !empty($importdata[11])?$importdata[11]:'';
                    $CustomerEmail2 = !empty($importdata[12])?$importdata[12]:'';
                    $ShippingName = trim($importdata[13]);
                    $ShippingAddress = trim($importdata[14]);
                    $ShippingAddress2 = !empty($importdata[15])?$importdata[15]:'';
                    $ShippingAddress3 = !empty($importdata[16])?$importdata[16]:'';
                    $ShippingAddress4 = !empty($importdata[17])?$importdata[17]:'';
                    $ShippingAddress5 = !empty($importdata[18])?$importdata[18]:'';
                    $ShippingPhoneNumber = !empty($importdata[19])?$importdata[19]:'';
                    $ShippingPhoneNumber2 = !empty($importdata[20])?$importdata[20]:'';
                    $ShippingCity = !empty($importdata[21])?$importdata[21]:'';
                    $ShippingPostcode = !empty($importdata[22])?$importdata[22]:'';
                    $ShippingCountry = !empty($importdata[23])?$importdata[23]:'';
                    $ShippingRegion = !empty($importdata[24])?$importdata[24]:'';
                    $BillingName = !empty($importdata[25])?$importdata[25]:'';
                    $BillingAddress = !empty($importdata[26])?$importdata[26]:'';
                    $BillingAddress2 = !empty($importdata[27])?$importdata[27]:'';
                    $BillingAddress3 = !empty($importdata[28])?$importdata[28]:'';
                    $BillingAddress4 = !empty($importdata[29])?$importdata[29]:'';
                    $BillingAddress5 = !empty($importdata[30])?$importdata[30]:'';
                    $BillingPhoneNumber = !empty($importdata[31])?$importdata[31]:'';
                    $BillingPhoneNumber2 = !empty($importdata[32])?$importdata[32]:'';
                    $BillingCity = !empty($importdata[33])?$importdata[33]:'';
                    $BillingPostcode = !empty($importdata[34])?$importdata[34]:'';
                    $BillingCountry = !empty($importdata[35])?$importdata[35]:'';
                    $TaxCode = !empty($importdata[36])?$importdata[36]:'';
                    $BranchNumber = !empty($importdata[37])?$importdata[37]:'';
                    $TaxInvoicerequested = !empty($importdata[38])?$importdata[38]:'';
                    $PaymentMethod = !empty($importdata[39])?$importdata[39]:'';
                    $PaidPrice = !empty($importdata[40])?$importdata[40]:'';
                    $UnitPrice = !empty($importdata[41])?$importdata[41]:'';
                    $ShippingFee = !empty($importdata[42])?$importdata[42]:'';
                    $WalletCredits = !empty($importdata[43])?$importdata[43]:'';
                    $ItemName = !empty($importdata[44])?$importdata[44]:'';
                    $Variation = !empty($importdata[45])?$importdata[45]:'';
                    $CDShippingProvider = !empty($importdata[46])?$importdata[46]:'';
                    $ShippingProvider = !empty($importdata[47])?$importdata[47]:'';
                    $ShipmentTypeName = !empty($importdata[48])?$importdata[48]:'';
                    $ShippingProviderType = !empty($importdata[49])?$importdata[49]:'';
                    $CDTrackingCode = !empty($importdata[50])?$importdata[50]:'';
                    $TrackingCode = !empty($importdata[51])?$importdata[51]:'';
                    $TrackingURL = !empty($importdata[52])?$importdata[52]:'';
                    $ShippingProviderfirstmile = !empty($importdata[53])?$importdata[53]:'';
                    $TrackingCodefirstmile = !empty($importdata[54])?$importdata[54]:'';
                    $TrackingURLfirstmile = !empty($importdata[55])?$importdata[55]:'';
                    $Promisedshippingtime = !empty($importdata[56])?$importdata[56]:'';
                    $Premium = !empty($importdata[57])?$importdata[57]:'';
                    $jobStatus = !empty($importdata[58])?$importdata[58]:'';
                    $CanceReturnInitiator = !empty($importdata[59])?$importdata[59]:'';
                    $Reason = !empty($importdata[60])?$importdata[60]:'';
                    $ReasonDetail = !empty($importdata[61])?$importdata[61]:'';
                    $Editor = !empty($importdata[62])?$importdata[62]:'';
                    $BundleID = !empty($importdata[63])?$importdata[63]:'';
                    $BundleDiscount = !empty($importdata[64])?$importdata[64]:'';
                    $RefundAmount = !empty($importdata[65])?$importdata[65]:'';
                    
                    $row = array(
                        'OrderItemId' => $OrderItemId,
                        'OrderType' => $OrderType,
                        'OrderFlag' => $OrderFlag,
                        'DarazId' => $DarazId,
                        'SellerSKU' => $SellerSKU,
                        'DarazSKU' => $DarazSKU,
                        'Createdat' => $Createdat,
                        'Updatedat' => $Updatedat,
                        'OrderNumber' => $OrderNumber,
                        'InvoiceRequired' => $InvoiceRequired,
                        'CustomerName' => $CustomerName,
                        'CustomerEmail1' => $CustomerEmail1,
                        'CustomerEmail2' => $CustomerEmail2,
                        'ShippingName' => $ShippingName,
                        'ShippingAddress' => $ShippingAddress,
                        'ShippingAddress2' => $ShippingAddress2,
                        'ShippingAddress3' => $ShippingAddress3,
                        'ShippingAddress4' => $ShippingAddress4,
                        'ShippingAddress5' => $ShippingAddress5,
                        'ShippingPhoneNumber' => $ShippingPhoneNumber,
                        'ShippingPhoneNumber2' => $ShippingPhoneNumber2,
                        'ShippingCity' => $ShippingCity,
                        'ShippingPostcode' => $ShippingPostcode,
                        'ShippingCountry' => $ShippingCountry,
                        'ShippingRegion' => $ShippingRegion,
                        'BillingName' => $BillingName,
                        'BillingAddress' => $BillingAddress,
                        'BillingAddress2' => $BillingAddress2,
                        'BillingAddress3' => $BillingAddress3,
                        'BillingAddress4' => $BillingAddress4,
                        'BillingAddress5' => $BillingAddress5,
                        'BillingPhoneNumber' => $BillingPhoneNumber,
                        'BillingPhoneNumber2' => $BillingPhoneNumber2,
                        'BillingCity' => $BillingCity,
                        'BillingPostcode' => $BillingPostcode,
                        'BillingCountry' => $BillingCountry,
                        'TaxCode' => $TaxCode,
                        'BranchNumber' => $BranchNumber,
                        'TaxInvoicerequested' => $TaxInvoicerequested,
                        'PaymentMethod' => $PaymentMethod,
                        'PaidPrice' => $PaidPrice,
                        'UnitPrice' => $UnitPrice,
                        'ShippingFee' => $ShippingFee,
                        'WalletCredits' => $WalletCredits,
                        'ItemName' => $ItemName,
                        'Variation' => $Variation,
                        'CDShippingProvider' => $CDShippingProvider,
                        'ShippingProvider' => $ShippingProvider,
                        'ShipmentTypeName' => $ShipmentTypeName,
                        'ShippingProviderType' => $ShippingProviderType,
                        'CDTrackingCode' => $CDTrackingCode,
                        'TrackingCode' => $TrackingCode,
                        'TrackingURL' => $TrackingURL,
                        'ShippingProviderfirstmile' => $ShippingProviderfirstmile,
                        'TrackingCodefirstmile' => $TrackingCodefirstmile,
                        'TrackingURLfirstmile' => $TrackingURLfirstmile,
                        'Promisedshippingtime' => $Promisedshippingtime,
                        'Premium' => $Premium,
                        'jobStatus' => $jobStatus,
                        'CanceReturnInitiator' => $CanceReturnInitiator,
                        'Reason' => $Reason,
                        'ReasonDetail' => $ReasonDetail,
                        'Editor' => $Editor,
                        'BundleID' => $BundleID,
                        'BundleDiscount' => $BundleDiscount,
                        'RefundAmount' => $RefundAmount,
                        'batchid' => $batch_id,
                        'batchdate' => date('Y-m-d')
                    );
                    
                    //If any record failed to save flag will be set false,then all records rolled back
                    if(!$this->db->insert('db_daraz_orders',$row)){
                        $flag='false';
                    }
                    
                    //Compulsary records
                    if(empty($importdata[0])){
                    $flag='false';   
                    }  
                }
                
                if(!$flag){
                    $this->db->trans_rollback();
                    echo 'failed';
                }else{
                    $this->db->trans_commit();
                    echo "success";
                    $this->session->set_flashdata('success', 'Success!! Order Data Imported Successfully!');
                }
                fclose($file);
            }
        }
    
     //unlink('uploads/csv/customers/'.$file_name);
    }

    public function daraz_pending_ajax_list()
	{
	    $query=$this->db->query("SELECT db_daraz_orders.id,IFNULL(db_items.item_name,'ITEM NOT FOUND') AS ItemName,OrderNumber,OrderItemId,SellerSKU,Createdat,Updatedat AS issueItems FROM db_daraz_orders LEFT JOIN db_items ON db_items.sku=db_daraz_orders.SellerSKU WHERE issueStatus='Added'");
		$res['pending_order_info'] = $query->result();

        $query2=$this->db->query("SELECT COUNT(db_daraz_orders.id) AS pending_count FROM db_daraz_orders LEFT JOIN db_items ON db_items.sku=db_daraz_orders.SellerSKU WHERE issueStatus='Added'");
		$res['pending_order_count'] = $query2->result();

		echo json_encode($res);
	}

	public function daraz_issued_ajax_list()
	{
		$formDate = $this->input->post('formDate');
		$toDate = $this->input->post('toDate');
	    $query=$this->db->query("SELECT db_daraz_orders.id,IFNULL(db_items.item_name,'ITEM NOT FOUND') AS ItemName,OrderNumber,OrderItemId,SellerSKU,Createdat,Updatedat AS issueItems FROM db_daraz_orders LEFT JOIN db_items ON db_items.sku=db_daraz_orders.SellerSKU WHERE issueStatus='Issued' AND (DATE(Createdat) BETWEEN '$formDate' AND '$toDate')");
		$res['issue_order_info'] = $query->result();

        $query=$this->db->query("SELECT COUNT(db_daraz_orders.id) AS issued_count FROM db_daraz_orders LEFT JOIN db_items ON db_items.sku=db_daraz_orders.SellerSKU WHERE issueStatus='Issued' AND (DATE(Createdat) BETWEEN '$formDate' AND '$toDate')");
		$res['issue_order_count'] = $query->result();

		echo json_encode($res);
	}

    public function update_issuedItems()
	{
        $query1=$this->db->query("SELECT db_daraz_orders.id,IFNULL(db_items.item_name,'ITEM NOT FOUND') AS ItemName,OrderItemId,SellerSKU,Createdat,Updatedat AS issueItems FROM db_daraz_orders LEFT JOIN db_items ON db_items.sku=db_daraz_orders.SellerSKU WHERE issueStatus='Added'");

        $count = 0;
        foreach ($query1->result() as $daraz_row) {
            $SellerSKU = $daraz_row->SellerSKU;

            $q_have_stock=$this->db->query("SELECT COUNT(id) st_count FROM db_stock WHERE stock_qty>0 AND sku='$SellerSKU'");
			$st_count=(int)$q_have_stock->row()->st_count;
            if($st_count>0){
                $q_stock=$this->db->query("SELECT id, sku, stock_qty FROM db_stock WHERE stock_qty>0 AND sku='$SellerSKU'");
                $stock_qty=(int)$q_stock->row()->stock_qty;
                $stock_id=$q_stock->row()->id;
                $n_stock_qty = (int)($stock_qty-1);

                $st_data = array(
                    'stock_qty' => $n_stock_qty
                );
                $this->db->where('id', $stock_id);
                $this->db->update('db_stock', $st_data);

                 $daraz_orders_id = $daraz_row->id;

                $daraz_data = array(
                    'issueStatus' => 'Issued'
                );
                $this->db->where('id', $daraz_orders_id);
                $this->db->update('db_daraz_orders', $daraz_data);
                $count++;

                // $q_d_order_all=$this->db->query("SELECT * FROM db_daraz_orders WHERE id='$daraz_orders_id'");
                // $dr_cus_Name=$q_d_order_all->row()->ShippingName;
                // $dr_cus_Address=$q_d_order_all->row()->ShippingAddress;
                // $dr_cus_phone = $q_d_order_all->row()->ShippingPhoneNumber;
                // $dr_cus_city = $q_d_order_all->row()->ShippingCity;

                // $query=$this->db->query("select * from db_customers where upper(customer_name)=upper('$dr_cus_Name')");
                // if($query->num_rows()>0){
                //     $dr_cus_ID=$query->row()->id;//return "Sorry! This Customers Name already Exist.";
                //    // print_r($dr_cus_ID);
                // }else{
                //     $qs5_1="select customer_init from db_company";
                //     $q5_1=$this->db->query($qs5_1);
                //     $customer_init=$q5_1->row()->customer_init;
                //     $qs4="select coalesce(max(id),0)+1 as maxid from db_customers";
                //     $q1=$this->db->query($qs4);
                //     $maxid_1=$q1->row()->maxid;
                //     $customer_code=$customer_init.str_pad($maxid_1, 4, '0', STR_PAD_LEFT);
                //     $cus_array = array(
                //         'customer_code' =>$customer_code,
                //         'customer_name' =>$dr_cus_Name,
                //         'mobile'    =>$dr_cus_phone,
                //         'phone' =>$dr_cus_phone,
                //         'email' =>'',
                //         'city'  =>$dr_cus_city,
                //         'address'   =>$dr_cus_Address,
                //         'system_ip' =>$SYSTEM_IP,
                //         'system_name'   =>$SYSTEM_NAME,
                //         'created_date'  =>$CUR_DATE,
                //         'created_time'  =>$CUR_TIME,
                //         'created_by'    =>$CUR_USERNAME
                //     );
                //     $q3_1 = $this->db->insert('db_customers', $cus_array);
                //     $dr_cus_ID = $this->db->insert_id();
                //    // print_r($dr_cus_ID);
                // }

                //     $q5_2=$this->db->query("select sales_init from db_company where id=1");
                //     $init=$q5_2->row()->sales_init;

                //     $maxid_2=$this->db->query("SELECT COALESCE(MAX(id),0)+1 AS maxid FROM db_sales")->row()->maxid;
                //     $sales_code=$init.str_pad($maxid_2, 4, '0', STR_PAD_LEFT);
                //    // print_r($sales_code);

                //     $cr_date = strtotime($q_d_order_all->row()->Createdat);
                //     $sales_date = date('Y-m-d', $cr_date);
                //     $sales_time = date('H:i:s', $cr_date);
                //     //print_r($sales_date);   
                    
                //     $query_agent=$this->db->query("select * from db_agent where upper(agent)=upper('Daraz')");
                //     $agent=$query_agent->row()->id;

                //     $query_platform=$this->db->query("select * from db_platform where upper(platform)=upper('Daraz')");
                //     $platform=$query_platform->row()->id;

                //     $final_tot = number_format($q_d_order_all->row()->PaidPrice+$q_d_order_all->row()->ShippingFee);
                    

                //     $sales_entry = array(
                //         'sales_code' 				=> $sales_code, 
                //         'sales_date' 				=> $sales_date,
                //         'sales_status' 				=> 'Pending',
                //         'customer_id' 				=> $dr_cus_ID,
                //         /*'warehouse_id' 				=> $warehouse_id,*/
                //         /*Discount*/
                //         'discount_to_all_input' 	=> '0.00',
                //         'discount_to_all_type' 		=> 'in_percentage',
                //         'tot_discount_to_all_amt' 	=> '0.00',
                //         /*Other Charges*/
                //         'other_charges_input' 		=> $q_d_order_all->row()->ShippingFee,
                //         'other_charges_amt' 		=> $q_d_order_all->row()->ShippingFee,
                //         /*Subtotal & Total */
                //         'subtotal' 					=> $q_d_order_all->row()->PaidPrice,
                //         'round_off' 				=> $q_d_order_all->row()->ShippingFee,
                //         'grand_total' 				=> $final_tot,
                //         'payment_status'			=> 'Unpaid',
                //         'paid_amount'				=> 0,
                //         /*System Info*/
                //         'created_date' 				=> date("Y-m-d"),
                //         'created_time' 				=> $sales_time,
                //         'created_by' 				=> 'admin',
                //         'system_ip' 				=> $SYSTEM_IP,
                //         'system_name' 				=> $SYSTEM_NAME,
                //         'pos' 						=> 1,
                //         'status' 					=> 1,
                //         'waybill'					=>'0',
                //         'platform'					=>$platform,
                //         'agent'						=>$agent
                //     );
                //     //print_r($sales_entry);

                //     $q3 = $this->db->insert('db_sales', $sales_entry);
                //     $sales_id = $this->db->insert_id();
                //     //print_r($sales_id);

                //     $q_stock=$this->db->query("SELECT * FROM db_stock WHERE sku='$SellerSKU'");

                //     $item_record = array(
                //         'sales_id'  =>  $sales_id,
                //         'sales_status'  =>  'Pending',
                //         'stock_id'  =>  $q_stock->row()->id,
                //         'sku'   => $q_stock->row()->sku,
                //         'color' =>  $q_stock->row()->color_id,
                //         'size'  =>  $q_stock->row()->size_id,
                //         'description'   =>  '-',
                //         'sales_qty' =>  1,
                //         'price_per_unit'    =>  $q_d_order_all->row()->PaidPrice,
                //         'item_a_price'  =>  $q_d_order_all->row()->PaidPrice,
                //         'tax_type'  =>  'Inclusive',
                //         'tax_id'    =>  '1',
                //         'tax_amt'   =>  '0.00',
                //         'discount_type' =>  'Percentage',
                //         'discount_input'    =>  '0.00',
                //         'discount_amt'  =>  '0.00',
                //         'unit_total_cost'   =>  $q_d_order_all->row()->PaidPrice,
                //         'total_cost'    =>  $q_d_order_all->row()->PaidPrice,
                //         'item_cost' =>  $q_d_order_all->row()->PaidPrice
                //     );

                //     $q3 = $this->db->insert('db_salesitems', $item_record);

                //     $ins_note ="Income for ".$sales_code." sales";
                //     $sales_ins = array(
                //         'sale_id' 				=> $sales_id, 
                //         'income' 				=> $q_stock->row()->ins,
                //         'expence' 				=> '0.00',
                //         'ins_note'				=> $ins_note
                //     );
                //     $query4 = $this->db->insert('db_ins', $sales_ins);
                
                
            }
            // echo json_encode($dr_cus_Name);
            // echo json_encode($dr_cus_Address);
        }
        if ($count>0){
            $output="ok";
        }else{
            $output="error";
        }
        echo json_encode($output);

	}

    public function transactions(){
        $this->permission_check('trans_daraz');
        $data=$this->data;
        $data['page_title']='Daraz Transaction';
        $this->load->view('import/daraz_trans', $data);
    }

    public function daraz_trans_csv() {
        extract($this->xss_html_filter(array_merge($this->data)));
        $filename = $_FILES["import_file"]["name"];
        
        if($_FILES['import_file']['size'] > 0)
        {   
            
            $config['upload_path']          = './uploads/csv/daraz_trans';
            $config['allowed_types']        = 'csv';
            $this->load->library('upload', $config);

            if ( ! $this->upload->do_upload('import_file')){
                    $error = array('error' => $this->upload->display_errors());
                    print($error['error']);
                    exit();
            }
            else{
                    $file_name=$this->upload->data('file_name');
            }
            
            // $csv_file = fopen('uploads/csv/daraz_trans/'.$file_name,"r");
            // $duplicate_val = array();
            // $dup_count = 0; 
            // // $this->db->trans_begin();
            // $j=1;
            // while(($importdata1 = fgetcsv($csv_file, NULL, ",")) !== FALSE){
            //     if($j++==1){ continue; }
                
            //     $importdata1=$this->xss_html_filter($importdata1);

            //     $s_OrderNumber = trim($importdata1[8]);
            //     $qs_dup="SELECT COUNT(id) AS o_id_count FROM db_daraz_orders WHERE OrderNumber='$s_OrderNumber';";
            //     $q_dup=$this->db->query($qs_dup);
            //     $o_id_count=$q_dup->row()->o_id_count;
            //     if($o_id_count>0){
            //         $dup_count++;
            //         array_push($duplicate_val,intval($s_OrderNumber));
            //     }
            // }
            // fclose($csv_file);
            // if($dup_count>0){
            //     echo 'duplicate<<>>';
            //     echo json_encode($duplicate_val);
            // }else{
                $query_batch_id =$this->db->query("SELECT IFNULL(MAX(batchID),0)+1 AS s_batch_id FROM db_daraz_payments");
                $batch_id=$query_batch_id->row()->s_batch_id;
                
                $file = fopen('uploads/csv/daraz_trans/'.$file_name,"r");
                //Save flag
                $flag='true';
                $this->db->trans_begin();
                $i=1;
                while(($importdata = fgetcsv($file, NULL, ",")) !== FALSE){
                    if($i++==1){ continue; }
                    
                    $importdata=$this->xss_html_filter($importdata);

                    $t_Date = $importdata[0];
                    $trans_Date = strtotime($t_Date);
                    $Transaction_Date = date('Y-m-d',$trans_Date);
                    $Transaction_Type=trim($importdata[1]);
                    $Fee_Name=trim($importdata[2]);
                    $Transaction_Number=trim($importdata[3]);
                    $Details=trim($importdata[4]);
                    $Seller_SKU=trim($importdata[5]);
                    $Lazada_SKU = trim($importdata[6]);
                    $Amount = trim($importdata[7]);
                    $VAT_in_Amount = trim($importdata[8]);
                    $WHT_Amount = trim($importdata[9]);
                    $WHT_included_in_Amount = trim($importdata[10]);
                    $Statement = trim($importdata[11]);
                    $Paid_Status = trim($importdata[12]);
                    $Order_No = trim($importdata[13]);
                    $Order_Item_No = trim($importdata[14]);
                    $Order_Item_Status = trim($importdata[15]);
                    $Shipping_Provider = trim($importdata[16]);
                    $Shipping_Speed = trim($importdata[17]);
                    $Shipment_Type = trim($importdata[18]);
                    $Reference = trim($importdata[19]);
                    $Comment = trim($importdata[20]);
                    $PaymentRefId = trim($importdata[21]);
                    
                    $row = array(
                        'Transaction_Date' => $Transaction_Date,
                        'Transaction_Type' => $Transaction_Type,
                        'Fee_Name' => $Fee_Name,
                        'Transaction_Number' => $Transaction_Number,
                        'Details' => $Details,
                        'Seller_SKU' => $Seller_SKU,
                        'Lazada_SKU' => $Lazada_SKU,
                        'Amount' => $Amount,
                        'VAT_in_Amount' => $VAT_in_Amount,
                        'WHT_Amount' => $WHT_Amount,
                        'WHT_included_in_Amount' => $WHT_included_in_Amount,
                        'Statement' => $Statement,
                        'Paid_Status' => $Paid_Status,
                        'Order_No' => $Order_No,
                        'Order_Item_No' => $Order_Item_No,
                        'Order_Item_Status' => $Order_Item_Status,
                        'Shipping_Provider' => $Shipping_Provider,
                        'Shipping_Speed' => $Shipping_Speed,
                        'Shipment_Type' => $Shipment_Type,
                        'Reference' => $Reference,
                        'Comment' => $Comment,
                        'PaymentRefId' => $PaymentRefId,
                        'batchID' => $batch_id,
                        'current_order_status' => '-'
                    );
                    
                    //If any record failed to save flag will be set false,then all records rolled back
                    if(!$this->db->insert('db_daraz_payments',$row)){
                        $flag='false';
                    }
                    
                    //Compulsary records
                    if(empty($importdata[0])){
                    $flag='false';   
                    }  
                }
                
                if(!$flag){
                    $this->db->trans_rollback();
                    echo 'failed';
                }else{
                    $this->db->trans_commit();
                    echo "success";
                    $this->session->set_flashdata('success', 'Success!! Payments Data Imported Successfully!');
                }
                fclose($file);
            }
        //}
    
     //unlink('uploads/csv/customers/'.$file_name);
    }

    public function daraz_pay_ajax_list()
	{
	    $query=$this->db->query("SELECT db_daraz_payments.id ,db_daraz_payments.Transaction_Date ,db_daraz_payments.Amount ,db_daraz_payments.VAT_in_Amount ,db_daraz_payments.Order_No ,db_daraz_payments.Order_Item_No ,db_daraz_payments.Reference ,db_daraz_payments.batchID ,db_daraz_payments.Seller_SKU ,db_items.item_name FROM db_items INNER JOIN db_daraz_payments ON (db_items.sku =db_daraz_payments.Seller_SKU) WHERE db_daraz_payments.status='Added' ORDER BY batchID DESC");
		$res['order_pay_info'] = $query->result();

        // $query2=$this->db->query("SELECT COUNT(db_daraz_orders.id) AS pending_count FROM db_daraz_orders LEFT JOIN db_items ON db_items.sku=db_daraz_orders.SellerSKU WHERE issueStatus='Added'");
		// $res['pending_order_count'] = $query2->result();

		echo json_encode($res);
	}

    public function update_pay_data()
	{
        $query1=$this->db->query("SELECT COUNT(id) AS countID,id,Transaction_Date, SUM(Amount) AS sumAmount, SUM(VAT_in_Amount) AS sumVat, (SUM(Amount)-SUM(VAT_in_Amount)) AS balance, Order_No,Order_Item_No,Reference,batchID,Order_Item_Status,(SELECT cost_price FROM db_stock WHERE sku=Seller_SKU) AS itemCost FROM db_daraz_payments WHERE db_daraz_payments.status='Added' GROUP BY Order_No,Reference ORDER BY batchID ASC");

        $count = 0;
        // $count1 = 0;
        // $count2 = 0;
        foreach ($query1->result() as $daraz_row) {
            $UniqueID = $daraz_row->id;
            $OrderItemNo = $daraz_row->Order_Item_No;
            $OrderNo = $daraz_row->Order_No;
            //$Paid = doubleval($daraz_row->balance);
            $Paid = round(doubleval($daraz_row->sumAmount),3);  
            $sumAmount = round(doubleval($daraz_row->sumAmount),3);            
            $PaidDate = $daraz_row->Transaction_Date;
            $OrderStatus = $daraz_row->Order_Item_Status;
            $itemCost = round(doubleval($daraz_row->itemCost),3);

            // echo $UniqueID.'<br>';
            // echo $OrderItemNo.'<br>';
            // echo $OrderNo.'<br>';
            // echo $Paid.'<br>';
            // echo ' sumAmount : '.$sumAmount.'<br>';
            // echo $PaidDate.'<br>';
            // echo $OrderStatus.'<br>';
            

            if ($OrderStatus=="Returned")
            {

               // echo 'cost : '.$itemCost.'<br>';
                // echo $OrderNo.','.$OrderItemNo.'<br>';
                // $count1++;
                // $query2=$this->db->query("SELECT * FROM db_daraz_orders WHERE OrderNumber='$OrderNo';");

                // foreach ($query2->result() as $daraz_order_row) {
                //     $issueStatus = $daraz_order_row->issueStatus;

                //     if(($sumAmount>0)&&($issueStatus=="Issued")){
                //         $paid_amt = '0';
                //         $return_status = '1';
                //     }

                // }


                if($sumAmount>0){
                    $paid_amt = $Paid;
                    $return_status = '0';
                   // echo 'x1';
                } else if($sumAmount==0){
                    $paid_amt = '0';
                    $return_status = '1';
                   // echo 'x2';
                } else{
                    $paid_amt = '0';
                    $return_status = '1';
                   // echo 'x3';
                }

                $or_data = array(
                    'Paid' => $paid_amt,
                    'Paid_Date' => $PaidDate,
                    'return_status' => $return_status,
                );
                $this->db->where('OrderNumber', $OrderNo);
                $this->db->where('OrderItemId', $OrderItemNo);
                $returnData1 = $this->db->update('db_daraz_orders', $or_data);

                if($returnData1)
                {
                    $pay_data = array(
                        'current_order_status' => 'Updated'
                    );
                    $this->db->where('Order_No', $OrderNo);
                    $this->db->where('Order_Item_No', $OrderItemNo);
                    $this->db->update('db_daraz_payments', $pay_data);

                    $pay_data_2 = array(
                        'status' => 'Updated'
                    );
                    $this->db->where('Order_No', $OrderNo);
                    $this->db->where('Order_Item_No', $OrderItemNo);
                    $this->db->update('db_daraz_payments', $pay_data_2);
                    $count++;
                
                    $issu_data = array(
                        'issueStatus' => 'Returned'
                    );
                    $this->db->where('Order_No', $OrderNo);
                    $this->db->where('Order_Item_No', $OrderItemNo);
                    $this->db->update('db_daraz_orders', $issu_data);
                }

            }
            else if($OrderStatus == "Delivered")
            {
                //$count2++;
                //echo $OrderNo.'<br>';

                $or_data = array(
                    'Paid' => $Paid,
                    'Paid_Date' => $PaidDate
                );
                $this->db->where('OrderNumber', $OrderNo);
                $this->db->where('OrderItemId', $OrderItemNo);
                $returnData2 =$this->db->update('db_daraz_orders', $or_data);

                if($returnData2)
                {
                    $pay_data = array(
                        'status' => 'Updated'
                    );
                    $this->db->where('Order_No', $OrderNo);
                    $this->db->where('Order_Item_No', $OrderItemNo);
                    $this->db->update('db_daraz_payments', $pay_data);
                }

                $trans_or_data = array(
                    'current_order_status' => 'Delivered'
                );
                $this->db->where('OrderNumber', $OrderNo);
                $this->db->where('OrderItemId', $OrderItemNo);
                $returnData3 =$this->db->update('db_daraz_orders', $trans_or_data);

                if($returnData3){
                    $count++;
                }
            }
        }
        // echo $count1.'<br>';
        // echo $count2;
        if ($count>0){
            $output="ok";
        }else{
            $output="error";
        }
        echo json_encode($output);

	}

    public function return_update()
	{
        $data=$this->input->post('data_table');
        $count = 0;

        foreach($data as $order_res){
			$order_no = $order_res['order_no'];
			$sale_sku = $order_res['sale_sku'];

            $query1=$this->db->query("SELECT return_status FROM db_daraz_orders WHERE OrderNumber='$order_no' AND SellerSKU='$sale_sku'");
            $row_Count = $query1->num_rows();

            if($row_Count>0){

                $return_data = array(
                    'Return_received' => '1',
                    'return_status' => '0',
                    'issueStatus' => 'ReturnReceived'
                );
                $this->db->where('OrderNumber', $order_no);
                $this->db->where('SellerSKU', $sale_sku);
                $this->db->update('db_daraz_orders', $return_data);

                $query2=$this->db->query("UPDATE db_stock SET stock_qty=stock_qty+1 WHERE sku='$sale_sku'");

                $count++;
            }
        }
        if ($count>0){
            $output="success";
        }else{
            $output="failed";
        }
        echo json_encode($output);

	}

}

