<?php
declare(strict_types=1);

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    api_json([
        'success' => false,
        'message' => 'Method not allowed.'
    ], 405);
}

$familySlug = trim((string)($_POST['family_slug'] ?? ''));
$username = trim((string)($_POST['username'] ?? ''));
$pin = trim((string)($_POST['pin'] ?? ''));

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

$stmt = db()->prepare("
    SELECT 
        c.id,
        c.family_id,
        c.name,
        c.username,
        c.pin_hash,
        c.is_active,
        f.family_name,
        f.family_slug
    FROM caregiver_accounts c
    INNER JOIN families f ON f.id = c.family_id
    WHERE f.family_slug = ?
      AND c.username = ?
    LIMIT 1
");
$stmt->execute([$familySlug, $username]);
$caregiver = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$caregiver || (int)$caregiver['is_active'] !== 1) {
    api_json([
        'success' => false,
        'message' => 'Invalid caregiver username or PIN.'
    ], 401);
}

if (!password_verify($pin, (string)$caregiver['pin_hash'])) {
    api_json([
        'success' => false,
        'message' => 'Invalid caregiver username or PIN.'
    ], 401);
}

$token = bin2hex(random_bytes(32));
$expiresAt = date('Y-m-d H:i:s', time() + (defined('SESSION_TTL_SECONDS') ? SESSION_TTL_SECONDS : 2592000));

$insert = db()->prepare("
    INSERT INTO app_sessions (user_type, user_id, family_id, session_token, expires_at, created_at, last_seen_at)
    VALUES ('caregiver', ?, ?, ?, ?, NOW(), NOW())
");
$insert->execute([
    (int)$caregiver['id'],
    (int)$caregiver['family_id'],
    $token,
    $expiresAt
]);

$update = db()->prepare("UPDATE caregiver_accounts SET last_login_at = NOW() WHERE id = ?");
$update->execute([(int)$caregiver['id']]);

$_SESSION['caregiver_session_token'] = $token;

api_json([
    'success' => true,
    'message' => 'Login successful.',
    'caregiver' => [
        'id' => (int)$caregiver['id'],
        'name' => $caregiver['name'],
        'username' => $caregiver['username']
    ],
    'family' => [
        'id' => (int)$caregiver['family_id'],
        'family_name' => $caregiver['family_name'],
        'family_slug' => $caregiver['family_slug']
    ]
]);