<?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\Hash;
use Illuminate\Http\UploadedFile;

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|email|unique:users,email,' . auth()->user()->id,
            'phone' => 'nullable|string',
            'date_of_birth' => 'nullable|date',
            'gender' => 'nullable|string',
            'profile' => 'nullable|image|max:2048',
        ]);

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

        // Handle image upload
        if ($request->hasFile('profile')) {
            $this->imageDelete($user->id, 'user', 'image');
            $response = $this->saveImage($request->file('profile'), '_user_');
            $user->image = json_encode($response['images']);
        }

        // Update other fields
        $user->first_name = $request->first_name;
        $user->last_name = $request->last_name;
        $user->email = $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();
        return redirect()->back()->with('success_message', __('profile_update_successfully'));
    }
}
