<?php

declare(strict_types=1);

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use App\Models\FormUpCountry;
use App\Models\FormEntertaimentPresentation;
use App\Models\FormVehicleRunningCost;
use App\Models\FormMeetingSeminar;
use App\Models\FormOthers;
use App\Models\UserHasCabang;
use App\Models\Notifications;


class DashboardController extends Controller
{
    public function index()
    {
        $role = auth()->user()->getRoleNames()[0];
        $startDate = date('Y-m-' . env('STARTING_DATE')); // Starting date from .env for the current month
        $closingDateNextMonth = date('Y-m-', strtotime('+1 month')) . env('CLOSING_DATE'); // Closing date for the next month

        $forms = [
            'vehicle' => FormVehicleRunningCost::whereMonth('tanggal', date('m'))
                        ->whereBetween('tanggal', [$startDate, $closingDateNextMonth])
                        ->orderBy('tanggal', 'desc')
                        ->get(),
            'upcountry' => FormUpCountry::whereMonth('tanggal', date('m'))
                        ->whereBetween('tanggal', [$startDate, $closingDateNextMonth])
                        ->orderBy('tanggal', 'desc')
                        ->get(),
            'entertainment' => FormEntertaimentPresentation::whereMonth('tanggal', date('m'))
                        ->whereBetween('tanggal', [$startDate, $closingDateNextMonth])
                        ->orderBy('tanggal', 'desc')
                        ->get(),
            'meeting' => FormMeetingSeminar::whereMonth('created_at', date('m'))
                        ->whereBetween('created_at', [$startDate, $closingDateNextMonth])
                        ->orderBy('created_at', 'desc')
                        ->get(),
            'others' => FormOthers::whereMonth('tanggal', date('m'))
                        ->whereBetween('tanggal', [$startDate, $closingDateNextMonth])
                        ->orderBy('tanggal', 'desc')
                        ->get(),
        ];

        if ($role == 'Admin Region' || $role == 'Marketing Operational Manager Region') {
            $region_id = auth()->user()->getMyCabangAndRegionId()['region'];

            if ($region_id) {
                $users = UserHasCabang::whereHas('cabang', function ($query) use ($region_id) {
                    $query->where('region_id', $region_id);
                })->pluck('user_id');

                foreach ($forms as $key => $query) {
                    $forms[$key] = $query->whereIn('user_id', $users)->whereIn('status', ['Approved', 'Closed']);
                }
            }
        } elseif ($role == 'Area Manager Cabang') {
            $cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'];

            if ($cabang_id) {
                $users = UserHasCabang::where('cabang_id', $cabang_id)->pluck('user_id');

                foreach ($forms as $key => $query) {
                    $forms[$key] = $query->whereIn('user_id', $users)->whereIn('status', ['Approved', 'Closed']);
                }
            }
        } elseif ($role == 'Medical Representatif') {
            foreach ($forms as $key => $query) {
                $forms[$key] = $query->where('user_id', auth()->user()->id)->whereIn('status', ['Approved', 'Closed']);
            }
        } else {
            foreach ($forms as $key => $query) {
                $forms[$key] = $query->whereIn('status', ['Approved', 'Closed']);
            }
        }

        // Sum the filtered queries
        foreach ($forms as $key => $query) {
            $forms[$key] = $query->sum('approved_total');
        }

        return view(
            'backend.pages.dashboard.index',
            [
                'forms' => $forms,
            ]
        );
    }

    public function notifications()
    {
        $this->checkAuthorization(auth()->user(), ['notification.view']);

        // Mulai dengan query dasar
        $notifications = Notifications::orderBy('created_at', 'desc')
            ->where('receiver_id', auth()->user()->id)
            ->where('is_read', 0);

        // Ambil data dan kembalikan sebagai JSON
        return response()->json([
            'count' => $notifications->count(),
            'data' => $notifications->take(7)->get(),
        ]);
    }

    public function mark_read($id)
    {
        $this->checkAuthorization(auth()->user(), ['notification.delete']);
        $receiver_id = auth()->user()->id;

        Notifications::where('receiver_id', $receiver_id)->where('id', $id)->update(['is_read' => 1]);

        return response()->json(['message' => 'Notification marked as read.']);
    }

    public function mark_all_read()
    {
        $this->checkAuthorization(auth()->user(), ['notification.delete']);
        $receiver_id = auth()->user()->id;

        Notifications::where('receiver_id', $receiver_id)->update(['is_read' => 1]);

        session()->flash('success', 'All notifications marked as read.');
        return redirect()->back();
    }
}
