<?php

namespace App\Http\Controllers\User;

use App\Constants\Status;
use App\Http\Controllers\Controller;
use App\Models\DeviceToken;
use App\Models\BookedTicket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    public function home()
    {
        $pageTitle = 'Dashboard';
        $user = auth()->user()->load('tickets');
        $bookedTickets = $user->tickets()->booked()->whereHas('trip', function($query) {
            $query->availableTrip();
        })->get();
        return view('Template::user.dashboard', compact('pageTitle', 'bookedTickets'));
    }



    public function userData()
    {
        $user = auth()->user();

        if ($user->profile_complete == Status::YES) {
            return to_route('user.home');
        }

        $pageTitle  = 'Complete Your Profile';
        $info       = json_decode(json_encode(getIpInfo()), true);
        $mobileCode = @implode(',', $info['code']);
        $countries  = json_decode(file_get_contents(resource_path('views/partials/country.json')));

        return view('Template::user.user_data', compact('pageTitle', 'user', 'countries', 'mobileCode'));
    }

    public function userDataSubmit(Request $request)
    {

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

        if ($user->profile_complete == Status::YES) {
            return to_route('user.home');
        }

        $countryData  = (array)json_decode(file_get_contents(resource_path('views/partials/country.json')));
        $countryCodes = implode(',', array_keys($countryData));
        $mobileCodes  = implode(',', array_column($countryData, 'dial_code'));
        $countries    = implode(',', array_column($countryData, 'country'));

        $request->validate([
            'country_code' => 'required|in:' . $countryCodes,
            'country'      => 'required|in:' . $countries,
            'mobile_code'  => 'required|in:' . $mobileCodes,
            'gender' => 'required|integer|gt:-1|lt:4',
            'username'     => 'required|unique:users|min:6',
            'mobile'       => ['required', 'regex:/^([0-9]*)$/', Rule::unique('users')->where('dial_code', $request->mobile_code)],
        ]);


        if (preg_match("/[^a-z0-9_]/", trim($request->username))) {
            $notify[] = ['info', 'Username can contain only small letters, numbers and underscore.'];
            $notify[] = ['error', 'No special character, space or capital letters in username.'];
            return back()->withNotify($notify)->withInput($request->all());
        }

        $user->country_code = $request->country_code;
        $user->mobile       = $request->mobile;
        $user->username     = $request->username;
        $user->gender       = $request->gender;


        $user->address = $request->address;
        $user->city = $request->city;
        $user->state = $request->state;
        $user->zip = $request->zip;
        $user->country_name = $request->country;
        $user->dial_code = $request->mobile_code;

        $user->profile_complete = Status::YES;
        $user->save();

        return to_route('user.home');
    }


    public function addDeviceToken(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'token' => 'required',
        ]);

        if ($validator->fails()) {
            return ['success' => false, 'errors' => $validator->errors()->all()];
        }

        $deviceToken = DeviceToken::where('token', $request->token)->first();

        if ($deviceToken) {
            return ['success' => true, 'message' => 'Already exists'];
        }

        $deviceToken          = new DeviceToken();
        $deviceToken->user_id = auth()->id();
        $deviceToken->token   = $request->token;
        $deviceToken->is_app  = Status::NO;
        $deviceToken->save();

        return ['success' => true, 'message' => 'Token saved successfully'];
    }


    public function ticketHistory(){
        $pageTitle = 'Booking History';
        $emptyMessage = 'No booked ticket found';
        $user = auth()->user();
        $widget['booked'] = $user->tickets()->booked()->count();
        $widget['pending'] = $user->tickets()->pending()->count();
        $widget['rejected'] = $user->tickets()->failed()->count();
        $widget['canceled'] = $user->tickets()->canceled()->count();
        $bookedTickets = $user->tickets()->orderBy('id', 'desc')->paginate(getPaginate());
        return view('Template::user.booking_history', compact('pageTitle', 'emptyMessage', 'bookedTickets', 'widget'));
    }

    public function bookingDetail($pnrNumber) {
        $pageTitle = 'Booking Details';
        $bookedTicket = BookedTicket::with(['trip.fleetType','trip.startFrom', 'trip.endTo' ,'pickup', 'drop', 'user'])->where('user_id', auth()->id())->where('pnr_number', $pnrNumber)->firstOrFail();
        return view('Template::user.booking_detail', compact('pageTitle', 'bookedTicket'));
    }

    public function bookingSuccess($pnrNumber) {
        $pageTitle = 'Booking Success';
        $bookedTicket = BookedTicket::with(['trip.fleetType','trip.startFrom', 'trip.endTo' ,'pickup', 'drop', 'user'])->where('user_id', auth()->id())->where('pnr_number', $pnrNumber)->firstOrFail();
        return view('Template::user.booking_success', compact('pageTitle', 'bookedTicket'));
    }

    public function printTicket($id){
        $pageTitle = "Ticket Print";
        $ticket = BookedTicket::with(['trip.fleetType','trip.startFrom', 'trip.endTo' ,'pickup', 'drop', 'user'])->where('user_id', auth()->id())->findOrFail($id);
        $termsConditions = gs('ticket_terms_conditions');
        return view('Template::print_ticket', compact('ticket', 'pageTitle', 'termsConditions'));
    }


    public function bookingRepayment($id) {
        $id = decrypt($id);
        $bookedTicket = BookedTicket::pending()->where('id', $id)->firstOrFail();

        $holdTimeInSeconds = gs('ticket_hold_time');
        $cutoffTime = now()->subSeconds($holdTimeInSeconds);

        if ($bookedTicket->last_payment_attempt_at > $cutoffTime) {
            $bookedTicket->last_payment_attempt_at = now();
            $bookedTicket->save();
            session()->put('pnr_number', $bookedTicket->pnr_number);
            return redirect()->route('user.deposit.index');
        }
        $bookedTicket->status = Status::BOOKED_FAILED;
        $bookedTicket->save();

        $notify[] = ['error', 'Payment attempt expired. Please initiate a new booking.'];
        return back()->withNotify($notify);
    }

}
