<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\Admin\Contracts\AdminServiceInterface;
use Carbon\Carbon;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    public function __construct(
        private AdminServiceInterface $adminService
    ) {}

    public function index(Request $request)
    {
        $selectedMonth = $request->input('month', Carbon::now()->format('Y-m'));
        $search        = $request->input('search');
        $status        = $request->input('status', (string)config('constants.STATUS_ACTIVE'));
        $role          = $request->input('role');
        $department    = $request->input('department');
        $flagSend      = $request->input('flag_send');

        [
            'users' => $users,
            'topReceivedUser' => $topReceivedUser,
            'topSentUser' => $topSentUser,
            'topReceivedUsers' => $topReceivedUsers,
            'topSentUsers' => $topSentUsers
        ] = $this->adminService->getUserListWithStats($selectedMonth, $search, $status, $role, $department, $flagSend);

        if ($request->ajax() || $request->wantsJson()) {
            return response()->json([
                'title' => view('admin.users.partials.title', compact('selectedMonth'))->render(),
                'stats' => view('admin.users.partials.stats', compact('topReceivedUser', 'topSentUser', 'topReceivedUsers', 'topSentUsers'))->render(),
                'table' => view('admin.users.partials.table', compact('users'))->render(),
            ]);
        }

        return view('admin.users.index', compact(
            'users', 
            'selectedMonth', 
            'topReceivedUser', 
            'topSentUser', 
            'topReceivedUsers',
            'topSentUsers',
            'search', 
            'status',
            'role',
            'department',
            'flagSend'
        ));
    }

    public function create()
    {
        return view('admin.users.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'msnv'        => 'required|integer|unique:user,msnv',
            'name'        => 'required|string|max:255',
            'mail'        => 'required|email|unique:user,mail',
            'departments' => 'required|string|in:' . implode(',', config('constants.DEPARTMENTS')),
            'password'    => 'required|string',
            'role'        => 'required|in:' . config('constants.ROLE_MEMBER') . ',' . config('constants.ROLE_ADMIN'),
        ]);

        $this->adminService->createUser($request->only('msnv', 'name', 'mail', 'departments', 'password', 'role'));

        return redirect()->route('admin.users.index')->with('success', __('messages.user_create_success'));
    }

    public function edit(Request $request, $msnv)
    {
        $user          = User::where('msnv', $msnv)->firstOrFail();
        $selectedMonth = $request->input('month', Carbon::now()->format('Y-m'));

        $administrations = $this->adminService->getUserTransactions($msnv, $selectedMonth);

        $addCards = \App\Models\AddCard::with('sellerUser')
            ->where('buyer', $user->msnv)
            ->orderBy('date', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        $admins = User::where('role', config('constants.ROLE_ADMIN'))
            ->where('status', config('constants.STATUS_ACTIVE'))
            ->get();

        return view('admin.users.edit', compact('user', 'administrations', 'selectedMonth', 'addCards', 'admins'));
    }

    public function update(Request $request, $msnv)
    {
        $request->validate([
            'card'        => 'required|integer|min:0',
            'role'        => 'required|in:' . config('constants.ROLE_MEMBER') . ',' . config('constants.ROLE_ADMIN'),
            'status'      => 'required|in:' . config('constants.STATUS_INACTIVE') . ',' . config('constants.STATUS_ACTIVE'),
            'flag_send'   => 'required|in:' . config('constants.FLAG_SEND_DISABLED') . ',' . config('constants.FLAG_SEND_ENABLED'),
            'first_login' => 'required|in:' . config('constants.FIRST_LOGIN_FALSE') . ',' . config('constants.FIRST_LOGIN_TRUE'),
        ]);

        $this->adminService->updateUser($msnv, $request->only('card', 'role', 'status', 'flag_send', 'first_login'));

        return redirect()->back()->with('success', __('messages.user_update_success'));
    }

    public function destroy($msnv)
    {
        $this->adminService->deactivateUser($msnv);

        return redirect()->route('admin.users.index')->with('success', __('messages.user_deactivate_success'));
    }

    public function updateAddCard(Request $request, $id)
    {
        $request->validate([
            'num_card' => 'required|integer|min:1',
            'seller'   => 'required|exists:user,msnv',
            'date'     => 'required|date',
        ]);

        try {
            $this->adminService->updateAddCard(intval($id), $request->only('num_card', 'seller', 'date'));
            return redirect()->back()->with('success', 'Cập nhật lịch sử cấp phát thẻ thành công.');
        } catch (\Exception $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    public function resetCards()
    {
        $this->adminService->resetAllCards();

        return redirect()->back()->with('success', __('messages.cards_reset_success'));
    }
}
