<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
$input = hw_input_json();
$email = hw_sanitize_string($input['email'] ?? '');
$password = (string)($input['password'] ?? '');
$roleHint = hw_sanitize_string($input['role_hint'] ?? '');
$roleHintNormalized = $roleHint ? strtolower($roleHint) : '';

if (!hw_validate_email($email)) hw_json(['success' => false, 'message' => 'Valid email is required'], 422);
if ($password === '') hw_json(['success' => false, 'message' => 'Password is required'], 422);

try {
    $pdo = hw_db();
    $stmt = $pdo->prepare('SELECT id, first_name, last_name, email, password_hash, status FROM users WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if (!$user || !hw_verify_password($password, $user['password_hash'])) {
        hw_json(['success' => false, 'message' => 'Invalid email or password'], 401);
    }

    if ($user['status'] !== 'active') {
        hw_json(['success' => false, 'message' => 'Account is not active'], 403);
    }

    // Load roles
    $stmt = $pdo->prepare('SELECT r.name FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ?');
    $stmt->execute([$user['id']]);
    $roles = array_map(fn($r) => $r['name'], $stmt->fetchAll());

    // Enforce selected role hint if provided
    if ($roleHintNormalized) {
        $allowed = ['admin', 'coach', 'client'];
        if (!in_array($roleHintNormalized, $allowed, true)) {
            hw_json(['success' => false, 'message' => 'Invalid role selection'], 400);
        }
        // Check if user has the requested role or superadmin (which can access admin)
        $hasRole = in_array($roleHintNormalized, $roles, true) || 
                   ($roleHintNormalized === 'admin' && in_array('superadmin', $roles, true));
        if (!$hasRole) {
            hw_json(['success' => false, 'message' => 'This account is not permitted for the selected role'], 403);
        }
    }

    $token = hw_jwt_encode([
        'sub' => (int)$user['id'],
        'email' => $user['email'],
        'roles' => $roles,
    ]);

    // Set HttpOnly cookie for convenience
    hw_set_auth_cookie($token);

    // Choose redirect based on role
    $redirect = 'dashboard/user/index.php';
    if ($roleHintNormalized === 'admin' && (in_array('admin', $roles, true) || in_array('superadmin', $roles, true))) {
        $redirect = 'superadmin/dashboard.php';
    } elseif ($roleHintNormalized === 'coach' && in_array('coach', $roles, true)) {
        $redirect = 'dashboard/coach/index.php';
    } elseif ($roleHintNormalized === 'client' && in_array('client', $roles, true)) {
        $redirect = 'dashboard/user/index.php';
    } else {
        if (in_array('superadmin', $roles, true) || in_array('admin', $roles, true)) $redirect = 'superadmin/dashboard.php';
        elseif (in_array('coach', $roles, true)) $redirect = 'dashboard/coach/index.php';
        else $redirect = 'dashboard/user/index.php';
    }

    hw_json([
        'success' => true,
        'message' => 'Login successful',
        'token' => $token,
        'redirect' => $redirect,
        'user' => [
            'id' => (int)$user['id'],
            'first_name' => $user['first_name'],
            'last_name' => $user['last_name'],
            'email' => $user['email'],
            'roles' => $roles,
        ]
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}
