<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use App\Models\Course;
use App\Models\Code;
use App\Models\Category;
use App\Models\Lab;
use App\Http\Requests\StorePaymentRequest;
use App\Http\Requests\UpdatePaymentRequest;
use Illuminate\Support\Facades\Storage;
use Image;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; 

class PaymentController extends Controller
{
   
    function __construct()
    { 

    $this->middleware('permission:show payment', ['only' => ['index']]);
    $this->middleware('permission:add payment', ['only' => ['create','store']]);
    $this->middleware('permission:update payment', ['only' => ['edit','update']]);
    $this->middleware('permission:delete payment', ['only' => ['destroy']]);

    }

    public function index()
    {
        $payments =  Payment::all();
        return view('pages.Payments.index',compact('payments'));
    }

   
    public function create()
    {
        $codes =  Code::all();
        $labs = Lab::where('year_id','2')->pluck('desc','id');
        // $labs = Lab::where('year_id','2')->get()->pluck('desc','id');
       // dd($labs);
        return view('pages.Payments.create',compact('codes','labs'));
    }

    public function getcodes($id)
    {

      $codes = Code::where('lab_id',$id)
      ->whereNotNull('lab_id')
      ->pluck('name','id');

      return json_encode ($codes);
      
    } 


    public function store(StorePaymentRequest $request)
    {
       // dd($request->all());
        // $payment= Auth::user()->user_id;

        $code = Code::where('id',$request->code)->first();
        $lab_id = $code->lab_id;
        $course_id = $code->course_id;

        $lab = Lab::where('id',$lab_id)->first();
        $execute = $lab->execute;
        $balance = $lab->balance;
        $qty = $lab->qty;
        
        if($request->amount > $balance )
        {
           return redirect()->back()->withErrors('The Amount is greater than Balance is available');
        }
        elseif($request->qty > $qty )
        {
           return redirect()->back()->withErrors('The Quantity is greater than what is available');
        }

        else{
            try {
                DB::beginTransaction();
                $validated = $request->validated();

                $payment = new Payment; 
                $payment->course_id =  $course_id;
                $payment->code_id = $request->code;
                $payment->lab_id = $lab_id;
                $payment->qty = $request->qty;
                $payment->amount = $request->amount;
                $payment->note = $request->note;
                $payment->user_id = Auth::user()->id;
            
                if ($request->hasFile('file')) {
                    $image = $request->file('file');
                    $filename = time() . '.' . $image->getClientOriginalExtension();
                    $location = public_path('images/files/' . $filename);
                    Image::make($image)->resize(500, 500)->save($location);
                    $payment->file = $filename;
                }  
            
                $payment->save();

                

                $newExecute = $execute + $request->amount ;
                $newBalance = $balance  - $request->amount ;
                $newqty = $qty  - $request->qty ;

                $lab->update([
                    'execute' => $newExecute ,
                    'balance' => $newBalance ,
                    'qty' => $newqty ,
                        ]);
                    DB::commit();
                    toastr()->success(trans('messages.success'));
                    return redirect()->route('payments.index');
                }

                

                catch (\Exception $e){
                DB::rollback();
                return redirect()->back()->withErrors(['error' => $e->getMessage()]);
                }
            }
        }
    
    public function show(Payment $payment)
    {
        //
    }

    public function edit(Payment $payment)
    {
        //
    }

    public function update(UpdatePaymentRequest $request, Payment $payment)
    {
        //
    }
 
    public function destroy(Payment $payment)
    {
        //
    }
}
