<?php
/**
 * Household add/edit form
 */

require_once __DIR__ . '/../../includes/audit-entities.php';

$isEdit = ($action === 'edit' && $id);
$household = null;
$errors = [];

if ($isEdit) {
    $stmt = $pdo->prepare('SELECT * FROM households WHERE id = ?');
    $stmt->execute([$id]);
    $household = $stmt->fetch();
    if (!$household) {
        header('Location: ' . BASE_PATH . '/households');
        exit;
    }
}

$members = $pdo->query('SELECT id, first_name, last_name FROM members ORDER BY last_name, first_name')->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $head_member_id = !empty($_POST['head_member_id']) ? (int)$_POST['head_member_id'] : null;
    $notes = trim($_POST['notes'] ?? '');

    if (empty($name)) $errors[] = 'Household name is required.';

    if (empty($errors)) {
        $beforeHousehold = $isEdit && !empty($household) ? $household : null;
        if ($isEdit) {
            $stmt = $pdo->prepare('UPDATE households SET name=?, address=?, head_member_id=?, notes=? WHERE id=?');
            $stmt->execute([$name, $address, $head_member_id, $notes, $id]);
            $householdId = (int) $id;
        } else {
            $stmt = $pdo->prepare('INSERT INTO households (name, address, head_member_id, notes) VALUES (?, ?, ?, ?)');
            $stmt->execute([$name, $address, $head_member_id, $notes]);
            $householdId = (int) $pdo->lastInsertId();
        }
        // Ensure the head of household is also assigned to this household so they appear in the members list
        if ($head_member_id) {
            $pdo->prepare('UPDATE members SET household_id = ? WHERE id = ?')->execute([$householdId, $head_member_id]);
        }
        $auditUid = function_exists('currentUserId') && currentUserId() ? (int) currentUserId() : null;
        nazarethTryLogHouseholdSaved($pdo, $auditUid, $householdId, $isEdit, $beforeHousehold);
        header('Location: ' . BASE_PATH . '/households?toast=' . urlencode('Household saved successfully.'));
        exit;
    }

    $household = [
        'name' => $name,
        'address' => $address,
        'head_member_id' => $head_member_id,
        'notes' => $notes,
    ];
}

$pageTitle = $isEdit ? 'Edit Household' : 'Add Household';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header">
    <h1><?= $isEdit ? 'Edit Household' : 'Add Household' ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/households">Back to Households</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div data-toast="error" data-toast-msg="<?= htmlspecialchars(implode(' ', $errors)) ?>" style="display:none"></div>
<?php endif; ?>

<div class="card">
    <form method="post">
        <div class="form-group">
            <label for="name">Household Name *</label>
            <input type="text" id="name" name="name" required
                value="<?= htmlspecialchars($household['name'] ?? '') ?>">
        </div>
        <div class="form-group form-group-head">
            <label for="head_display">Head of Household</label>
            <input type="text" id="head_display" autocomplete="off" placeholder="Type to search by name..."
                value="<?php
                if (!empty($household['head_member_id'])) {
                    foreach ($members as $m) {
                        if ((int)$m['id'] === (int)$household['head_member_id']) {
                            echo htmlspecialchars(trim($m['first_name'] . ' ' . $m['last_name']));
                            break;
                        }
                    }
                }
                ?>">
            <input type="hidden" id="head_member_id" name="head_member_id" value="<?= (int)($household['head_member_id'] ?? 0) ?>">
            <div id="head_member_list" class="head-member-list" role="listbox" aria-label="Matching members" hidden></div>
        </div>
        <div class="form-group">
            <label for="address">Address</label>
            <textarea id="address" name="address"><?= htmlspecialchars($household['address'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label for="notes">Notes</label>
            <textarea id="notes" name="notes"><?= htmlspecialchars($household['notes'] ?? '') ?></textarea>
        </div>
        <button type="submit" class="btn"><?= $isEdit ? 'Update' : 'Add' ?> Household</button>
        <a href="<?= BASE_PATH ?>/households" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<script>
(function() {
    var members = <?= json_encode(array_map(function($m) {
        return ['id' => (int)$m['id'], 'name' => trim($m['first_name'] . ' ' . $m['last_name'])];
    }, $members)) ?>;
    var input = document.getElementById('head_display');
    var hidden = document.getElementById('head_member_id');
    var list = document.getElementById('head_member_list');

    function showMatches(q) {
        q = (q || '').trim().toLowerCase();
        if (q.length < 2) {
            list.hidden = true;
            list.innerHTML = '';
            return;
        }
        var matches = members.filter(function(m) {
            return m.name.toLowerCase().indexOf(q) !== -1;
        }).slice(0, 10);
        list.innerHTML = '';
        if (matches.length === 0) {
            list.hidden = true;
            return;
        }
        matches.forEach(function(m) {
            var div = document.createElement('div');
            div.className = 'head-member-item';
            div.setAttribute('role', 'option');
            div.textContent = m.name;
            div.dataset.id = m.id;
            div.dataset.name = m.name;
            div.addEventListener('click', function() {
                hidden.value = m.id;
                input.value = m.name;
                list.hidden = true;
                list.innerHTML = '';
                input.focus();
            });
            list.appendChild(div);
        });
        list.hidden = false;
    }

    function clearSelection() {
        hidden.value = '';
    }

    input.addEventListener('input', function() {
        showMatches(input.value);
        if (!input.value.trim()) clearSelection();
    });
    input.addEventListener('focus', function() {
        showMatches(input.value);
    });
    input.addEventListener('blur', function() {
        setTimeout(function() {
            list.hidden = true;
        }, 200);
    });
    input.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            list.hidden = true;
        }
    });
})();
</script>

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