<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Supplier;
use App\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{
    public function registerSupplier(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'company_name' => 'required|string|max:255',
            'registration_number' => 'nullable|string|max:100',
            'vat_number' => 'nullable|string|max:50',
            'contact_name' => 'nullable|string|max:255',
            'contact_phone' => 'nullable|string|max:50',
            'contact_email' => 'nullable|email|max:255',
            'address' => 'nullable|string',
            'city' => 'nullable|string|max:100',
            'province' => 'nullable|string|max:100',
            'postal_code' => 'nullable|string|max:20',
            'description' => 'nullable|string',
            'delivery_self' => 'boolean',
            'delivery_platform' => 'boolean',
            'delivery_collection' => 'boolean',
        ]);

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

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'user_type' => 'supplier',
        ]);

        $supplier = Supplier::create([
            'user_id' => $user->id,
            'company_name' => $request->company_name,
            'registration_number' => $request->registration_number,
            'vat_number' => $request->vat_number,
            'contact_name' => $request->contact_name ?? $request->name,
            'contact_phone' => $request->contact_phone,
            'contact_email' => $request->contact_email ?? $request->email,
            'address' => $request->address,
            'city' => $request->city,
            'province' => $request->province,
            'postal_code' => $request->postal_code,
            'description' => $request->description,
            'delivery_self' => $request->delivery_self ?? true,
            'delivery_platform' => $request->delivery_platform ?? false,
            'delivery_collection' => $request->delivery_collection ?? true,
        ]);

        $token = JWTAuth::fromUser($user);

        return response()->json([
            'message' => 'Supplier registered successfully',
            'user' => $user,
            'supplier' => $supplier,
            'token' => $token,
            'token_type' => 'bearer',
        ], 201);
    }

    public function registerCompany(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'company_name' => 'required|string|max:255',
            'registration_number' => 'nullable|string|max:100',
            'vat_number' => 'nullable|string|max:50',
            'contact_name' => 'nullable|string|max:255',
            'contact_phone' => 'nullable|string|max:50',
            'contact_email' => 'nullable|email|max:255',
            'billing_address' => 'nullable|string',
            'delivery_address' => 'nullable|string',
            'city' => 'nullable|string|max:100',
            'province' => 'nullable|string|max:100',
            'postal_code' => 'nullable|string|max:20',
        ]);

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

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'user_type' => 'company',
        ]);

        $company = Company::create([
            'user_id' => $user->id,
            'company_name' => $request->company_name,
            'registration_number' => $request->registration_number,
            'vat_number' => $request->vat_number,
            'contact_name' => $request->contact_name ?? $request->name,
            'contact_phone' => $request->contact_phone,
            'contact_email' => $request->contact_email ?? $request->email,
            'billing_address' => $request->billing_address,
            'delivery_address' => $request->delivery_address ?? $request->billing_address,
            'city' => $request->city,
            'province' => $request->province,
            'postal_code' => $request->postal_code,
        ]);

        $token = JWTAuth::fromUser($user);

        return response()->json([
            'message' => 'Company registered successfully',
            'user' => $user,
            'company' => $company,
            'token' => $token,
            'token_type' => 'bearer',
        ], 201);
    }

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

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

        $credentials = $request->only('email', 'password');

        if (!$token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'Invalid credentials'], 401);
        }

        $user = auth()->user();

        if (!$user->is_active) {
            return response()->json(['error' => 'Account is disabled'], 403);
        }

        $profile = null;
        if ($user->isSupplier()) {
            $profile = $user->supplier;
        } elseif ($user->isCompany()) {
            $profile = $user->company;
        }

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

    public function logout()
    {
        JWTAuth::invalidate(JWTAuth::getToken());
        return response()->json(['message' => 'Successfully logged out']);
    }

    public function me()
    {
        $user = auth()->user();
        $profile = null;

        if ($user->isSupplier()) {
            $profile = $user->supplier;
        } elseif ($user->isCompany()) {
            $profile = $user->company;
        }

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

    public function refresh()
    {
        return response()->json([
            'token' => JWTAuth::refresh(JWTAuth::getToken()),
            'token_type' => 'bearer',
        ]);
    }
}
