<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Jobseeker;
use App\Models\Company;
use Illuminate\Support\Facades\DB;
use Hash;
use Auth;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'full_name' => 'required_if:user_type,jobseeker',
            'company_name' => 'required_if:user_type,company',
            'phone' => 'nullable',
            'location' => 'nullable',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
            'user_type' => 'required|in:jobseeker,company'
        ]);

        DB::beginTransaction();

        try {

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

            // 🔥 AUTO CREATE PROFILE
            if ($user->user_type === 'jobseeker') {

                Jobseeker::create([
                    'user_id' => $user->id,
                    'full_name' => $request->full_name ?? '',
                    'phone' => $request->phone ?? '',
                    'city' => $request->location ?? ''
                ]);

            } elseif ($user->user_type === 'company') {

                Company::create([
                    'user_id' => $user->id,
                    'email' => $request->email,
                    'phone' => $request->phone ?? '',
                    'company_name' => $request->company_name ?? '',
                ]);
            }

            DB::commit();

            return response()->json($user, 201);

        } catch (\Exception $e) {
            DB::rollBack();

            return response()->json([
                'message' => 'Register failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function login(Request $request)
    {
        if (!Auth::attempt($request->only('email','password'))) {
            return response()->json(['message'=>'Invalid credentials'],401);
        }

        $user = Auth::user();
        $token = $user->createToken('api')->plainTextToken;

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

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