<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/common.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['success' => false, 'message' => 'POST required'], 405);
}

$payload = json_decode((string) file_get_contents('php://input'), true) ?: $_POST;
$familySlug = strtolower(trim((string) ($payload['family_slug'] ?? '')));
$username = trim((string) ($payload['username'] ?? ''));
$password = (string) ($payload['password'] ?? '');

if ($familySlug === '' || $username === '' || $password === '') {
    json_response(['success' => false, 'message' => 'Family slug, username, and password are required.'], 422);
}

$stmt = db()->prepare(
    'SELECT fa.id, fa.family_id, fa.full_name, fa.password_hash, f.family_name, f.family_slug, f.status
     FROM family_admins fa
     INNER JOIN families f ON f.id = fa.family_id
     WHERE f.family_slug = :family_slug
       AND fa.username = :username
       AND fa.is_active = 1
     LIMIT 1'
);
$stmt->execute([
    ':family_slug' => $familySlug,
    ':username' => $username,
]);
$admin = $stmt->fetch();

if (!$admin || $admin['status'] !== 'active' || !password_verify($password, $admin['password_hash'])) {
    json_response(['success' => false, 'message' => 'Invalid login.'], 401);
}

$token = bin2hex(random_bytes(32));
$expiresAt = (new DateTimeImmutable('now +' . SESSION_TTL_SECONDS . ' seconds'))->format('Y-m-d H:i:s');

$insert = db()->prepare(
    'INSERT INTO app_sessions (user_type, user_id, family_id, session_token, expires_at) VALUES ("family_admin", :user_id, :family_id, :token, :expires_at)'
);
$insert->execute([
    ':user_id' => $admin['id'],
    ':family_id' => $admin['family_id'],
    ':token' => $token,
    ':expires_at' => $expiresAt,
]);

setcookie(FAMILY_LOGIN_SESSION_COOKIE, $token, [
    'expires' => strtotime($expiresAt),
    'path' => '/',
    'httponly' => true,
    'samesite' => 'Lax',
]);

db()->prepare('UPDATE family_admins SET last_login_at = NOW() WHERE id = :id')->execute([':id' => $admin['id']]);

json_response([
    'success' => true,
    'message' => 'Login successful.',
    'family' => [
        'id' => (int) $admin['family_id'],
        'name' => $admin['family_name'],
        'slug' => $admin['family_slug'],
    ],
    'admin' => [
        'id' => (int) $admin['id'],
        'full_name' => $admin['full_name'],
    ],
]);
