<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use App\Models\Transaction;
use App\Models\SellLines;
use App\Models\Payment;
use App\Models\Tax;
use DB;
use Auth;
use PDF;
use Illuminate\Support\Facades\Storage;
class PayementController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $company_listing=User::where('role','client')->get();
        return view('payment',compact('company_listing'));
    }
    function fetchTotalPaymentDue(Request $request){
      
        $result = array('data' => array());
        $report=Transaction::select(DB::raw('SUM(transaction.amount) as total'),'transaction.customer_id')
                            ->leftjoin('users','users.id','=','transaction.customer_id')
                            ->where('transaction.type','=','sale')->groupBy('transaction.customer_id');


        if (!empty($request->company_id)) {
            if (auth()->user()->role == 'admin' || auth()->user()->role == 'users') {
                $report->where('transaction.customer_id','=',$request->company_id);
            }
           
        }
// && auth()->user()->role == 'users
        $data=$report->get();
        // echo $request->company_id;die;

         $i=1;
         foreach ($data as $key => $value) {
          $username=User::where('id','=',$value['customer_id'])->first();
          $total = DB::table('transaction') ->where('transaction.customer_id', '=', $value->customer_id)->sum('transaction.amount');
               
       $paid = DB::table('transaction_payment') ->where('transaction_payment.payment_for', '=', $value->customer_id)->sum('transaction_payment.amount');
      $due=$total-$paid;
          // print_r($username);die;
            $button='';
            
                  $button.=' <td>  <button type="button" class="btn btn-block bg-danger btn-sm" data-toggle="modal" data-target="#payment_modal" data-keyboard="false" data-id="'.$value->customer_id.'" data-backdrop="static" id="pay">Pay</button>
                     </td>
                </td>';


                $result['data'][$key] = array(
                $i,
                $username['company_name'],round($due),
                $button,
            );
       $i++;  }
     echo json_encode($result);
    }

    function total_payment_due($id){
      
       $total = DB::table('transaction') ->where('transaction.customer_id', '=', $id)->sum('transaction.amount');
               
       $paid = DB::table('transaction_payment') ->where('transaction_payment.payment_for', '=', $id)->sum('transaction_payment.amount');
      $response=$total-$paid;
      return json_encode($response); 
    }

      function pay_due_amount($id,Request $request){
        if (!empty($request->Amount)) {

            $all_bill=DB::select("SELECT a.id,a.amount FROM transaction a WHERE a.customer_id=$id AND a.type='sale'");
            // print_r($all_bill);die;
            $amount=$request->Amount;
            $bal=0;

            for ($i=0; $i <sizeof($all_bill) ; $i++) { 
           
            $paid = DB::table('transaction_payment') ->where('transaction_payment.transaction_id', '=', $all_bill[$i]->id)->sum('transaction_payment.amount');
            $due_amount=$all_bill[$i]->amount-$paid;
          
             $bal=$amount -$due_amount;
           if ($due_amount > 0) {
            if ($amount <= $due_amount) { 
                $newamount=$amount;
            }else {
               $newamount=$due_amount;
            }
            $payment=array('amount' => $newamount,
            'payment_date' =>  $request->transaction_date,
            'transaction_id' => $all_bill[$i]->id,
            'payment_for'=>$request->id,
            'payment_type' => $request->payment_type,
            'paid_amount' => $request->Amount,
            'created_by'=>Auth::user()->id);
            $TransactionPayment=Payment::create($payment);
          if ($bal <=0) {
               break;
            }
          
                $amount=$bal;

            }
            
            }
           }
            if($TransactionPayment){
                $response=['success' => 'true'];
            }else{
                $response=['success' => 'false'];
            }
        return json_encode($response);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function viewPaymentSlip()
    {
          $company_listing=User::where('role','client')->get();
        return view('viewPaymentSlip',compact('company_listing'));
    }
    
    function fetchPaymentSlip(Request $request){
        // print_r($request->company_id);die;
      $this->export_pdf($request->company_id,$request->datefrom,$request->dateto);
        $result = array('data' => array());
        $report=Payment::select('transaction_payment.*','transaction_payment.amount as devided_amount','users.company_name','transaction.amount as bill_amount','transaction.ledger','transaction.ledger_value','transaction.transaction_date','transaction.id as tra_id')->leftjoin('transaction','transaction.id','=','transaction_payment.transaction_id')
                        ->leftjoin('users','users.id','=','transaction.customer_id')
                            ->where('transaction.type','=','sale')->whereDate('transaction_payment.payment_date', '>=', '2022-02-16')->where('transaction_payment.amount','>=',0)->orderBy('transaction_payment.payment_date', 'asc');
        if (!empty($request->datefrom)) {
            $datefrom = date('Y-m-d', strtotime($request->datefrom));

            $report->whereDate('transaction_payment.payment_date', '>=', $datefrom);
        }
        if (!empty($request->dateto)) {
            $dateto = date('Y-m-d', strtotime($request->dateto));
            $report->whereDate('transaction_payment.payment_date', '<=', $dateto);
        }

        if (!empty($request->company_id)) {
            if (auth()->user()->role == 'admin' || auth()->user()->role == 'users') {
                $report->whereIn('transaction.customer_id',$request->company_id);
            }
           
        }
// && auth()->user()->role == 'users
        $data=$report->get();
        // echo $request->company_id;die;

         $i=1;
         foreach ($data as $key => $value) {
        $qty=SellLines::where('transaction_id','=',$value['transaction_id'])->sum('quantity');
        $balance = DB::table('transaction_payment')->where('transaction_payment.transaction_id', '=', $value['tra_id'])->sum('transaction_payment.amount');
            $pay_status = round($value['bill_amount'], 2) - round($balance, 2);
            $button='';
            
           


                $result['data'][$key] = array(
                $i,
                'SRK :-'.$value['transaction_id'],
                date('d-m-Y',strtotime($value['transaction_date'])),
                $value['company_name'],
                $value['ledger'].'-'.$value['ledger_value'],
                $qty,
                round($value['bill_amount'],2),
                date('d-m-Y',strtotime($value['payment_date'])),
                $value['paid_amount'],
                round($value['devided_amount'],2),
                round($pay_status,1),
              
            );
       $i++;  }
     echo json_encode($result);
    }
    
     function export_pdf($company_id,$datefrom,$dateto)
    {
         $datefrom = date('Y-m-d', strtotime($datefrom));
          $dateto = date('Y-m-d', strtotime($dateto));
         $report=Payment::select('transaction_payment.*','transaction_payment.amount as devided_amount','users.company_name','transaction.amount as bill_amount','transaction.ledger','transaction.ledger_value','transaction.transaction_date','transaction.id as tra_id')->leftjoin('transaction','transaction.id','=','transaction_payment.transaction_id')
                        ->leftjoin('users','users.id','=','transaction.customer_id')
                            ->where('transaction.type','=','sale')->whereDate('transaction_payment.payment_date', '>=', '2022-02-16')->where('transaction_payment.amount','>=',0)->orderBy('transaction_payment.payment_date', 'asc');
        if (!empty($datefrom)) {
          

            $report->whereDate('transaction_payment.payment_date', '>=', $datefrom);
        }
        if (!empty($dateto)) {
           
            $report->whereDate('transaction_payment.payment_date', '<=', $dateto);
        }

        if (!empty($company_id)) {
            if (auth()->user()->role == 'admin' || auth()->user()->role == 'users') {
                $report->whereIn('transaction.customer_id',$company_id);
            }
           
        }
        $data = $report->get();
        // print_r($data);die;
        $path = base_path('logo.jpeg');
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $data2 = file_get_contents($path);
        $pic = 'data:image/' . $type . ';base64,' . base64_encode($data2);
        $pdf = PDF::loadView('export_slip_pdf', compact('data',  'pic'))->setOptions(['defaultFont' => 'sans-serif'])->setPaper([0, 0, 685.98, 1000], 'landscape');
        // return $pdf->stream();
        Storage::put('public/pdf/slip.pdf', $pdf->output());
  }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function export_public_slip_pdf()
    {
        return Storage::download('public/pdf/slip.pdf');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function duePaymentBills()
    {
         $company_listing = User::where('role', 'client')->get();
        return view('duePaymentBills',compact('company_listing'));
    }
    
    function fetchDueBillrData(Request $request)
    {  
        $this->due_bill_export($request->company_id,$request->datefrom,$request->dateto,$request->ledger_id);
        $user_id = Auth::user()->id;
        $result = array('data' => array());
        $report = Transaction::select('transaction.*', 'users.company_name', 'vehicles.vehicle_no', 'vehicles.driver_name', 'sell_lines.quantity', 'sell_lines.total', 'sell_lines.kilometer')
            ->leftjoin('sell_lines', 'sell_lines.transaction_id', '=', 'transaction.id')
            ->leftjoin('users', 'users.id', '=', 'transaction.customer_id')
            ->leftjoin('vehicles', 'vehicles.id', '=', 'transaction.vehicle_number')
            ->where('transaction.type', '=', 'sale')->latest();
        if (!empty($request->ledger_id)) {
            $report->where('transaction.ledger', '=', $request->ledger_id);
        }

        if (!empty($request->datefrom)) {
            $datefrom = date('Y-m-d', strtotime($request->datefrom));

            $report->whereDate('transaction.transaction_date', '>=', $datefrom);
        }
        if (!empty($request->dateto)) {
            $dateto = date('Y-m-d', strtotime($request->dateto));
            $report->whereDate('transaction.transaction_date', '<=', $dateto);
        }
        if (auth()->user()->role == 'client') {
            $report->where('transaction.customer_id', '=', $user_id);
        }
        if (!empty($request->company_id)) {
            if (auth()->user()->role == 'admin' || auth()->user()->role == 'users') {
                $report->where('transaction.customer_id', '=', $request->company_id);
            }
        }
        // && auth()->user()->role == 'users
        $data = $report->get();
        // echo $request->company_id;die;

        $i = 1;
        foreach ($data as $key => $value) {
            if ($value['ledger'] == 'Cashsale') {
                $Cashsale = $value['ledger_value'];
                $DoNo = '-';
            }
            if ($value['ledger'] == 'DoNo') {
                $DoNo = $value['ledger_value'];
                $Cashsale = '-';
            }
   
            $bill = Transaction::where('id', '=', $value['id'])->first();
            $balance = DB::table('transaction_payment')->where('transaction_payment.transaction_id', '=', $value['id'])->sum('transaction_payment.amount');
            $pay_status = round($bill['amount'], 2) - round($balance, 2);
//   if($pay_status){
    $company_name=  $value['company_name'];
    $transaction_date=date('d-m-Y', strtotime($value['transaction_date']));
    $ledger=$value['ledger'];
    $ledger_value=$value['ledger_value'];
    $vehicle_no=$value['vehicle_no'];
    $driver_name=$value['driver_name'];
    $kilometer=$value['kilometer'];
    $quantity=$value['quantity'];
    $total=round($value['total'], 3);
    $pay_status=round($pay_status);
     $result['data'][$key] = array(
                $i,
                $company_name,
                $transaction_date,
                $ledger,
                $ledger_value,
                $vehicle_no,
                $driver_name,
                $kilometer,
                $quantity,
                $total,
                $pay_status,
             
            );
            $i++; 
        
//   }
           if($pay_status == 0){
               unset($result['data'][$key]);
              
               
           }
          
        }
      rsort($result['data']);
    //   print_r($result);die;
        echo json_encode($result);       
        
       
    }
    
    function due_bill_export($company_id,$datefrom,$dateto,$ledger_id){
        $user_id = Auth::user()->id;
        $result = array('data' => array());
        $report = Transaction::select('transaction.*', 'users.company_name', 'vehicles.vehicle_no', 'vehicles.driver_name', 'sell_lines.quantity', 'sell_lines.total', 'sell_lines.kilometer')
            ->leftjoin('sell_lines', 'sell_lines.transaction_id', '=', 'transaction.id')
            ->leftjoin('users', 'users.id', '=', 'transaction.customer_id')
            ->leftjoin('vehicles', 'vehicles.id', '=', 'transaction.vehicle_number')
            ->where('transaction.type', '=', 'sale')->latest();
        if (!empty($ledger_id)) {
            $report->where('transaction.ledger', '=', $ledger_id);
        }

        if (!empty($datefrom)) {
            $datefrom = date('Y-m-d', strtotime($datefrom));

            $report->whereDate('transaction.transaction_date', '>=', $datefrom);
        }
        if (!empty($dateto)) {
            $dateto = date('Y-m-d', strtotime($dateto));
            $report->whereDate('transaction.transaction_date', '<=', $dateto);
        }
        if (auth()->user()->role == 'client') {
            $report->where('transaction.customer_id', '=', $user_id);
        }
        if (!empty($company_id)) {
            if (auth()->user()->role == 'admin' || auth()->user()->role == 'users') {
                $report->where('transaction.customer_id', '=',$company_id);
            }
        }
        $data = $report->get();
        // print_r($data);die;
        $path = base_path('logo.jpeg');
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $data2 = file_get_contents($path);
        $pic = 'data:image/' . $type . ';base64,' . base64_encode($data2);
        $pdf = PDF::loadView('dueBillpdf', compact('data',  'pic'))->setOptions(['defaultFont' => 'sans-serif'])->setPaper([0, 0, 600.98, 1000], 'landscape');
        // return $pdf->stream();
        Storage::put('public/pdf/due.pdf', $pdf->output());
    }
    
    
    
     public function export_due_pdf()
    {
        return Storage::download('public/pdf/due.pdf');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function fetchBill($id)
    {
        
        $bill=Payment::select('transaction.*','transaction_payment.*','transaction_payment.id as voucher_id')->leftjoin('transaction','transaction.id','transaction_payment.transaction_id')->where('transaction.type','=','sale')->where('transaction_payment.id',$id)->first();
        $amount_in_word=$this->convert_number($bill->amount);
        $customer_name=User::find($bill->payment_for);
        $transaction=Transaction::find($bill->transaction_id);
        return view('payment_bill',compact('amount_in_word','bill','customer_name','transaction'));
    }
    
    function convert_number($num)
{

$ones = array(
0 =>"ZERO",
1 => "ONE",
2 => "TWO",
3 => "THREE",
4 => "FOUR",
5 => "FIVE",
6 => "SIX",
7 => "SEVEN",
8 => "EIGHT",
9 => "NINE",
10 => "TEN",
11 => "ELEVEN",
12 => "TWELVE",
13 => "THIRTEEN",
14 => "FOURTEEN",
15 => "FIFTEEN",
16 => "SIXTEEN",
17 => "SEVENTEEN",
18 => "EIGHTEEN",
19 => "NINETEEN",
"014" => "FOURTEEN"
);
$tens = array( 
0 => "ZERO",
1 => "TEN",
2 => "TWENTY",
3 => "THIRTY", 
4 => "FORTY", 
5 => "FIFTY", 
6 => "SIXTY", 
7 => "SEVENTY", 
8 => "EIGHTY", 
9 => "NINETY" 
); 
$hundreds = array( 
"HUNDRED", 
"THOUSAND", 
"MILLION", 
"BILLION", 
"TRILLION", 
"QUARDRILLION" 
); /*limit t quadrillion */
$num = number_format($num,2,".",","); 
$num_arr = explode(".",$num); 
$wholenum = $num_arr[0]; 
$decnum = $num_arr[1]; 
$whole_arr = array_reverse(explode(",",$wholenum)); 
krsort($whole_arr,1); 
$rettxt = ""; 
foreach($whole_arr as $key => $i){
	
while(substr($i,0,1)=="0")
		$i=substr($i,1,5);
if($i < 20){ 
/* echo "getting:".$i; */
$rettxt .= $ones[$i]; 
}elseif($i < 100){ 
if(substr($i,0,1)!="0")  $rettxt .= $tens[substr($i,0,1)]; 
if(substr($i,1,1)!="0") $rettxt .= " ".$ones[substr($i,1,1)]; 
}else{ 
if(substr($i,0,1)!="0") $rettxt .= $ones[substr($i,0,1)]." ".$hundreds[0]; 
if(substr($i,1,1)!="0")$rettxt .= " ".$tens[substr($i,1,1)]; 
if(substr($i,2,1)!="0")$rettxt .= " ".$ones[substr($i,2,1)]; 
} 
if($key > 0){ 
$rettxt .= " ".$hundreds[$key]." "; 
}
} 
if($decnum > 0){
$rettxt .= " DIRHAMS AND ";
if($decnum < 20){
$rettxt .= $ones[$decnum]." FILLS";
}elseif($decnum < 100){
$rettxt .= $tens[substr($decnum,0,1)];
$rettxt .= " ".$ones[substr($decnum,1,1)]." FILLS";
}
}
return $rettxt;
}
}
