<?php

namespace App\Http\Controllers\Api;

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

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);

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

        $user = User::with('restaurant')->where('email', $request->email)->first();
        if (! $user || ! Hash::check($request->password, $user->password)) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }

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

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

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

    public function getCustomer($restaurant_id)
    {
        $customer= Restaurant::with('customer')->find($restaurant_id);
        if($customer){
            if($customer->customer){
                return response()->json(['customer' => $customer->customer], 200);
            } else {
                return response()->json(['customer' => "Customer Not Found"], 404);
            }
        } else {
            return response()->json(['error' => "Restaurant Not Found"], 404);
        }
    }
}
