<?php
// File: /home/okgroups/public_html/sm.okgroups.com/app/Http/Controllers/Web/Users/UsersController.php

namespace App\Http\Controllers\Web\Users;

use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use App\Events\User\Deleted;
use App\Http\Controllers\Controller;
use App\Http\Requests\User\CreateUserRequest;
use App\Models\User;
use App\Models\Purchase;
use App\Models\VoucherRedemption;
use App\Repositories\Country\CountryRepository;
use App\Repositories\Role\RoleRepository;
use App\Repositories\User\UserRepository;
use App\Support\Enum\UserStatus;

class UsersController extends Controller
{
    public function __construct(private readonly UserRepository $users)
    {
    }

    public function index(Request $request): View
    {
        // ✅ Base query
        $query = User::query();

        // ✅ Search by User Code (public_code)
        if ($request->filled('search')) {
            $query->where(function($q) use ($request) {
                $q->where('public_code', 'like', '%' . $request->search . '%')
                  ->orWhere('username', 'like', '%' . $request->search . '%')
                  ->orWhere('email', 'like', '%' . $request->search . '%');
            });
        }

        // ✅ Filter by Status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // ✅ Filter by OS
        if ($request->filled('os_filter')) {
            if ($request->os_filter === 'no_device') {
                $query->doesntHave('deviceTelemetry');
            } else {
                $query->whereHas('deviceTelemetry', function ($q) use ($request) {
                    $q->where('os', 'like', '%' . $request->os_filter . '%');
                });
            }
        }

        // ✅ Filter by Credit (فقط با credit_seconds)
        if ($request->filled('credit_filter')) {
            if ($request->credit_filter === 'zero') {
                // موجودی صفر
                $query->where(function($q) {
                    $q->where('credit_seconds', '<=', 0)
                      ->orWhereNull('credit_seconds');
                });
            } elseif ($request->credit_filter === 'low') {
                // موجودی کمتر یا مساوی 5 دقیقه (300 ثانیه)
                $query->whereBetween('credit_seconds', [1, 300]);
            } elseif ($request->credit_filter === 'high') {
                // موجودی بیشتر از 5 دقیقه (300 ثانیه)
                $query->where('credit_seconds', '>', 300);
            }
        }

        // ✅ Sorting با فلش
        $sortBy = $request->get('sort', 'created_at');
        $sortOrder = $request->get('order', 'desc');

        if ($sortBy === 'credit') {
            // Sort by credit_seconds
            $query->orderByRaw('COALESCE(credit_seconds, 0) ' . ($sortOrder === 'asc' ? 'ASC' : 'DESC'));
        } elseif ($sortBy === 'created_at') {
            $query->orderBy('created_at', $sortOrder);
        } else {
            // Default: آخرین ثبت‌نام بالا
            $query->orderBy('created_at', 'desc');
        }

        // ✅ Load device telemetry data
        $users = $query->with('deviceTelemetry')->paginate(20);

        // ✅ Append query params to pagination
        $users->appends($request->all());

        $statuses = ['' => __('All')] + UserStatus::lists();

        return view('user.list', compact('users', 'statuses'));
    }

    public function show(User $user): View
    {
        // ✅ لود تراکنش‌های کاربر
        $purchases = $user->purchases()->get();
        $voucherRedemptions = $user->voucherRedemptions()->with('voucher')->get();

        return view('user.view', compact('user', 'purchases', 'voucherRedemptions'));
    }

    public function create(CountryRepository $countryRepository, RoleRepository $roleRepository): View
    {
        return view('user.add', [
            'countries' => $this->parseCountries($countryRepository),
            'roles' => $roleRepository->lists(),
            'statuses' => UserStatus::lists(),
        ]);
    }

    /**
     * Parse countries into an array that also has a blank
     * item as first element, which will allow users to
     * leave the country field unpopulated.
     */
    private function parseCountries(CountryRepository $countryRepository): array
    {
        return [0 => __('Select a Country')] + $countryRepository->lists()->toArray();
    }

    public function store(CreateUserRequest $request): RedirectResponse
    {
        // When user is created by administrator, we will set his
        // status to Active by default.
        $data = $request->all() + [
            'status' => UserStatus::ACTIVE,
            'email_verified_at' => now(),
        ];

        $data['force_password_change'] = !!setting('password-change.enabled');

        if (! data_get($data, 'country_id')) {
            $data['country_id'] = null;
        }

        // Username should be updated only if it is provided.
        if (! data_get($data, 'username')) {
            $data['username'] = null;
        }

        $this->users->create($data);

        return redirect()->route('users.index')
            ->withSuccess(__('User created successfully.'));
    }

    public function edit(User $user, CountryRepository $countryRepository, RoleRepository $roleRepository): View
    {
        return view('user.edit', [
            'edit' => true,
            'user' => $user,
            'countries' => $this->parseCountries($countryRepository),
            'roles' => $roleRepository->lists(),
            'statuses' => UserStatus::lists(),
            'socialLogins' => $this->users->getUserSocialLogins($user->id),
        ]);
    }

    public function destroy(User $user): RedirectResponse
    {
        if ($user->is(auth()->user())) {
            return redirect()->route('users.index')
                ->withErrors(__('You cannot delete yourself.'));
        }

        $this->users->delete($user->id);

        event(new Deleted($user));

        return redirect()->route('users.index')
            ->withSuccess(__('User deleted successfully.'));
    }
}