<?php

namespace App\Http\Controllers;

use App\Mail\MemberChanges;
use App\Services\MemberService;
use App\Services\SummaryService;
use App\Services\UserService;
use Illuminate\Support\Facades\Mail;
use App\Http\Requests\Member\SummaryStore;

class SummaryController extends Controller
{

    private $summaryService;
    private $memberService;

    public function __construct(
        MemberService $memberService,
        UserService $userService,
        SummaryService $summaryService
    ) {
        $this->memberService = $memberService;
        $this->summaryService = $summaryService;
        $this->userService = $userService;
        $this->middleware('auth:sanctum');
    }

    public function index()
    {
        $summaries = $this->summaryService->getAll();

        return response()->json($summaries, 201);
    }

    public function store(SummaryStore $request)
    {
        $member = $this->memberService->get($request->member_id);

        if (!$member) {
            return response()->json(['message' => 'Member not found.'], 404);
        }

        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isSuperAdminOrAdmin = $isSuperAdmin || $isAdmin;
        $isUserDelegated = $member->user_id === auth()->user()->id;

        $isAppliedToAll = $request->has('toAll') ? true : false;

        if (!$isSuperAdminOrAdmin && !$isUserDelegated) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $request_data = $request->validated();

        $is_edit_mode = isset($request_data['id']);
        $is_create_mode = !$is_edit_mode;

        $summary = null;

        if ($is_edit_mode) {

            if ($isSuperAdminOrAdmin) {
                $request_data['revisor_id'] = auth()->user()->id;
                $request_data['approved_at'] = now();
            }

            $summary = $this->summaryService->get($request_data['id']);
            $is_already_approved = $summary->approved_at;

            if ($isUserDelegated && !$isSuperAdminOrAdmin && $is_already_approved) {
                return response()->json(['message' => 'You have no rights to do this'], 401);
            }
        }

        if ($isAppliedToAll && $is_create_mode) {

            if ($isUserDelegated && !$isSuperAdminOrAdmin) {
                return response()->json(['message' => 'You have no rights to do this'], 401);
            }

            $members = $this->memberService->with(['summaries']);

            //  Store for all existing members
            foreach ($members as $member) {

                // If the member doesn't have that year set, store the record
                if (!$member->summaries->contains('year', $request_data['year'])) {

                    $request_data['member_id'] = $member['id'];

                    // Gives back the summary to update the page
                    if ($request_data['member_id'] === $member['user_id']) {
                        $summary = $this->summaryService->save($request_data);
                    } else {
                        $this->summaryService->save($request_data);
                    }
                }
            }
        } else {
            $summary = $this->summaryService->save($request_data);
        }

        // If is a user delegated to make changes, send a mail
        if ($isUserDelegated) {

            // Get super admins & admins, send them an email
            $super_admins_and_admins = $this->userService->getAllWithRoles(['super_admin', 'admin']);

            $notification = (object) array();
            $notification->member = $member;
            $notification->subject = 'Er zijn wijzigingen doorgevoerd';
            $notification->message = sprintf(
                'De volgende wijzigingen kunnen worden beoordeeld, voor het volgende lid: <em>%s</em>',
                $member->informal_name,
            );

            // Add emails to queue | * php artisan queue:listen
            foreach ($super_admins_and_admins as $user) {
                Mail::to($user)->send(new MemberChanges($notification));
            }
        }

        return response()->json($summary, 201);
    }

    public function show($id)
    {
        $summary = $this->summaryService->get($id);

        return response()->json($summary);
    }

    public function destroy($id)
    {
        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isSuperAdminOrAdmin = $isSuperAdmin || $isAdmin;

        if (!$isSuperAdminOrAdmin) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $this->summaryService->delete($id);
        return response()->json(null, 204);
    }
}
