<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Invoice;
use App\User;
use App\Product;
use App\Numbertowordconvertsconver;
use Session;
use App\Payment;

class AdminController extends Controller
{
    
    public function login(Request $request)
    {
          //validate incoming request 
        $this->validate($request, [
            'name' => 'required|string',
            'password' => 'required',
        ]);
        
       $ipad =  $request->ip();

        $credentials = $request->only(['name', 'password']);

        if (! $token = Auth::attempt($credentials)) {
            return response()->json(['message' => $ipad], 401);
        }

        $nm = $request->input('name');

        $results = app('db')->select("SELECT `mes_user`.*,`mes_depot`.`dep_name` from `mes_user` join `mes_depot` on `mes_depot`.`dep_id` = `mes_user`.`user_depoid` 
        where `user_name` ='$nm' and `user_lvl` <'2'");
        
        $gen_results = app('db')->select("SELECT * FROM `general`");
            $token_id = $this->respondWithToken($token);
            
            if(count($results)>0){
                    if($results[0]->user_status!=0){
                        return response()->json(['message' => 'Success','token'=>$token_id->original['token'],'user'=>$results]);
                    }else{
                        return response()->json(['message' => 'Inactive User'], 401);
                    }
            }else{
                return response()->json(['message' => 'Incorrect Data'], 401);
            }
           
            
            $_SESSION["uname"] = $results[0]->user_name;
    }
    
    function gen_data(){
        $inv =  app('db')->select("SELECT `po_id` FROM `mes_qto` where `po_auth`='0'");
       if(count($inv)>0){$invauth = count($inv);}else{$invauth=0;}
       
       $cust =  app('db')->select("SELECT `cust_id` FROM `mes_customer` where `cust_auth`='0'");
       if(count($cust)>0){$custauth = count($cust);}else{$custauth=0;}
       $list['inv'] = $invauth;
       $list['cust'] = $custauth;

        $data = response()->json($list);
            return $data;
    }

    function inv_list(){
      
       $list =  app('db')->select("SELECT * FROM `mes_qto` ORDER BY `po_id` DESC LIMIT 20");

        $data = response()->json($list);
            return $data;
    }
    
    
    function all_inv_list(){
      
       $list =  app('db')->select("SELECT `mes_qto`.`po_id`, `mes_qto`.`po_final_tot`,`mes_qto`.`po_status`, `mes_customer`.`cust_company`,
       `mes_user`.`user_name`,
       `mes_qto`.`po_discount`,`mes_qto`.`po_tot_qty`
       FROM `mes_qto` LEFT JOIN `mes_customer` ON `mes_customer`.`cust_id` = `mes_qto`.`po_sup_id` 
       LEFT JOIN `mes_user` ON `mes_user`.`user_id` = `mes_qto`.`po_ref_id` where `po_auth`='0' ORDER BY `mes_qto`.`po_id` DESC LIMIT 20");

        $data = response()->json($list);
            return $data;
    }
    
    function sin_inv(Request $request){
        
        $this->validate($request, [
            'inv' => 'required',
        ]);
        
        $inv =$request->input('inv');
      
                    $dataa =  app('db')->select("SELECT *
                            FROM `qto_items` 
                            LEFT JOIN `mes_item` ON `qto_items`.`po_itm_item_id`   = `mes_item`.`item_id`
                            LEFT JOIN `item` ON `item`.`itm_id`   = `mes_item`.`item_name`
                            LEFT JOIN `mes_currancy` ON `qto_items`.`po_itm_currancy`   = `mes_currancy`.`curr_id`
                            LEFT JOIN `mes_unit` ON `qto_items`.`po_itm_unit`   = `mes_unit`.`unit_id`
                            LEFT JOIN `mes_model` ON `mes_model`.`model_id` = `mes_item`.`item_model`
                            LEFT JOIN `mes_brand` ON `mes_brand`.`brand_id` = `mes_item`.`item_brand`
                            LEFT JOIN `mes_category` ON `mes_category`.`cat_id` = `mes_item`.`item_cat`
                            WHERE `qto_items`.`po_itm_po_id` = '$inv'
                            ORDER BY `qto_items`.`po_itm_po_id` DESC");
                    
                    for($i=0; $i<count($dataa); $i++){
                        $batchid = $dataa[$i]->po_itm_batch;
                        $batch =  app('db')->select("SELECT * FROM `batch` WHERE `batch_id` = '$batchid'");
                        
                            $itm = $dataa[$i]->brand_name." ".$dataa[$i]->itm_name." ".$dataa[$i]->model_name;
                            
                            $data[] = array($batch[0]->batch,$dataa[$i]->item_catcount,$dataa[$i]->itm_name,
                            $dataa[$i]->po_itm_unitprice,$dataa[$i]->po_itm_qty,$dataa[$i]->po_itm_id,$dataa[$i]->free_item,
                            $batch[0]->selling_price,$dataa[$i]->item_freeitm,$dataa[$i]->item_freqty,$dataa[$i]->po_itm_item_id,$inv); 
                    }
                    
                 if(!empty($data)){$data;}else{$data="";}        
        $res = response()->json($data);
            return $res;
    }
    
    function updt_invitem(Request $request){
        
        $this->validate($request, [
            'line_id' => 'required',
             'user' => 'required',
        ]);
        
        $id =$request->input('line_id');
        $nprice =$request->input('nprice');
        $frqty =$request->input('frqty');
        $user =$request->input('user');
        
        
        $item =  app('db')->select("SELECT * FROM `qto_items` JOIN `mes_qto` ON `mes_qto`.`po_id`=`qto_items`.`po_itm_po_id` WHERE `po_itm_id`='$id'");
        
        $done = "Updated. Cannot Increse Free Quantity";  
        if(($frqty!="")&&($frqty < $item[0]->free_item )){
            $depo =$item[0]->depo;
            $ins_id = $item[0]->po_itm_po_id;
            $item_id = $item[0]->po_itm_item_id;
            $b_qty = $item[0]->free_item;
            $n_qty = $item[0]->free_item;
            $b_id = $item[0]->po_itm_batch;
            $user_id = $item[0]->po_user;
            
            $cal = new Invoice();
            $cal_stock = $cal->cal_batch($depo,"auth",$ins_id,$item_id,$b_qty,"min",$b_id,$user_id);
            $cal_stock = $cal->cal_batch($depo,"auth",$ins_id,$item_id,$frqty,"plus",$b_id,$user_id);
            
            $done = "Free Issues Updated"; 
            app('db')->update("UPDATE `qto_items` SET `free_item`='$frqty' WHERE `po_itm_id` = '$id'"); 
        }
        
        
        $dtt= date('Y-m-d');
        echo $nprice;
        if($nprice!=""){
            app('db')->update("UPDATE `qto_items` SET `po_itm_unitprice`='$nprice' WHERE `po_itm_id` = '$id'"); 
        }
       
        $resultinsert = app('db')->insert("INSERT INTO `admin_log`(`user_id`, `id`,`action`, `table_name`) 
                                            VALUES ('$user','$id','Invoice Item','Invoice') ");
        
            return $done;
    }
    
    function updt_inv(Request $request){
        
        $this->validate($request, [
            'id' => 'required',
            'user' => 'required',
        ]);
        
        $id =$request->input('id');
        $discount =$request->input('discount');
        $user =$request->input('user');
        $coment =$request->input('coment');
        
        $userr =  app('db')->select("SELECT `user_id` FROM `mes_user` where `user_name`='$user'");
       
        
        $inv =  app('db')->select("SELECT * FROM `mes_qto` where `po_id`='$id'");
        
        $dtt= date('Y-m-d');
        $user_id = $userr[0]->user_id;
        
        if($discount==""){
            $discount = $inv[0]->po_discount;
        }
        
            $item =  app('db')->select("SELECT * FROM `qto_items` where `po_itm_po_id`='$id'");
            $totqty = $prc = $totprice = $totfree= 0;
            
            for($i=0; $i<count($item); $i++){
                $totqty += $item[$i]->po_itm_qty;
                $prc = $item[$i]->po_itm_qty * $item[$i]->po_itm_unitprice;
                $totprice += $prc;
                $totfree += $item[$i]->free_item;
                
                $itm_id = $item[$i]->po_itm_id;
                app('db')->update("UPDATE `qto_items` SET `po_aprvl`='0' WHERE `po_itm_id` = '$itm_id'"); 
            }
            
            $caldis = (100 - $discount);
            $fin =  ($totprice/100)*$caldis;
            
          
           $final = number_format((float)$fin, 2, '.', '');
       
       $num_val = new Numbertowordconvertsconver; 
        $last_val = $num_val->convert_number($final);
        
        
            $tempNum = explode('.', $final);
            $num1 =  $num_val->convert_number($tempNum[0]);
            $num2 = $num_val->convert_number($tempNum[1]);
            
            if($tempNum[1]!=00){
               $finl= $num1." and ". $num2." cents only";
                
            }else{$finl= $num1." and ". $num2." only";}
        
        
         $updt = app('db')->update("UPDATE `mes_qto` 
         SET `po_discount`='$discount',
         `po_tot_price`='$fin',
         `po_final_tot`='$final',
         `po_fwording`='$finl',
         `actual_final`='$fin',
         `po_tot_qty`='$totqty',
         `po_tot_freqty`='$totfree',
         `po_auth_comment`='$coment',
         `po_auth`='1',
         `po_authdate`= '$dtt',
         `po_authuser`='$user_id' 
         WHERE `po_id` = '$id'"); 
         
        
        if($updt){
            $data = "Done";
              $resultinsert = app('db')->insert("INSERT INTO `admin_log`(`user_id`, `id`,`action`, `table_name`) 
                                            VALUES ('$user','$id','Invoice authorize','Invoice') ");
            
        }else{
            $data = "Error";
        
        }
        
        
            return $data;
    }
    
    function all_replist(){
      
       $list =  app('db')->select("SELECT * FROM `mes_user` JOIN `mes_depot` ON `mes_user`.`user_depoid`=`mes_depot`.`dep_id` WHERE `user_lvl`=20");
       $depo =  app('db')->select("SELECT `dep_name` FROM `mes_depot`");
     
    
        //array_push($list,$depo);

        $data = response()->json($list);
            return $data;
    }
    
    function updt_ref(Request $request){
        
        $this->validate($request, [
            'id' => 'required',
            'status' => 'required',
            'depo' => 'required',
            'user' => 'required',
        ]);
        
        $id =$request->input('id');
        $status =$request->input('status');
        $depot =$request->input('depo');
        $user =$request->input('user');
        
        $detail =  app('db')->select("SELECT * FROM `mes_user` where `user_id`='$id';");
        $depo =  app('db')->select("SELECT * FROM `mes_depot` where `dep_id`='$depot';");
        
        
        
       // if($depo[0]->dep_name!=$depot){
            
        //    $updt = app('db')->update("UPDATE `mes_user` SET `user_depoid`='$depp' WHERE `user_id` = '$id'"); 
       // }
        
        if($depot=="Ampara"){
            $depp = 1;
                }else{ $depp = 0; }
        
        if($status!="true"){
                $active = 0;
            }else{
                $active = 1;
            }
        
            $updt = app('db')->update("UPDATE `mes_user` SET `user_depoid`='$depp',`user_status`='$active' WHERE `user_id` = '$id'"); 
                                       
              $resultinsert = app('db')->insert("INSERT INTO `admin_log`(`user_id`, `id`,`action`, `table_name`) 
                                            VALUES ('$user','$id','Ref update','user') ");
      
        
        $data = 'done';
            return $data;
    }
    
    function actv_ref(){
        $this->validate($request, [
            'user' => 'required',
        ]);
        
          $user =$request->input('user');
        
        $detail =  app('db')->select("SELECT * FROM `mes_user` where `user_lvl`='20';");
        if($detail[0]->all_inactive == 1){
            $updt = app('db')->update("UPDATE `mes_user` SET `all_inactive`='0' WHERE `user_lvl`='20'");
            $ret = "All Salse Persons Active";
        }else{
            $updt = app('db')->update("UPDATE `mes_user` SET `all_inactive`='1' WHERE `user_lvl`='20'"); 
             $ret = "All Salse Persons Inactive";
        }
        
        $resultinsert = app('db')->insert("INSERT INTO `admin_log`(`user_id`, `id`,`action`, `table_name`) 
                                            VALUES ('$user','0','All ref Active','user') ");
        
        return $ret;
    }
    
    function all_customerlist(){
      
       $list =  app('db')->select("SELECT `mes_customer`.`cust_id`,`mes_customer`.`cust_company`,   
       `mes_customer`.`cust_addres`, `mes_customer`.`credit_limit` ,`mes_customer`.`cust_creditper`,`mes_customer`.`cust_status`, 
       `mes_customer`.`cust_auth`, `mes_user`.`user_name`,`customer_route`.`route_id`,`mes_route`.`route_name` 
       FROM `mes_customer` LEFT JOIN `mes_user` ON `mes_user`.`user_id`=`mes_customer`.`cust_salseperson` 
       LEFT JOIN `customer_route` ON `customer_route`.`cus_id`=`mes_customer`.`cust_id` 
       JOIN `mes_route` ON `mes_route`.`route_id`=`customer_route`.`route_id` ORDER BY `cust_auth` ASC LIMIT 100;");

        $data = response()->json($list);
            return $data;
    }
    
    function search_customer_list(Request $request){
        
         $txt =$request->input('txt');
      
      if($txt!=""){
          $list =  app('db')->select("SELECT `mes_customer`.`cust_id`,`mes_customer`.`cust_company`,   
       `mes_customer`.`cust_addres`, `mes_customer`.`credit_limit` ,`mes_customer`.`cust_creditper`,`mes_customer`.`cust_status`, 
       `mes_customer`.`cust_auth`, `mes_user`.`user_name`,`customer_route`.`route_id`,`mes_route`.`route_name` 
       FROM `mes_customer` LEFT JOIN `mes_user` ON `mes_user`.`user_id`=`mes_customer`.`cust_salseperson` 
       LEFT JOIN `customer_route` ON `customer_route`.`cus_id`=`mes_customer`.`cust_id` 
       JOIN `mes_route` ON `mes_route`.`route_id`=`customer_route`.`route_id`  WHERE `mes_customer`.`cust_company` LIKE '%$txt%' ORDER BY `cust_auth` ASC;");
      }else{
          $list =  app('db')->select("SELECT `mes_customer`.`cust_id`,`mes_customer`.`cust_company`,   
       `mes_customer`.`cust_addres`, `mes_customer`.`credit_limit` ,`mes_customer`.`cust_creditper`,`mes_customer`.`cust_status`, 
       `mes_customer`.`cust_auth`, `mes_user`.`user_name`,`customer_route`.`route_id`,`mes_route`.`route_name` 
       FROM `mes_customer` LEFT JOIN `mes_user` ON `mes_user`.`user_id`=`mes_customer`.`cust_salseperson` 
       LEFT JOIN `customer_route` ON `customer_route`.`cus_id`=`mes_customer`.`cust_id` 
       JOIN `mes_route` ON `mes_route`.`route_id`=`customer_route`.`route_id` ORDER BY `cust_auth` ASC LIMIT 100;");
      }
       

        $data = response()->json($list);
            return $data;
    }
    
    function save_customerdt(Request $request){
        
        $this->validate($request, [
            'id' => 'required',
            'status' => 'required',
            'user' => 'required',
        ]);
        
        $id =$request->input('id');
        $status =$request->input('status');
        $credit =$request->input('credit');
        $user =$request->input('user');
        
        $detail =  app('db')->select("SELECT * FROM `mes_customer` where `cust_id`='$id';");
        
        if($detail[0]->cust_auth>0){
            if(empty($credit)){
                $credit = $detail[0]->cust_creditper;
            }else{
                $credit =$request->input('credit');
            }
            
            if($status!="true"){
                $active = 0;
            }else{
                $active = 1;
            }
            
            $updt = app('db')->update("UPDATE `mes_customer` SET `cust_status`='$active',`cust_creditper`='$credit' WHERE `cust_id` = '$id'"); 
        }else{
            $updt = app('db')->update("UPDATE `mes_customer` SET `cust_auth`='1',`cust_status`='1' WHERE `cust_id` = '$id'"); 
                                       
        }
        $date = date('Y-m-d');
        
      $resultinsert = app('db')->insert("INSERT INTO `admin_log`(`user_id`,`id`, `action`, `table_name`) 
                                            VALUES ('$user','$id','Customer Edit','customer') ");
        if($updt){
            $data = 'done';
        }else{
            $data = 'error';
        }
        
        $credit_cal = new Payment();
       $chk = $credit_cal->cal_credit_limit($id);
       
            return $updt;
    }
    
    function sales_summary(Request $request){
        
        $this->validate($request, [
            'date' => 'required',
            'id' => 'required',
        ]);
        
        $date = $request->input('date');
        $id = $request->input('id');
        
        if(($date!="")){
            
            $url = "https://newapp.nance.lk/salsesumry_print/".$id."/".$date;
                if(empty($url)){
                    $url = $url;
                }
            
        }else{
            $url = "";
        }
        
        $data = response()->json($url);
            return $data;
        
    }
    
    
}