<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Invoice;
use App\Payment;
use App\User;
use Carbon\Carbon;

class CustomerController extends Controller
{
 
    public function __construct()
    {
        $this->middleware('auth');
    }
 
    function province(){
        $pro = new Payment();
       $dataa = $pro->province();
        
        $data = response()->json($dataa);
            return $data;
    }
    
    function districts(Request $request){
        
    $this->validate($request, [
            'pro' => 'required'
        ]);
        
         $prov = $_GET['pro'];
        $pro = new Payment();
       $dataa = $pro->districts($prov);
        
        $data = response()->json($dataa);
            return $data;
    }
    
    function cities(Request $request){
        
        $this->validate($request, [
            'dis' => 'required'
        ]);
        
         $dis = $_GET['dis'];
        $pro = new Payment();
       $dataa = $pro->cities($dis);
        
        $data = response()->json($dataa);
            return $data;
    }    
    
    function all_customer(Request $request){
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $refid = $user_data[0]->user_id;
        $data = app('db')->select("SELECT `mes_customer`.*,`provinces`.`name_en` as provin,`districts`.`name_en` as dist,`cities`.`name_en` as city
        FROM `mes_customer` LEFT JOIN `provinces` ON `provinces`.`id` = `mes_customer`.`cust_prov` 
        LEFT JOIN `districts` ON `districts`.`id` = `mes_customer`.`cust_distc`
        LEFT JOIN `cities` ON `cities`.`id` = `mes_customer`.`cust_city` WHERE `cust_salseperson` = '$refid'");



        for($i=0; $i<count($data); $i++){
            
            $dt = new User;
            $out = $dt->outstand($data[$i]->cust_id);
            $cust[] = array('uniq_id'=>$data[$i]->cust_uniqid,'ref_id'=>$refid,'cust_id'=>$data[$i]->cust_idtext.$data[$i]->cust_id,'shop'=>$data[$i]->cust_company,'adrs'=>$data[$i]->cust_addres,'prov'=>$data[$i]->provin
            ,'dist'=>$data[$i]->dist,'city'=>$data[$i]->city,'status'=>$data[$i]->cust_status,'outstand'=>$out);
        }
        
        if(count($data)<1){
            $cust[] = array();
        }
        
            $dataa = response()->json($cust);
            return $dataa;
    }
    
    function cust_sav(Request $request){
        
        $this->validate($request, [
            'shop_name' => 'required',
            'shop_adrs' => 'required',
            'prov' => 'required',
            'district' => 'required',
            'city' => 'required',
            
        ]);
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        
        $refid = $user_data[0]->user_id;
        $user = $user_data[0]->user_name;
        $shop_name = $request->input('shop_name');
        $shop_adrs1 = $request->input('shop_adrs');
        $shop_adrs = preg_replace('/\s+/', '', $shop_adrs1);
        $prov = $request->input('prov');
        $district = $request->input('district');
        $city = $request->input('city');
        $disc = $request->input('discount');
        $contact = $request->input('contact');
        $contact_person = $request->input('conperson');
        if($disc!=""){$discount=$request->input('discount');}else{$discount='0.00';}
        $credt_p = $request->input('credit_period');
        if($credt_p!=""){$cred_p=$request->input('credit_period');}else{$cred_p='0.00';}
        $today = date('Y-m-d');
        
        
        $detail = app('db')->select("SELECT * FROM `mes_customer` where `cust_company` = '$shop_name' and `cust_addres` = '$shop_adrs'");
        if(count($detail)>0){
            $ret[0] = "Duplicate Customer";
        }else{
                $pro = new Payment();
                $data_dis = $pro->districts($prov);
                    $ds = new Payment();
                    $data_pro = $ds->cities($district);
                
                    if((count($data_dis)<0) || (count($data_pro)<0) ){
                            $ret[0] = "Select Correct District or City";
                    }else{
                        $unc = new Invoice();
                        $rand = $unc->unique_code(20);;
                        $resultinsert = app('db')->insert("INSERT INTO `mes_customer`(`cust_company`, 
                        `cust_addres`, `cust_distc`, `cust_prov`, `cust_city`,`cust_contact`,`cust_conperson`,
                        `cust_discount`, `cust_creditper`, `cust_salseperson`, `cust_cuser`, `cust_cdate`,`cust_uniqid`) 
                        VALUES ('$shop_name','$shop_adrs1','$district','$prov','$city','$contact','$contact_person','$discount','$cred_p','$refid','$user','$today','$rand')");
                        
                        if($resultinsert){
                            $ret[0] = "New Customer Detail Saved";
                        }else{
                            $ret[0] = "Please Re enter all details";
                        }
                    }
        }
        
        $dataa = response()->json($ret[0]);
            return $dataa;
    }
    
    function get_sin_cust(Request $request){
        
        $this->validate($request, [
            'cust_uniqid' => 'required'
            
        ]);
        $id = $request->input('cust_uniqid');
        
        $detail = app('db')->select("SELECT `mes_customer`.*, `mes_user`.`user_fname` as 'ref_fname',`mes_user`.`user_lname` as 'ref_lname' FROM `mes_customer` LEFT JOIN `mes_user` ON `mes_user`.`user_id` = `mes_customer`.`cust_salseperson`
        LEFT JOIN `provinces` ON `provinces`.`id` = `mes_customer`.`cust_prov`
        LEFT JOIN `districts` ON `districts`.`id` = `mes_customer`.`cust_distc`
        LEFT JOIN `cities` ON `cities`.`id` = `mes_customer`.`cust_city`
        where `mes_customer`.`cust_uniqid` = '$id'");
        
         $dataa = response()->json($detail);
            return $dataa;
        
        //$updt = app('db')->update("UPDATE `inv_return` SET `ret_totqty`='$tot' WHERE `ret_id`='$insert_id'");
        
    }
    
    function update_customer(Request $request){
        $this->validate($request, [
            'shop_name' => 'required',
            'shop_adrs' => 'required',
            'prov' => 'required',
            'district' => 'required',
            'city' => 'required',
            
        ]);
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        
        $id = $request->input('cust_uniqid');
        $refid = $user_data[0]->user_id;
        $user = $user_data[0]->user_name;
         $shop_name1 = $request->input('shop_name');
        $shop_adrs1 = $request->input('shop_adrs');
        $prov = $request->input('prov');
        $district = $request->input('district');
        $city = $request->input('city');
        $disc = $request->input('discount');
        $contact = $request->input('contact');
        $contact_person = $request->input('conperson');
        if($disc!=""){$discount=$request->input('discount');}else{$discount='0.00';}
        $credt_p = $request->input('credit_period');
        if($credt_p!=""){$cred_p=$request->input('credit_period');}else{$cred_p='0.00';}
        $today = date('Y-m-d');
        
        
        $shop_name = preg_replace('/\s+/', '', strtoupper($shop_name1)); 
        $shop_adrs = preg_replace('/\s+/', '', strtoupper($shop_adrs1));
        
        $detail = app('db')->select("SELECT * FROM `mes_customer` WHERE REPLACE(`cust_company`, ' ', '') = '$shop_name' and REPLACE(`cust_addres`, ' ', '') = '$shop_adrs' AND `cust_uniqid` != '$id'");
       //$detail2 = app('db')->select("SELECT * FROM `mes_customer1` WHERE REPLACE(`cust_addres`, ' ', '') = '$shop_adrs' AND `cust_uniqid` != '$id'");
        
        if ((count($detail)>0) ){
    	            $ret[0] = "Customer Cannot Be duplicate ";
    	            
                }else{ 
                    $pro = new Payment();
                $data_dis = $pro->districts($prov);
                    $ds = new Payment();
                    $data_pro = $ds->cities($district);
                
                    if((count($data_dis)<0) || (count($data_pro)<0) ){
                            $ret[0] = "Select Correct District or City";
                    }else{
                        $updt = app('db')->update("UPDATE `mes_customer` SET `cust_company`='$shop_name1',`cust_addres`='$shop_adrs1',`cust_prov`='$prov'
                        ,`cust_distc`='$district',`cust_city`='$city',`cust_creditper`='$cred_p',`cust_discount`='$discount',`cust_euser`='$user'
                        ,`cust_edate`='$today',`cust_contact`='$contact',`cust_conperson`='$contact_person' WHERE `cust_uniqid`='$id'");
                   
                        if($updt){
                           $ret[0] = "Updated"; 
                        }else{
                            $ret[0] = "Re enter all details";
                        }
                    }
                    
                }
                
                 $dataa = response()->json($ret[0]);
            return $dataa;
    }
    
     function sales_summary(Request $request){
        
        $this->validate($request, [
            'date' => 'required'
        ]);
        $dte = $_GET['date'];
        
        if(($dte!="")){
            $headers = $request->header('Authorization');
            $dt = new User;
            $user_data = $dt->getBearerToken($headers);
            $uid = $user_data[0]->user_id;
            
            $url = "https://demo.webip.lk/nance/salsesumry_print/".$uid."/".$dte;
                if(empty($url)){
                    $url = $url;
                }
            
        }else{
            $url = "";
        }
        
        $data = response()->json($url);
            return $data;
        
    }
    
    function cust_summary(Request $request){
        
        $this->validate($request, [
            'period' => 'required',
            'cust_id' => 'required'
        ]);
        
        $period = $request->input('period');
        $cust = $request->input('cust_id');
        $exp = explode("CUST",$cust);
        $cust_id = $exp[1];
        
              $old_date = Carbon::now()->subDays($period);
                   $nw =  $old_date->toDateString();
                   
            $data = app('db')->select("SELECT * from `mes_qto` where `po_sup_id`='$cust_id' and `po_cdate` <= '$nw' and `po_payment`='0'");
            $total = 0.00;
            if(count($data)>0){
                for($i=0; $i<count($data); $i++){
                            $inv_bl = new Payment();
                                $bal = $inv_bl->inv_balance($data[$i]->po_id);
                            if($bal>0){
                                $total = $total+$bal;
                            }
                        }
            }
            
            $numf = sprintf("%.2f",$total);
        
        $data = response()->json($numf);
            return $data;
        
    }
    
    function summary_period(){
        $user_data = array("0"=>"All","90"=>"90 days","60"=>"60 days","45"=>"45 days","90"=>"90 days");
       $dataa = response()->json($user_data);
       
       
            return $dataa;   
    }
}


