<?php
/**
 * Household view - show household details and members in this household
 */

require_once __DIR__ . '/../../includes/auth.php';
requireAuth();
requirePermission('households.manage');

$id = isset($route_id) ? (int) $route_id : null;
if (!$id) {
    header('Location: ' . BASE_PATH . '/households');
    exit;
}

$stmt = $pdo->prepare('SELECT h.*, (SELECT CONCAT(first_name, " ", last_name) FROM members WHERE id = h.head_member_id) AS head_name FROM households h WHERE h.id = ?');
$stmt->execute([$id]);
$household = $stmt->fetch();

if (!$household) {
    header('Location: ' . BASE_PATH . '/households');
    exit;
}

// Include all members assigned to this household, plus the head if set (so head always appears in the list)
$headId = isset($household['head_member_id']) && (int)$household['head_member_id'] > 0 ? (int)$household['head_member_id'] : null;
$members = $pdo->prepare('
    SELECT id, first_name, last_name, gender, date_of_birth, phone, status, household_id
    FROM members
    WHERE household_id = ? OR (id = ? AND ? IS NOT NULL)
    ORDER BY (id = ?) DESC, last_name, first_name
');
$members->execute([$id, $headId, $headId, $headId]);
$members = $members->fetchAll();

$headNotInHousehold = $headId && $household['head_name'];
if ($headNotInHousehold) {
    $headRow = null;
    foreach ($members as $m) {
        if ((int)$m['id'] === $headId) {
            $headRow = $m;
            break;
        }
    }
    $headNotInHousehold = $headRow && (int)($headRow['household_id'] ?? 0) !== (int)$id;
}

$pageTitle = $household['name'] . ' - Household';
$currentPage = 'households';

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header">
    <h1><?= htmlspecialchars($household['name']) ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/households/edit/<?= (int) $household['id'] ?>" class="btn">Edit household</a>
        <a href="<?= BASE_PATH ?>/households" class="btn btn-secondary">← Households</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<div class="card" style="margin-bottom: 1.5rem;">
    <div class="card-body">
    <h2 style="margin-top: 0; font-size: 1rem;">Household details</h2>
    <dl class="dl-inline">
        <dt>Head of household</dt>
        <dd><?= htmlspecialchars($household['head_name'] ?? '—') ?></dd>
        <dt>Address</dt>
        <dd><?= nl2br(htmlspecialchars($household['address'] ?? '—')) ?></dd>
        <?php if (!empty(trim($household['notes'] ?? ''))): ?>
        <dt>Notes</dt>
        <dd><?= nl2br(htmlspecialchars($household['notes'])) ?></dd>
        <?php endif; ?>
    </dl>
    </div>
</div>

<div class="card">
    <h2 style="margin-top: 0; font-size: 1rem;">Members in this household (<?= count($members) ?>)</h2>
    <?php if ($headNotInHousehold): ?>
    <p class="alert" style="background: #fef3c7; border-left: 4px solid #f59e0b; padding: 0.75rem 1rem; margin-bottom: 1rem; border-radius: 4px; font-size: 0.875rem;">
        <strong>Heads of household should be members.</strong> <?= htmlspecialchars($household['head_name']) ?> is set as head but is not assigned to this household. <a href="<?= BASE_PATH ?>/members/edit/<?= (int)$headId ?>">Edit this member</a> and set their household to &ldquo;<?= htmlspecialchars($household['name']) ?>&rdquo; so the listing is correct.
    </p>
    <?php endif; ?>
    <?php if (empty($members)): ?>
    <p>No members assigned to this household. <a href="<?= BASE_PATH ?>/members/add">Add a member</a> and set their household to &ldquo;<?= htmlspecialchars($household['name']) ?>&rdquo;.</p>
    <?php else: ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Gender</th>
                    <th>Date of birth</th>
                    <th>Phone</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($members as $m):
                    $fullName = trim(($m['first_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
                    if ($fullName === '') $fullName = 'Member #' . (int) $m['id'];
                    $isHead = isset($household['head_member_id']) && (int) $household['head_member_id'] === (int) $m['id'];
                ?>
                <tr>
                    <td><?= htmlspecialchars($fullName) ?><?= $isHead ? ' <span class="badge">Head</span>' : '' ?></td>
                    <td><?= htmlspecialchars($m['gender'] ?? '—') ?></td>
                    <td><?= !empty($m['date_of_birth']) ? date('M j, Y', strtotime($m['date_of_birth'])) : '—' ?></td>
                    <td><?= htmlspecialchars($m['phone'] ?? '—') ?></td>
                    <td><?= htmlspecialchars($m['status'] ?? '—') ?></td>
                    <td class="actions">
                        <a href="<?= BASE_PATH ?>/members/view/<?= (int) $m['id'] ?>">View</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
    </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
