<?php

namespace App\Http\Controllers;

use App\Mail\ForgotPasswordMail;
use App\Models\CountryCode;
use App\Models\ServicePackage;
use App\Models\User;
use App\Services\PermissionService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class AuthController extends Controller
{
    public function login()
    {
        return view('app.auth.login');
    }

    public function loginSubmit(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (!Auth::attempt($credentials)) {
            return back()->with('error', 'Invalid credentials');
        }


        if (!Auth::user()->sub_end_date) {
            return redirect('app/invoice-for-new-customer');
        }

        $permission = (new PermissionService())->getPermissionByRole(Auth::user()->user_type_id);

        Session::put('permission', $permission->groupBy('group_name'));


        return redirect('app');
    }

    public function logout()
    {
        Auth::logout();
        Session::flush();
        return redirect('app/login');
    }

    public function register(Request $request)
    {

        $selected_package = ServicePackage::with('serviceCategory')->where('id', $request->package)->first();
        if (!$selected_package) {
            return redirect('/')->with('error', 'Please select a valid package');
        }

        $country_codes = CountryCode::all();

        $duration = 1;
        if ($selected_package->type == 'yearly') {
            $duration = 12;
        }

        $discount_percentage = $selected_package->discount;
        $expected_end_date = date('Y-m-d', strtotime('+' . $duration . ' months'));
        $grand_total = $selected_package->price - ($selected_package->price * $discount_percentage / 100);

        return view('app.auth.register', compact('selected_package', 'duration', 'grand_total', 'expected_end_date', 'discount_percentage', 'country_codes'));
    }

    public function forgotPassword()
    {
        return view('app.auth.forgot-password');
    }

    public function forgotPasswordSubmit(Request $request)
    {
        $user = User::where('email', operator: $request->email)->first();

        if (!$user) {
            return back()->with('error', 'Email not found');
        }

        $token = Str::random(64);

        DB::table('password_reset_tokens')->insert([
            'email' => $request->email,
            'token' => $token,
            'expires_at' => Carbon::now()->addHour(),
            'created_at' => Carbon::now()
        ]);

        Mail::to($request->email)->send(new ForgotPasswordMail($token));

        return back()->with('success', 'Password reset link sent to your email');
    }

    public function resetPassword(Request $request)
    {
        $token = $request->token;
        $tokenData = DB::table('password_reset_tokens')->where('token', $token)->whereNull('used_at')->where('expires_at', '>', Carbon::now())->first();

        if (!$tokenData) {
            return redirect('app/forgot-password')->with('error', 'Invalid token');
        }

        return view('app.auth.reset-password', compact('token'));
    }

    public function resetPasswordSubmit(Request $request)
    {
        $validated = Validator::make($request->all(), [
            'password' => 'required|confirmed|min:6',
            'token' => 'required'
        ]);

        if ($validated->fails()) {
            return back()->with('error', $validated->errors()->first());
        }

        $token = $request->token;
        $tokenData = DB::table('password_reset_tokens')->where('token', $token)->whereNull('used_at')->where('expires_at', '>', Carbon::now())->first();

        if (!$tokenData) {
            return redirect('app/forgot-password')->with('error', 'Token expired');
        }

        try {
            DB::beginTransaction();
            $user = User::where('email', $tokenData->email)->first();
            $user->password = bcrypt($request->password);
            $user->save();

            DB::table('password_reset_tokens')->where('token', $token)->update(['used_at' => Carbon::now()]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }

        return redirect('app/login')->with('success', 'Password reset successful');
    }
}
