<?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 alldistricts(Request $request){
        
        $pro = new Payment();
       $dataa = $pro->alldistricts();
        
        $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 allcities(Request $request){
       
        // $dis = $_GET['dis'];
        $pro = new Payment();
       $dataa = $pro->allcities();
        
        $data = response()->json($dataa);
            return $data;
    } 
    
    function get_routes(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 `route_id` as id,`route_name` as route
       // FROM `mes_route` WHERE `ref_id` = '$refid'");
       
       $data = app('db')->select("SELECT `route_id` as id,`route_name` as route
       FROM `mes_route`");

        for($i=0; $i<count($data); $i++){
            
            $rt[] = array('id'=>$data[$i]->id,'route'=>$data[$i]->route);
        }
        
        if(count($data)<1){
            $rt[] = array();
        }
        
            $dataa = response()->json($rt);
            return $dataa;
    } 
    
    
    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' order by `cust_auth` DESC");


        $cust = [];    
        for($i=0; $i<count($data); $i++){
            
            $dt = new User;
            $out = $dt->outstand($data[$i]->cust_id);
            if($data[$i]->cust_status<1){$auth="red";}else{
                if($data[$i]->cust_auth<1){
                    $auth = "yellow";
                }else{
                   $auth = "green";
                }
            }
            $cust[] = array('uniq_id'=>$data[$i]->cust_uniqid,'ref_id'=>$refid,'cust_id'=>$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,'status_color'=>$auth,'call'=>$data[$i]->cust_contact);
        }
        
         $data1 = app('db')->select("SELECT `mes_customer`.*,`provinces`.`name_en` as provin,`districts`.`name_en` as dist,`cities`.`name_en` as city
                FROM `mes_qto` LEFT JOIN `mes_customer` ON `mes_customer`.`cust_id` = `mes_qto`.`po_sup_id` 
                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_qto`.`po_ref_id` = '$refid' AND `mes_customer`.`cust_salseperson`!='$refid' 
                GROUP by `mes_qto`.`po_sup_id` order by `cust_auth` DESC");
        
        
                for($i=0; $i<count($data1); $i++){
                    
                    $dt = new User;
                    $out = $dt->outstand($data1[$i]->cust_id);
                            if($data1[$i]->cust_status<1){$auth="red";}else{
                                if($data1[$i]->cust_auth<1){
                                    $auth = "yellow"; 
                                }else{
                                   $auth = "green";
                                }
                            }
                    
                        if(in_array($data1[$i]->cust_uniqid, $cust)){
                            
                        }else{
                           $cust[] = array('uniq_id'=>$data1[$i]->cust_uniqid,'ref_id'=>$refid,'cust_id'=>$data1[$i]->cust_idtext.$data1[$i]->cust_id,'shop'=>$data1[$i]->cust_company,'adrs'=>$data1[$i]->cust_addres,'prov'=>$data1[$i]->provin
                                ,'dist'=>$data1[$i]->dist,'city'=>$data1[$i]->city,'status'=>$data1[$i]->cust_status,'outstand'=>$out,'status_color'=>$auth,'call'=>$data[$i]->cust_contact);
                        }
                    
                }
        
        if(count($data)<1){
            $cust = array();
            
        }
        
            $dataa = response()->json($cust);
            return $dataa;
    }
    
    function inv_outstand(Request $request){
        $id = $request->input('cust_id');
        
        $data2 = app('db')->select("SELECT `mes_qto`.*
                                    FROM `mes_qto` WHERE `po_sup_id` = '$id' order by `po_id` DESC");
                                    
           $inv = [];                           
            for($i=0; $i<count($data2); $i++){
                
                $poid = $data2[$i]->po_id;
                $datap = app('db')->select("SELECT SUM(`pay_amount`) as totp
                                    FROM `mes_payment` WHERE `pay_invid` = '$poid' and `pay_stetus` = '1'");
                $datar = app('db')->select("SELECT SUM(`ret_amount`) as ret
                                    FROM `inv_return` WHERE `ret_invnum` = '$poid' and `ret_stetus` = '1'"); 
                                    
                $outinv = $data2[$i]->po_final_tot - ($datar[0]->ret + $datap[0]->totp);   
                if($outinv>0){
                  $inv[]  = array('invoice'=>$data2[$i]->qto_code.$data2[$i]->po_id,'invdate'=>$data2[$i]->po_cdate,'out'=>$outinv);
                }
                
                                    
                
            }
        $dataa = response()->json($inv);
            return $dataa;    
        
    }
    
    function cust_sav(Request $request){
        
        $this->validate($request, [
            'shop_name' => 'required',
            'shop_adrs' => 'required',
           // 'prov' => 'required',
           // 'district' => 'required',
           // 'city' => 'required',
            'route' => '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');
        $route = $request->input('route');
        $contact_person = $request->input('conperson');
       // if($disc!=""){$discount=$request->input('discount');}else{$discount='0.00';}
        if($disc!=""){$discount='25';}else{$discount='0.00';}
        $credt_p = $request->input('credit_period');
        if($credt_p!=""){$cred_p=$request->input('credit_period');}else{$cred_p='93';}
        $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 if($route<1){
            $ret[0] = "Please Select the Route";
        }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`,`cust_route`,`cust_auth`) 
                        VALUES ('$shop_name','$shop_adrs1','$district','$prov','$city','$contact','$contact_person','$discount',
                        '$cred_p','$refid','$user','$today','$rand','$route','0')");
                        
                        $gt_id =   app('db')->select("SELECT `cust_id` from `mes_customer` ORDER BY `cust_id` DESC LIMIT 1");
                            $insert_id = $gt_id[0]->cust_id;
                            
                        
                        if($resultinsert){
                            $ret[0] = "New Customer Detail Saved";
                            $add_rt = app('db')->insert("INSERT INTO `customer_route`(`cus_id`, `route_id`) VALUES ('$insert_id','$route')");
                        }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'");
        
        //route
        
         $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://neha.webip.lk/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;   
    }
}


