<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Models\Event;
use App\Models\Product;
use App\Models\Permissions;
use App\Models\Sendpush;
use App\Models\Admin;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use DB;
use App\Models\Visitor;
use Config;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Laravel\Passport\Token;

class AuthController extends Controller
{
    public $successStatus = 200;
    public $failureStatus = 203;

    
    public function resetPassword(Request $request)
    {

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

        if ($validator->fails()) {
            return response()->json([
                'status' => false,                
                'msg' => $validator->errors()->first(),
            ], 400);
        }


        $allowedHost = 'frenzinsoftwares.com';
        $allowedIps = ['65.2.107.98'];
    
        $requestIp = $request->ip();
        // $request->getHost() === $allowedHost
        if ($request->input('token')) {
            $password = Hash::make($request->password);
            $decoded = base64_decode($request->input('token'));
            $implode_token = explode(',', $decoded);
            
            if (count($implode_token) === 3) {
                $customerId = $implode_token[0];
                $email = $implode_token[1];
                $timestamp = $implode_token[2];
                $formattedTime = date('Y-m-d H:i:s', (int)$timestamp);
                $user = User::where('CustomerID', $customerId)->where('email', $email)->first();
                if ($user) {                   
                    $user->password = $password;
                    $user->save();
    
                    return response()->json([
                        'status'=>true,
                        'message' => "Password updated successfully for $email on $formattedTime"
                    ],$this->successStatus);
                } else {
                    return response()->json([ 'status'=>false,'msg' => "User not found for CustomerID: $customerId and Email: $email"], $this->failureStatus);
                }
            } else {
                return response()->json([ 'status'=>false,'msg' => 'Invalid token format'], $this->failureStatus);
            }
        } else {
            return response()->json([ 'status'=>false,'msg' => "Unauthorized request from $requestIp "], $this->failureStatus);
        }
    }
    
    
}
