<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Brian2694\Toastr\Facades\Toastr;
use App\Helpers\CurrentUser;
use App\Models\ExpenseCategory;
use App\Models\Expense;
use App\Models\ExpenseReceipt;
use App\Models\ExpenseReceiptService;
use Auth;

class ExpenseReceiptController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:expense-receipt-list|expense-receipt-create|expense-receipt-edit|expense-receipt-delete', ['only' => ['index','show']]);
        $this->middleware('permission:expense-receipt-create', ['only' => ['create','store']]);
        $this->middleware('permission:expense-receipt-edit', ['only' => ['edit','update']]);
        $this->middleware('permission:expense-receipt-delete', ['only' => ['destroy']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $expenseReceiptData = ExpenseReceipt::orderBy('id', 'desc')->where('status', true)->paginate(10);
        $allExpenseReceiptCount = ExpenseReceipt::orderBy('id', 'desc')->where('status', true)->count();

        return view('admin.expenses.expenseReceipt.index',compact('expenseReceiptData','allExpenseReceiptCount'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //To fet userId..
        $userId = CurrentUser::getUserId();
        //To check ExpenseReceipt status...
        $previousExpenseReceiptData = ExpenseReceipt::getPendingExpenseReceiptData($userId);
        if(!empty($previousExpenseReceiptData)){
            ExpenseReceipt::whereIn('id', $previousExpenseReceiptData)->delete();
        }

        //To add ExpenseReceipt data...
        $singleExpenseReceiptData = $this->addExpenseReceiptData($userId);

        //To get expene category & expense data...
        $expenseCategoryData = ExpenseCategory::orderBy('id','desc')->where('status',true)->get();
        $expenseData = Expense::orderBy('id','desc')->where('status',true)->get();
        $unpaidExpenseServiceData[] = null;
        $totalExpenseServiceQty = 0;
        $totalExpenseServiceAmount = 0;

        return view('admin.expenses.expenseReceipt.create',compact('expenseCategoryData','expenseData','unpaidExpenseServiceData'
                ,'totalExpenseServiceQty','totalExpenseServiceAmount','singleExpenseReceiptData'));
    }

    //To add new ExpenseReceipt data....
    public function addExpenseReceiptData($userId)
    {
            $data = new ExpenseReceipt();
            $data->user_id = $userId;
            $data->receipt_by = Auth::user()->name;
            
            if($data->save()){
                return $data;
            }else{
                $data = null;
            }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'expense_receipt_id'=> 'required',
            'expense_category_id'=> 'required',
            'expense_id'=> 'required',
            'expense_amount'=> 'required',
            'expense_details'=> 'required',
        ]);

        //To fet userId..
        $userId = CurrentUser::getUserId();
        $data = $request->all();
        $data['user_id'] = $userId;

        if(ExpenseReceiptService::create($data)){
            $unpaidExpenseServiceData = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $request->expense_receipt_id)->get();
            $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $request->expense_receipt_id)->count();
            $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $request->expense_receipt_id)->sum('expense_amount');
            $expenseCategoryData = ExpenseCategory::orderBy('id','desc')->where('status',true)->get();
            $expenseData = Expense::orderBy('id','desc')->where('status',true)->get();  

            return view('admin.expenses.expenseReceipt.updateExpenseDetails',compact('unpaidExpenseServiceData','totalExpenseServiceQty'
                    ,'totalExpenseServiceAmount','expenseCategoryData','expenseData'));
        }else{
            return response()->json([
                'error' => 'Sorry, Something is wrong.!'
            ]);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $singleExpenseReceiptData = ExpenseReceipt::where('id', $id)->first();
        $expenseReceiptId = $singleExpenseReceiptData->id;
        if($singleExpenseReceiptData != null){
            $unpaidExpenseServiceData = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $expenseReceiptId)->get();
            $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $expenseReceiptId)->count();
            $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $expenseReceiptId)->sum('expense_amount');
         
            $expenseCategoryData = ExpenseCategory::orderBy('id','desc')->where('status',true)->get();
            $expenseData = Expense::orderBy('id','desc')->where('status',true)->get();  

            return view('admin.expenses.expenseReceipt.edit',compact('unpaidExpenseServiceData','totalExpenseServiceQty'
                    ,'totalExpenseServiceAmount','expenseCategoryData','expenseData','singleExpenseReceiptData'));
        }else{
            return response()->json([
                'error' => 'Sorry, Something is wrong.!'
            ]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $request->validate([
            'expense_service_id'=> 'required',
            'expense_receipt_id'=> 'required',
            'expense_category_id'=> 'required',
            'expense_id'=> 'required',
            'expense_amount'=> 'required',
            'expense_details'=> 'required',
        ]);

        //To fet userId..
        $userId = CurrentUser::getUserId();
        $singleExpenseReceiptService = ExpenseReceiptService::where('id', $request->expense_service_id)->first();
        $data = $request->all();
        $data['user_id'] = $userId;

        if($singleExpenseReceiptService->update($data)){
            $unpaidExpenseServiceData = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $request->expense_receipt_id)->get();
            $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $request->expense_receipt_id)->count();
            $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $request->expense_receipt_id)->sum('expense_amount');
            $expenseCategoryData = ExpenseCategory::orderBy('id','desc')->where('status',true)->get();
            $expenseData = Expense::orderBy('id','desc')->where('status',true)->get();  

            return view('admin.expenses.expenseReceipt.updateExpenseDetails',compact('unpaidExpenseServiceData','totalExpenseServiceQty'
                    ,'totalExpenseServiceAmount','expenseCategoryData','expenseData'));
        }else{
            return response()->json([
                'error' => 'Sorry, Something is wrong.!'
            ]);
        }

        $data = $request->all();
        $singleExpense = Expense::where('id', $id)->first();

        if($singleExpense->update($data)){
            Toastr::success('Expense updated successfully.', 'Success', ["progressbar" => true]);
            return redirect()->back();
        }else{
            Toastr::error('Sorry, Something is wrong.!', 'Error', ["progressbar" => true]);
            return redirect()->back();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $singleExpenseData = Expense::where('id', $id)->first();
        if($singleExpenseData->delete()){
            Toastr::success('Expense deleted successfully.', 'Success', ["progressbar" => true]);
            return redirect()->back();
        }else{
            Toastr::error('Soething is wrong!.', 'Error', ["progressbar" => true]);
            return redirect()->back();
        }
    }

    //To remove expene service data...
    public function removeExpenseService(Request $request)
    {
        $singleExpenseReceiptServiceData = ExpenseReceiptService::where('id', $request->expense_service_id)->first();
        $expenseReceiptId = $singleExpenseReceiptServiceData->expense_receipt_id;
        if($singleExpenseReceiptServiceData->delete()){
            $unpaidExpenseServiceData = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $expenseReceiptId)->get();
            $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $expenseReceiptId)->count();
            $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $expenseReceiptId)->sum('expense_amount');
         
            $expenseCategoryData = ExpenseCategory::orderBy('id','desc')->where('status',true)->get();
            $expenseData = Expense::orderBy('id','desc')->where('status',true)->get();  

            return view('admin.expenses.expenseReceipt.updateExpenseDetails',compact('unpaidExpenseServiceData','totalExpenseServiceQty'
                    ,'totalExpenseServiceAmount','expenseCategoryData','expenseData'));
        }else{
            return response()->json([
                'error' => 'Sorry, Something is wrong.!'
            ]);
        }
    }

    //To save all the expense receipt data...
    public function saveAllExpenseReceipt(Request $request)
    {
        $singleExpenseReceiptData = ExpenseReceipt::where('id', $request->expense_receipt_id)->first();
        $singleExpenseReceiptData->receipt_notes = $request->receipt_notes;
        $singleExpenseReceiptData->status = 1;

        //To get billing service product data...
        $expenseReceiptId = $singleExpenseReceiptData->id;
        $expenseRSD = ExpenseReceiptService::orderBy('id','desc')
                                ->where('expense_receipt_id', $expenseReceiptId)->get();;
        if(isset($expenseRSD) && $expenseRSD != null){
            //To update expense receiptid...
            $nextExpenseReceiptId = ExpenseReceipt::max('expense_receipt_id') + 1;
            if($nextExpenseReceiptId != 1){
                if($singleExpenseReceiptData->expense_receipt_id == null){
                    $singleExpenseReceiptData->expense_receipt_id = $nextExpenseReceiptId;
                }
            }else{
                $singleExpenseReceiptData->expense_receipt_id = 10001;
            }

            if($singleExpenseReceiptData->save()){
                $unpaidExpenseServiceData = ExpenseReceiptService::orderBy('id','desc')
                                ->where('expense_receipt_id', $expenseReceiptId)->get();
                $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                            ->where('expense_receipt_id', $expenseReceiptId)->count();
                $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                            ->where('expense_receipt_id', $expenseReceiptId)->sum('expense_amount');

                return view('admin.expenses.expenseReceipt.getExpenseDetailsPage',compact('unpaidExpenseServiceData','totalExpenseServiceQty'
                        ,'totalExpenseServiceAmount','singleExpenseReceiptData'));
            }else{
                Toastr::error('Soething is wrong!.', 'Error', ["progressbar" => true]);
                return redirect()->back();
            }
        }else{
            Toastr::error('Sorry, You did not create any expense receipt.!.', 'Error', ["progressbar" => true]);
            return redirect()->back();
        }
    }
    
    //To get all the expense receipt data...
    public function getAllExpenseReceipt($id)
    {
        $singleExpenseReceiptData = ExpenseReceipt::where('id', $id)->first();

        //To get billing service product data...
        $expenseReceiptId = $singleExpenseReceiptData->id;
        $expenseRSD = ExpenseReceiptService::orderBy('id','desc')
                                ->where('expense_receipt_id', $expenseReceiptId)->get();;
        if(isset($expenseRSD) && $expenseRSD != null){
            $unpaidExpenseServiceData = ExpenseReceiptService::orderBy('id','desc')
                            ->where('expense_receipt_id', $expenseReceiptId)->get();
            $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $expenseReceiptId)->count();
            $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                        ->where('expense_receipt_id', $expenseReceiptId)->sum('expense_amount');

            return view('admin.expenses.expenseReceipt.getExpenseDetailsPage',compact('unpaidExpenseServiceData','totalExpenseServiceQty'
                    ,'totalExpenseServiceAmount','singleExpenseReceiptData'));
        }else{
            Toastr::error('Sorry, You did not create any expense receipt.!.', 'Error', ["progressbar" => true]);
            return redirect()->back();
        }
    }

    //To get all the expense data with category wise...
    public function getExpenseWithCategory(Request $request)
    {
        $request->validate([
            'expense_category_id'=> 'required',
        ]);

        $expenseCategoryId = $request->expense_category_id;
        $data = Expense::where('expense_category_id', $request->expense_category_id)->get();
        
        return response()->json($data);
    }
}
