<?php

namespace App\Http\Controllers\Auth;

use Exception;
use App\Models\User;
use App\Models\Restaurant;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{

    public function restaurantLogin(Request $request)
    {

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

        if($validator->fails()){
            return response()->json($validator->errors());
        } else {
            return DB::transaction(function () use ($request) {
                $restaurant = Restaurant::where('r_number', $request->number)->first();

                if ($restaurant) {
                    if($restaurant->status=='1'){
                        $user = $restaurant->user;
                        if (! $user) {
                            $user = $this->createUserForNumber($request->number);
                            $restaurant->user_id = $user->id;
                            $restaurant->save();
                        }
                    } else {
                        return response()->json([
                            'data' => 'This User In Inactive',
                        ]);
                    }
                } else {
                    return response()->json([
                        'data' => 'User Not Found',
                    ], 404);
                }

                $token = $user->createToken('mobile-token')->plainTextToken;

                return response()->json([
                    'token' => $token,
                    'user' => $user,
                    'restaurant' => $restaurant
                ]);
            });
        }
    }

    // public function store(Request $request)
    // {
    //     $validator = Validator::make($request->all(), [
    //         'r_number' => 'required|unique:restaurants,r_number',
    //         'name'     => 'required|string|max:255',
    //     ]);

    //     if ($validator->fails()) {
    //         return response()->json([
    //             'errors' => $validator->errors()
    //         ], 422);
    //     }

    //     try {
    //         $user = $this->createUserForNumber($request->r_number);

    //         $restaurant = Restaurant::create([
    //             'r_number' => $request->r_number,
    //             'name'     => $request->name,
    //             'user_id'  => $user->id,
    //             'status'  => '1',
    //         ]);

    //         return response()->json([
    //             'success' => true,
    //             'data'    => $restaurant
    //         ], 200);

    //     } catch (\Exception $exp) {
    //         return response()->json([
    //             'error' => $exp->getMessage(),
    //         ], 500);
    //     }
    // }
    
    
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'r_number' => 'required|unique:restaurants,r_number',
            'name'     => 'required|string|max:255',
            'image'    => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048', // validate image
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()
            ], 422);
        }
    
        try {
            $user = $this->createUserForNumber($request->r_number);
    
            $restaurantData = [
                'r_number' => $request->r_number,
                'name'     => $request->name,
                'user_id'  => $user->id,
                'status'   => '1',
            ];
    
            // Handle image upload
            if($request->hasFile('image')){
                $image = $request->file('image');
                $imageName = time() . '_' . $image->getClientOriginalName();
                $image->move(public_path('uploads/restaurants'), $imageName);
                $restaurantData['image'] = $imageName;
            }
    
            $restaurant = Restaurant::create($restaurantData);
    
            // Send image URL in response for frontend
            $restaurant->image_url = $restaurant->image ? asset('uploads/restaurants/' . $restaurant->image) : '';
    
            return response()->json([
                'success' => true,
                'data'    => $restaurant
            ], 200);
    
        } catch (\Exception $exp) {
            return response()->json([
                'error' => $exp->getMessage(),
            ], 500);
        }
    }



    protected function createUserForNumber(string $number)
    {
        $email = 'rest' . preg_replace('/\D/', '', $number) . '@no-reply.local';
        if (User::where('email', $email)->exists()) {
            $email = 'rest' . preg_replace('/\D/', '', $number) . '+' . Str::random(4) . '@no-reply.local';
        }

        return User::create([
            'name' => 'Restaurant '.$number,
            'email' => $email,
            'password' => Hash::make('12345678'), // dummy password
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json([
            'message' => 'Logged out successfully'
        ]);
    }
}
