<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;

class ApiController extends Controller {

    public function __construct() {
        $this->middleware('guest');
    }

    public function login(Request $request) {
        try {
            $credentials = $request->validate([
                'email' => ['required', 'email', 'max:255'],
                'password' => ['required', 'max:255']
            ]);

            if (Auth::attempt($credentials)) {
                $request->session->regenerate();

                return response()->json([
                    'session_id' => session()->getId()
                ], 200)
                    ->header('Content-Type', 'application/json');
            } else {
                return response->json([
                    'error' => 'Failed to authenticate'
                ], 400)
                    ->header('Content-Type', 'application/json');
            }
        } catch (Exception $e) {
            return response->json([
                'error' => $e->getMessage()
            ], 500)
                ->header('Content-Type', 'application/json');
        }
    }

    public function register(Request $request) {
        try {
            $credentials = $request->validate([
                'username' => ['required', 'string', 'max:255'],
                'club_name' => ['required', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'phone_number' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|size:10',
                'date_of_birth' => 'nullable|date_format:Y-m-d|before:today',
                'password' => ['required', 'string', 'min:8', 'confirmed'],
                'first_name' => ['required', 'string', 'max:255'],
                'last_name' => ['required', 'string', 'max:255']
            ]);

            $user = User::create([
                'username' => $credentials['username'],
                'email' => $credentials['email'],
                'phone_number' => $credentials['phone_number'],
                'date_of_birth' => $credentials['date_of_birth'],
                'password' => Hash::make($credentials['password']),
                'first_name' => $credentials['first_name'],
                'last_name' => $credentials['last_name'],
            ]);

            $request->session->regenerate();

            return response()->json([
                'session_id' => session()->getId()
            ], 201)
                ->header('Content-Type', 'application/json');
        } catch (Exception $e) {
            return response->json([
                'error' => $e->getMessage()
            ], 500)
                ->header('Content-Type', 'application/json');
        }
    }
}
