<?php

namespace App\Http\Controllers\API\Report;

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

class ExpenseReportController extends Controller
{
    //To get daily invoice report...
    public function dailyReport()
    {
        //Today date, month & year...
        $selectedDate = Carbon::now()->today()->toDateString();

        //To get all the ExpenseReceipt data...
        $expenseReceiptIds = ExpenseReceipt::whereDate('created_at','=', $selectedDate)->where('status', true)
                        ->select('id')->pluck('id')->toArray();
        $unpaidExpenseReceiptData = ExpenseReceipt::orderBy('id','desc')->whereDate('created_at','=', $selectedDate)->where('status', true)->get();

        //To get expense service data...
        $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->count();
        $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->sum('expense_amount');

        $allData = [];
        $indexNumberForAll = 1;
        foreach($unpaidExpenseReceiptData as $key => $singleItem){
            if(isset($singleItem) && $singleItem != null){
                // To get expense total qty and amount...
                $totalExpenseQty = ExpenseReceiptService::getTotalExpenseReceiptServiceQty($singleItem->id);
                $totalExpenseAmount = ExpenseReceiptService::getTotalExpenseReceiptServiceAmount($singleItem->id);
                $allData[] = array(
                    'serial_no' => $singleItem->expense_receipt_id,
                    'receipt_by' => Str::title($singleItem->receipt_by),
                    'receipt_notes' => $singleItem->receipt_notes,
                    'expense_qty' => $totalExpenseQty,
                    'expense_amount'=>$totalExpenseAmount,
                    'date' => $singleItem->created_at->toDateString(),
                    'time' => $singleItem->created_at->toTimeString()
                );
            }
        }

        // Check user has permission...
        if (auth()->user()->hasPermissionTo('expense-daily-report-access', 'web')) {
            return response()->json([
                'message'   =>  'Expense updated successfully.',
                'expense_data'   =>  $allData,
                'totalExpenseServiceQty'   =>  $totalExpenseServiceQty,
                'totalExpenseServiceAmount'   =>  $totalExpenseServiceAmount,
                'selectedDate'   =>  $selectedDate,
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }
    }
    
    //To get selected year invoice report...
    public function dailyReportWithDate(Request $request)
    {
        $request->validate([
            'selected_from_date'=> 'required',
        ]);

        //Today date, month & year...
        $selectedDate = Carbon::parse($request->selected_from_date)->format('Y-m-d');

        //To get all the ExpenseReceipt data...
        $expenseReceiptIds = ExpenseReceipt::whereDate('created_at','=', $selectedDate)->where('status', true)
                        ->select('id')->pluck('id')->toArray();
        $unpaidExpenseReceiptData = ExpenseReceipt::orderBy('id','desc')->whereDate('created_at','=', $selectedDate)->where('status', true)->get();

        //To get expense service data...
        $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->count();
        $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->sum('expense_amount');

        $allData = [];
        $indexNumberForAll = 1;
        foreach($unpaidExpenseReceiptData as $key => $singleItem){
            if(isset($singleItem) && $singleItem != null){
                // To get expense total qty and amount...
                $totalExpenseQty = ExpenseReceiptService::getTotalExpenseReceiptServiceQty($singleItem->id);
                $totalExpenseAmount = ExpenseReceiptService::getTotalExpenseReceiptServiceAmount($singleItem->id);
                $allData[] = array(
                    'serial_no' => $singleItem->expense_receipt_id,
                    'receipt_by' => Str::title($singleItem->receipt_by),
                    'receipt_notes' => $singleItem->receipt_notes,
                    'expense_qty' => $totalExpenseQty,
                    'expense_amount'=>$totalExpenseAmount,
                    'date' => $singleItem->created_at->toDateString(),
                    'time' => $singleItem->created_at->toTimeString()
                );
            }
        }
        // Check user has permission...
        if (auth()->user()->hasPermissionTo('expense-daily-report-access', 'web')) {
            return response()->json([
                'message'   =>  'Expense updated successfully.',
                'expense_data'   =>  $allData,
                'totalExpenseServiceQty'   =>  $totalExpenseServiceQty,
                'totalExpenseServiceAmount'   =>  $totalExpenseServiceAmount,
                'selectedDate'   =>  $selectedDate,
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }
    }

    //To get monthly expense report...
    public function monthlyExpenseReport()
    {
        //Today date, month & year...
        $todayDate = Carbon::now()->today()->toDateString();

        //To get current & all year...
        $currentYear = Carbon::now()->year;
        $getAllYears = [];
        $endYear = 2100;
        for($startYear = 2000; $startYear <= $endYear; $startYear++){
            $getAllYears[] = $startYear;
        }

        //To get all the months & current month name..
        $currentMonth = date('F', strtotime(Carbon::now()));
        $getAllMonthNames = [];
        for ($m=1; $m<=12; $m++) {
            $getAllMonthNames[] = date('F', mktime(0,0,0,$m, 1, date('Y')));
        }

        //To get all the ExpenseReceipt data...
        $expenseReceiptIds = ExpenseReceipt::whereYear('created_at','=', $currentYear)->whereMonth('created_at','=', date('m', strtotime($currentMonth)))
                        ->where('status', true)->select('id')->pluck('id')->toArray();
        $unpaidExpenseReceiptData = ExpenseReceipt::orderBy('id','desc')->whereYear('created_at','=', $currentYear)->whereMonth('created_at','=', date('m', strtotime($currentMonth)))
                        ->where('status', true)->get();

        //To get expense service data...
        $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->count();
        $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->sum('expense_amount');

        $allData = [];
        $indexNumberForAll = 1;
        foreach($unpaidExpenseReceiptData as $key => $singleItem){
            if(isset($singleItem) && $singleItem != null){
                // To get expense total qty and amount...
                $totalExpenseQty = ExpenseReceiptService::getTotalExpenseReceiptServiceQty($singleItem->id);
                $totalExpenseAmount = ExpenseReceiptService::getTotalExpenseReceiptServiceAmount($singleItem->id);
                $allData[] = array(
                    'serial_no' => $singleItem->expense_receipt_id,
                    'receipt_by' => Str::title($singleItem->receipt_by),
                    'receipt_notes' => $singleItem->receipt_notes,
                    'expense_qty' => $totalExpenseQty,
                    'expense_amount'=>$totalExpenseAmount,
                    'date' => $singleItem->created_at->toDateString(),
                    'time' => $singleItem->created_at->toTimeString()
                );
            }
        }
        // Check user has permission...
        if (auth()->user()->hasPermissionTo('expense-monthly-report-access', 'web')) {
            return response()->json([
                'message'   =>  'Expense updated successfully.',
                'expense_data'   =>  $allData,
                'totalExpenseServiceQty'   =>  $totalExpenseServiceQty,
                'totalExpenseServiceAmount'   =>  $totalExpenseServiceAmount,
                'currentYear'   =>  $currentYear,
                'currentMonth'   =>  $currentMonth,
                'getAllMonthNames'   =>  $getAllMonthNames,
                'getAllYears'   =>  $getAllYears,
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }
    }

    //To get selected month expense report...
    public function selectedMonthExpenseReport(Request $request)
    {
        $request->validate([
            'month'=> 'required',
            'year'=> 'required',
        ]);

        //Today date, month & year...
        $todayDate = Carbon::now()->today()->toDateString();
        $currentMonth = $request->month;
        $currentYear = $request->year;

        //To get all year...
        $getAllYears = [];
        $endYear = 2100;
        for($startYear = 2000; $startYear <= $endYear; $startYear++){
            $getAllYears[] = $startYear;
        }

        //To get all the months & current month name..
        $getAllMonthNames = [];
        for ($m=1; $m<=12; $m++) {
            $getAllMonthNames[] = date('F', mktime(0,0,0,$m, 1, date('Y')));
        }

        //To get all the ExpenseReceipt data...
        $expenseReceiptIds = ExpenseReceipt::whereYear('created_at','=', $currentYear)->whereMonth('created_at','=', date('m', strtotime($currentMonth)))
                        ->where('status', true)->select('id')->pluck('id')->toArray();
        $unpaidExpenseReceiptData = ExpenseReceipt::orderBy('id','desc')->whereYear('created_at','=', $currentYear)->whereMonth('created_at','=', date('m', strtotime($currentMonth)))
                        ->where('status', true)->get();

        //To get expense service data...
        $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->count();
        $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->sum('expense_amount');

        $allData = [];
        $indexNumberForAll = 1;
        foreach($unpaidExpenseReceiptData as $key => $singleItem){
            if(isset($singleItem) && $singleItem != null){
                // To get expense total qty and amount...
                $totalExpenseQty = ExpenseReceiptService::getTotalExpenseReceiptServiceQty($singleItem->id);
                $totalExpenseAmount = ExpenseReceiptService::getTotalExpenseReceiptServiceAmount($singleItem->id);
                $allData[] = array(
                    'serial_no' => $singleItem->expense_receipt_id,
                    'receipt_by' => Str::title($singleItem->receipt_by),
                    'receipt_notes' => $singleItem->receipt_notes,
                    'expense_qty' => $totalExpenseQty,
                    'expense_amount'=>$totalExpenseAmount,
                    'date' => $singleItem->created_at->toDateString(),
                    'time' => $singleItem->created_at->toTimeString()
                );
            }
        }
        // Check user has permission...
        if (auth()->user()->hasPermissionTo('expense-monthly-report-access', 'web')) {
            return response()->json([
                'message'   =>  'Expense updated successfully.',
                'expense_data'   =>  $allData,
                'totalExpenseServiceQty'   =>  $totalExpenseServiceQty,
                'totalExpenseServiceAmount'   =>  $totalExpenseServiceAmount,
                'currentYear'   =>  $currentYear,
                'currentMonth'   =>  $currentMonth,
                'getAllMonthNames'   =>  $getAllMonthNames,
                'getAllYears'   =>  $getAllYears,
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }
    }

    //To get between expense report...
    public function betweenExpenseReport()
    {
        //Today date, month & year...
        $todayDate = Carbon::now()->today()->toDateString();

        //Today & End date...
        $startDate = Carbon::now()->today()->toDateString();
        $endDate = Carbon::now()->today()->toDateString();

        //To get all the ExpenseReceipt data...
        $expenseReceiptIds = ExpenseReceipt::whereDate('created_at','>=',$startDate)->whereDate('created_at','<=',$endDate)
                        ->where('status', true)->select('id')->pluck('id')->toArray();
        $unpaidExpenseReceiptData = ExpenseReceipt::orderBy('id','desc')->whereDate('created_at','>=',$startDate)->whereDate('created_at','<=',$endDate)
                        ->where('status', true)->get();

        //To get expense service data...
        $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->count();
        $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->sum('expense_amount');

        $allData = [];
        $indexNumberForAll = 1;
        foreach($unpaidExpenseReceiptData as $key => $singleItem){
            if(isset($singleItem) && $singleItem != null){
                // To get expense total qty and amount...
                $totalExpenseQty = ExpenseReceiptService::getTotalExpenseReceiptServiceQty($singleItem->id);
                $totalExpenseAmount = ExpenseReceiptService::getTotalExpenseReceiptServiceAmount($singleItem->id);
                $allData[] = array(
                    'serial_no' => $singleItem->expense_receipt_id,
                    'receipt_by' => Str::title($singleItem->receipt_by),
                    'receipt_notes' => $singleItem->receipt_notes,
                    'expense_qty' => $totalExpenseQty,
                    'expense_amount'=>$totalExpenseAmount,
                    'date' => $singleItem->created_at->toDateString(),
                    'time' => $singleItem->created_at->toTimeString()
                );
            }
        }
        // Check user has permission...
        if (auth()->user()->hasPermissionTo('expense-between-report-access', 'web')) {
            return response()->json([
                'message'   =>  'Expense updated successfully.',
                'expense_data'   =>  $allData,
                'totalExpenseServiceQty'   =>  $totalExpenseServiceQty,
                'totalExpenseServiceAmount'   =>  $totalExpenseServiceAmount,
                'startDate'   =>  $startDate,
                'endDate'   =>  $endDate,
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }
    }

    //To get selected between expense report...
    public function selectedBetweenExpenseReport(Request $request)
    {
        $request->validate([
            'start_date'=> 'required',
            'end_date'=> 'required',
        ]);

        //Today date, month & year...
        $todayDate = Carbon::now()->today()->toDateString();

        //Today & End date...
        $startDate = Carbon::parse($request->start_date)->format('Y-m-d');
        $endDate = Carbon::parse($request->end_date)->format('Y-m-d');

        //To get all the ExpenseReceipt data...
        $expenseReceiptIds = ExpenseReceipt::whereDate('created_at','>=',$startDate)->whereDate('created_at','<=',$endDate)
                        ->where('status', true)->select('id')->pluck('id')->toArray();
        $unpaidExpenseReceiptData = ExpenseReceipt::orderBy('id','desc')->whereDate('created_at','>=',$startDate)->whereDate('created_at','<=',$endDate)
                        ->where('status', true)->get();

        //To get expense service data...
        $totalExpenseServiceQty = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->count();
        $totalExpenseServiceAmount = ExpenseReceiptService::orderBy('id','desc')
                    ->whereIn('expense_receipt_id', $expenseReceiptIds)->sum('expense_amount');

        $allData = [];
        $indexNumberForAll = 1;
        foreach($unpaidExpenseReceiptData as $key => $singleItem){
            if(isset($singleItem) && $singleItem != null){
                // To get expense total qty and amount...
                $totalExpenseQty = ExpenseReceiptService::getTotalExpenseReceiptServiceQty($singleItem->id);
                $totalExpenseAmount = ExpenseReceiptService::getTotalExpenseReceiptServiceAmount($singleItem->id);
                $allData[] = array(
                    'serial_no' => $singleItem->expense_receipt_id,
                    'receipt_by' => Str::title($singleItem->receipt_by),
                    'receipt_notes' => $singleItem->receipt_notes,
                    'expense_qty' => $totalExpenseQty,
                    'expense_amount'=>$totalExpenseAmount,
                    'date' => $singleItem->created_at->toDateString(),
                    'time' => $singleItem->created_at->toTimeString()
                );
            }
        }
        // Check user has permission...
        if (auth()->user()->hasPermissionTo('expense-between-report-access', 'web')) {
            return response()->json([
                'message'   =>  'Expense updated successfully.',
                'expense_data'   =>  $allData,
                'totalExpenseServiceQty'   =>  $totalExpenseServiceQty,
                'totalExpenseServiceAmount'   =>  $totalExpenseServiceAmount,
                'startDate'   =>  $startDate,
                'endDate'   =>  $endDate,
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }

    }
}
