<?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',
            '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,
                'color_code'  => $request->color_code,
                '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);
        }
    }


    public function getRestaurantDetail($id)
    {
        $restaurant= Restaurant::find($id);
        if($restaurant){
            return response()->json([ 'restaurant' => $restaurant ], 200);
        } else {
            return response()->json([ 'restaurant' => 'Not Found' ], 404);
        }
    }



    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 updateRestaurant(Request $request, $id)
    // {
    //     $validated = $request->validate([
    //         'name'       => 'required|string|max:255',
    //         'r_number'   => 'required|numeric',
    //         'color_code' => 'required|string|size:7', // e.g., #ffffff
    //         'image'      => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    //     ]);

    //     $restaurant = Restaurant::find($id);
    //     if (!$restaurant) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Restaurant not found'
    //         ], 404);
    //     }

    //     $restaurant->name = $validated['name'];
    //     $restaurant->r_number = $validated['r_number'];
    //     $restaurant->color_code = $validated['color_code'];

    //     // Optional image upload
    //     if ($request->hasFile('image')) {
    //         $file = $request->file('image');
    //         $filename = time().'_'.$file->getClientOriginalName();
    //         $file->move(public_path('uploads/restaurants'), $filename);
    //         $restaurant->image = $filename;
    //     }

    //     $restaurant->save();

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


    public function updateRestaurant(Request $request, $id)
    {
        $validated = $request->validate([
            'name'       => 'required|string|max:255',
            'r_number'   => 'required|numeric',
            'color_code' => 'required|string|size:7',
            'image'      => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
        ]);

        $restaurant = Restaurant::find($id);
        if (!$restaurant) {
            return response()->json([
                'success' => false,
                'message' => 'Restaurant not found'
            ], 404);
        }

        $restaurant->name = $validated['name'];
        $restaurant->r_number = $validated['r_number'];
        $restaurant->color_code = $validated['color_code'];

        // Optional image upload
        if ($request->hasFile('image')) {
            // Delete old image if exists
            if ($restaurant->image && file_exists(public_path('uploads/restaurants/' . $restaurant->image))) {
                unlink(public_path('uploads/restaurants/' . $restaurant->image));
            }

            // Save new image
            $file = $request->file('image');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/restaurants'), $filename);
            $restaurant->image = $filename;
        }

        $restaurant->save();

        return response()->json([
            'success' => true,
            'data' => $restaurant->fresh() // fresh ensures latest values including new image
        ]);
    }



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