<?php

namespace App\Services\Admin;

use App\Models\AddCard;
use App\Models\Administration;
use App\Models\User;
use App\Services\Admin\Contracts\AdminServiceInterface;
use Carbon\Carbon;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class AdminService implements AdminServiceInterface
{
    public function getUserListWithStats(
        string $selectedMonth, 
        ?string $search = null, 
        ?string $status = '1',
        ?string $role = null,
        ?string $department = null,
        ?string $flagSend = null
    ): array {
        $startOfMonth = Carbon::parse($selectedMonth)->startOfMonth();
        $endOfMonth   = Carbon::parse($selectedMonth)->endOfMonth();

        $usersQuery = User::select('user.*')
            ->addSelect([
                'total_received' => Administration::selectRaw('COALESCE(SUM(received), 0)')
                    ->whereColumn('msnv', 'user.msnv')
                    ->whereBetween('date', [$startOfMonth, $endOfMonth]),
                'total_sent' => Administration::selectRaw('COALESCE(SUM(sent), 0)')
                    ->whereColumn('msnv', 'user.msnv')
                    ->whereBetween('date', [$startOfMonth, $endOfMonth])
            ]);

        $activeUsers = (clone $usersQuery)->where('status', config('constants.STATUS_ACTIVE'))->get();

        $maxReceived = $activeUsers->max('total_received') ?? 0;
        $maxSent     = $activeUsers->max('total_sent') ?? 0;

        $topReceivedUsers = $maxReceived > 0 
            ? $activeUsers->filter(fn($u) => $u->total_received == $maxReceived)->values() 
            : collect();

        $topSentUsers = $maxSent > 0 
            ? $activeUsers->filter(fn($u) => $u->total_sent == $maxSent)->values() 
            : collect();

        $topReceivedUser = $topReceivedUsers->first();
        $topSentUser     = $topSentUsers->first();

        if (!is_null($status) && $status !== '') {
            $usersQuery->where('status', intval($status));
        }

        if (!is_null($role) && $role !== '') {
            $usersQuery->where('role', intval($role));
        }

        if (!is_null($department) && $department !== '') {
            $usersQuery->where('departments', $department);
        }

        if (!is_null($flagSend) && $flagSend !== '') {
            $usersQuery->where('flag_send', intval($flagSend));
        }

        if (!is_null($search) && trim($search) !== '') {
            $search = trim($search);
            $usersQuery->where(function ($q) use ($search) {
                $q->whereRaw('LOWER(msnv) LIKE ?', ['%' . strtolower($search) . '%'])
                  ->orWhereRaw('LOWER(name) LIKE ?', ['%' . strtolower($search) . '%'])
                  ->orWhereRaw('LOWER(mail) LIKE ?', ['%' . strtolower($search) . '%']);
            });
        }
        $users = $usersQuery->paginate(20)->withQueryString();

        return compact('users', 'topReceivedUser', 'topSentUser', 'topReceivedUsers', 'topSentUsers');
    }

    public function getUserTransactions(string $msnv, string $selectedMonth): LengthAwarePaginator
    {
        $startOfMonth = Carbon::parse($selectedMonth)->startOfMonth();
        $endOfMonth   = Carbon::parse($selectedMonth)->endOfMonth();

        return Administration::where('msnv', $msnv)
            ->whereBetween('date', [$startOfMonth, $endOfMonth])
            ->orderBy('date', 'desc')
            ->paginate(10)
            ->withQueryString();
    }

    public function createUser(array $data): void
    {
        User::create([
            'msnv'        => $data['msnv'],
            'name'        => $data['name'],
            'mail'        => $data['mail'],
            'pass'        => md5($data['password']),
            'departments' => $data['departments'],
            'role'        => $data['role'],
            'status'      => config('constants.STATUS_ACTIVE'),
            'card'        => 0,
            'flag_send'   => config('constants.FLAG_SEND_DISABLED'),
            'first_login' => $data['role'] == config('constants.ROLE_ADMIN') ? config('constants.FIRST_LOGIN_FALSE') : config('constants.FIRST_LOGIN_TRUE'),
        ]);
    }

    public function updateUser(string $msnv, array $data): void
    {
        $user = User::where('msnv', $msnv)->firstOrFail();

        DB::transaction(function () use ($data, $user) {
            $newCard = intval($data['card']);
            $oldCard = intval($user->card);

            if ($newCard > $oldCard) {
                $diff = $newCard - $oldCard;
                AddCard::create([
                    'buyer'    => $user->msnv,
                    'num_card' => $diff,
                    'seller'   => Auth::user()->msnv,
                    'date'     => Carbon::today(),
                ]);
            }

            $user->card        = $newCard;
            $user->role        = intval($data['role']);
            $user->status      = intval($data['status']);
            $user->flag_send   = intval($data['flag_send']);
            $user->first_login = intval($data['first_login']);
            $user->save();
        });
    }

    public function deactivateUser(string $msnv): void
    {
        $user = User::where('msnv', $msnv)->firstOrFail();
        $user->status = config('constants.STATUS_INACTIVE');
        $user->save();
    }

    public function resetAllCards(): void
    {
        User::where('status', config('constants.STATUS_ACTIVE'))->update(['card' => 0]);
    }

    public function updateAddCard(int $id, array $data): void
    {
        $addCard = AddCard::findOrFail($id);


        $currentMonth = Carbon::now()->format('Y-m');
        $recordMonth = Carbon::parse($addCard->date)->format('Y-m');

        if ($recordMonth !== $currentMonth) {
            throw new \Exception('Không cho phép chỉnh sửa dữ liệu card của các tháng trước.');
        }

        $newDateMonth = Carbon::parse($data['date'])->format('Y-m');
        if ($newDateMonth !== $currentMonth) {
            throw new \Exception('Chỉ được phép chỉnh sửa dữ liệu của tháng hiện tại.');
        }

        $user = User::where('msnv', $addCard->buyer)->firstOrFail();

        DB::transaction(function () use ($addCard, $user, $data) {
            $oldNumCard = intval($addCard->num_card);
            $newNumCard = intval($data['num_card']);
            $diff = $newNumCard - $oldNumCard;

            if ($user->card + $diff < 0) {
                throw new \Exception('Số lượng card cập nhật không hợp lệ vì tổng số card của user không được nhỏ hơn 0.');
            }

            $user->card += $diff;
            $user->save();

            $addCard->num_card = $newNumCard;
            $addCard->seller   = $data['seller'];
            $addCard->date     = $data['date'];
            $addCard->save();
        });
    }
}