<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\FavoriteLiveTv;
use App\Models\Subscription;
use App\Models\WatchHistory;
use App\Traits\ImageTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class UserController extends Controller
{
    use ImageTrait;

    public function index($tab = 'account')
    {
        $user = auth()->user();
        $filter = request('time_filter');
        $paymentQuery = $user->paymentHistories()->with('package')->latest();
        $tab = request('tab') ?: 'account';
        if ($filter && $filter !== 'all') {
            switch ($filter) {
                case 'this_month':
                    $paymentQuery->whereMonth('created_at', now()->month)
                        ->whereYear('created_at', now()->year);
                    break;
                case 'last_month':
                    $paymentQuery->whereMonth('created_at', now()->subMonth()->month)
                        ->whereYear('created_at', now()->subMonth()->year);
                    break;
                case '1_month_ago':
                    $paymentQuery->whereMonth('created_at', now()->subMonths(1)->month)
                        ->whereYear('created_at', now()->subMonths(1)->year);
                    break;
                case '2_month_ago':
                    $paymentQuery->whereMonth('created_at', now()->subMonths(2)->month)
                        ->whereYear('created_at', now()->subMonths(2)->year);
                    break;
                case '3_month_ago':
                    $paymentQuery->whereMonth('created_at', now()->subMonths(3)->month)
                        ->whereYear('created_at', now()->subMonths(3)->year);
                    break;
            }
        }
        $data['playLists'] = $user->playLists()->withMovieCount()->get();
        $data['histories'] = WatchHistory::where('user_id', auth()->user()->id)->where('watchable_type', '!=', 'live_tv')->orderBy('last_watched_at', 'desc')->paginate(15);
        $data['live_tvs'] = WatchHistory::where('user_id', auth()->user()->id)->where('watchable_type', 'live_tv')->orderBy('last_watched_at', 'desc')->get();
        $data['movies'] = $user->favoriteMovies()->get();
        $data['tvShows'] = $user->favoriteTvShows()->get();
        $data['liveTvs'] = FavoriteLiveTv::where('user_id', auth()->user()->id)->get();
        $data['paymentHistories'] = $paymentQuery->paginate(10)->appends(request()->query());
        $data['tab'] = $tab;
        return view('user.dashboard', $data);
    }

    public function update(Request $request)
    {
        $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . auth()->user()->id,
            'phone' => 'nullable|string|max:50',
            'date_of_birth' => 'nullable|date',
            'gender' => 'nullable|string',
            'profile' => 'nullable|image|max:2048',
        ]);

        $user = auth()->user();

        // Handle image upload (Intervention Image v3: saveImage must complete or DB image can be cleared by imageDelete first)
        if ($request->hasFile('profile')) {
            try {
                $this->imageDelete($user->id, 'user', 'image');
                $response = $this->saveImage($request->file('profile'), '_user_');
                if (! is_array($response) || empty($response['images'])) {
                    return redirect()->back()->withErrors([
                        'profile' => __('something_went_wrong_please_try_again'),
                    ]);
                }
                $user->refresh();
                $user->image = json_encode($response['images']);
            } catch (\Throwable $e) {
                Log::error('User profile image upload failed: ' . $e->getMessage(), ['user_id' => $user->id]);

                return redirect()->back()->withErrors([
                    'profile' => __('something_went_wrong_please_try_again'),
                ]);
            }
        }

        // Update other fields
        $user->first_name = $request->first_name;
        $user->last_name = $request->last_name;
        $user->email = Str::lower((string) $request->email);
        $user->phone = $request->phone;
        $user->date_of_birth = $request->date_of_birth;
        $user->gender = $request->gender;

        if ($request->current_password && $request->new_password) {
            if (!Hash::check($request->current_password, $user->password)) {
                return redirect()->back()->withErrors(['current_password' => __('current_password_is_incorrect')]);
            }
            $user->password = Hash::make($request->new_password);
        }

        $user->save();
        Auth::guard('web')->setUser($user->fresh());

        return redirect()->back()->with('success_message', __('profile_update_successfully'));
    }
}
