<?php

declare(strict_types=1);

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\BudgetControl;
use App\Models\BudgetControlLog;
use App\Models\Admin;
use Illuminate\Http\Request;
use App\Models\FormUpCountry;
use App\Models\FormMeetingSeminar;
use App\Models\FormOthers;
use App\Models\FormEntertaimentPresentation;
use App\Models\FormVehicleRunningCost;

class BudgetControlController extends Controller
{
    public function index()
	{
		$this->checkAuthorization(auth()->user(), ['budget_control.view']);
		session()->put('redirect_url', route('budget_control'));

		// Get the budget control data
		$budget = BudgetControl::orderBy('created_at', 'desc')->with(['user', 'cabang'])->get();

		// Initialize an empty array to hold the used budget sums
		$usedBudget = [];

		foreach ($budget as $b) {
			// Get the month and year from the budget
			$month = $b->periode_month;
			$year = $b->periode_year;

			// Add the used budget per model for the specified month and year to the usedBudget array
			$usedBudget[] = [
				'FormUpCountry' => FormUpCountry::whereIn('status', ['Approved', 'Closed'])
					->whereMonth('tanggal', '=', date('m', strtotime($month)))
					->whereYear('tanggal', '=', $year)
					->sum('approved_total'),

				'FormMeetingSeminar' => FormMeetingSeminar::whereIn('status', ['Approved', 'Closed'])
					->whereMonth('created_at', '=', date('m', strtotime($month)))
					->whereYear('created_at', '=', $year)
					->sum('approved_total'),

				'FormOthers' => FormOthers::whereIn('status', ['Approved', 'Closed'])
					->whereMonth('tanggal', '=', date('m', strtotime($month)))
					->whereYear('tanggal', '=', $year)
					->sum('approved_total'),

				'FormEntertaimentPresentation' => FormEntertaimentPresentation::whereIn('status', ['Approved', 'Closed'])
					->whereMonth('tanggal', '=', date('m', strtotime($month)))
					->whereYear('tanggal', '=', $year)
					->sum('approved_total'),

				'FormVehicleRunningCost' => FormVehicleRunningCost::whereIn('status', ['Approved', 'Closed'])
					->whereMonth('tanggal', '=', date('m', strtotime($month)))
					->whereYear('tanggal', '=', $year)
					->sum('approved_total')
			];
		}

		$usedBudget = array_sum(array_map(function ($b) {
			return array_sum($b);
		}, $usedBudget));

		return view(
			'backend.pages.budget_control.index',
			[
				'data' => $budget,
				'usedBudget' => $usedBudget,
				'availableBudget' => $budget->sum('amount') - $usedBudget,
			]
		);
	}

	public function log()
    {
		$this->checkAuthorization(auth()->user(), ['budget_control.view']);
		session()->put('redirect_url', route('budget_control'));

        return view(
            'backend.pages.budget_control.log',
            [
                'data' => BudgetControlLog::orderBy('created_at', 'desc')->with(['user', 'cabang'])->get(),
            ]
        );
    }

	public function create()
	{
		$this->checkAuthorization(auth()->user(), ['budget_control.create']);
		$users = Admin::getUserByRoleName('Area Manager Cabang');

		return view('backend.pages.budget_control.create', [
			'users' => $users,
		]);
	}

	public function store(Request $request)
	{
		$this->checkAuthorization(auth()->user(), ['budget_control.create']);

		$validated = $request->validate([
			'receiver_id' => 'required|exists:admins,id',
			'periode_month' => 'required|string|in:january,february,march,april,may,june,july,august,september,october,november,december',
			'periode_year' => 'required|numeric',
			'amount' => 'required|numeric',
			'remarks' => 'nullable|string',
			'closing_at' => 'required|date',
		]);

		$cabang_id = Admin::find($validated['receiver_id'])->getMyCabangAndRegionId()['cabang'];
		BudgetControl::updateOrCreate(['cabang_id' => $cabang_id],
		[
			'sender_id' => auth()->user()->id,
			'receiver_id' => $validated['receiver_id'],
			'periode_month' => $validated['periode_month'],
			'periode_year' => $validated['periode_year'],
			'amount' => $validated['amount'],
			'remarks' => $validated['remarks'],
			'closing_at' => $validated['closing_at'],
			'status' => 'Assigned',
		]);

		BudgetControlLog::create([
			'cabang_id' => $cabang_id,
			'sender_id' => auth()->user()->id,
			'receiver_id' => $validated['receiver_id'],
			'periode_month' => $validated['periode_month'],
			'periode_year' => $validated['periode_year'],
			'amount' => $validated['amount'],
			'remarks' => $validated['remarks'],
			'closing_at' => $validated['closing_at'],
			'status' => 'Assigned',
		]);

		session()->flash('success', 'Budget has been added or updated successfully');
		return redirect()->route('budget_control');
	}

	public function destroy($id)
	{
		$this->checkAuthorization(auth()->user(), ['budget_control.delete']);

		$budgetRequest = BudgetControl::findOrfail($id);
		$budgetRequest->delete();

		return redirect()->route('budget_control');
	}
}
