<?php
/**
 * Permanently delete a member and clean up related rows (admin only).
 */

require_once __DIR__ . '/audit.php';

/**
 * @return array{ok: bool, error: ?string, name: string, warnings: string[]}
 */
function nazarethDeleteMember(PDO $pdo, int $memberId): array
{
    $stmt = $pdo->prepare('SELECT id, title, first_name, middle_name, last_name, photo FROM members WHERE id = ?');
    $stmt->execute([$memberId]);
    $member = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$member) {
        return ['ok' => false, 'error' => 'Member not found.', 'name' => '', 'warnings' => []];
    }

    $name = trim(
        ($member['title'] ?? '') . ' '
        . ($member['first_name'] ?? '') . ' '
        . ($member['middle_name'] ?? '') . ' '
        . ($member['last_name'] ?? '')
    );
    if ($name === '') {
        $name = 'Member #' . $memberId;
    }

    $warnings = [];

    try {
        $pdo->beginTransaction();

        $pdo->prepare('UPDATE households SET head_member_id = NULL WHERE head_member_id = ?')->execute([$memberId]);

        $cleanupDeletes = [
            'event_attendance' => 'DELETE FROM event_attendance WHERE member_id = ?',
            'group_members' => 'DELETE FROM group_members WHERE member_id = ?',
            'executives' => 'DELETE FROM executives WHERE member_id = ?',
        ];
        foreach ($cleanupDeletes as $table => $sql) {
            try {
                $pdo->prepare($sql)->execute([$memberId]);
            } catch (Throwable $e) {
                if (strpos($e->getMessage(), 'exist') === false && strpos($e->getMessage(), '1146') === false) {
                    throw $e;
                }
            }
        }

        try {
            $txStmt = $pdo->prepare('SELECT COUNT(*) FROM transactions WHERE member_id = ?');
            $txStmt->execute([$memberId]);
            $txCount = (int) $txStmt->fetchColumn();
            if ($txCount > 0) {
                $pdo->prepare('UPDATE transactions SET member_id = NULL WHERE member_id = ?')->execute([$memberId]);
                $warnings[] = $txCount . ' finance record(s) kept but unlinked from this member.';
            }
        } catch (Throwable $e) {
            if (strpos($e->getMessage(), 'exist') === false && strpos($e->getMessage(), '1146') === false) {
                throw $e;
            }
        }

        try {
            $pdo->prepare('UPDATE receipts SET member_id = NULL WHERE member_id = ?')->execute([$memberId]);
        } catch (Throwable $e) {
            // receipts table optional on some installs
        }

        $pdo->prepare('DELETE FROM members WHERE id = ?')->execute([$memberId]);

        $pdo->commit();
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        return ['ok' => false, 'error' => $e->getMessage(), 'name' => $name, 'warnings' => []];
    }

    $uploadDir = dirname(__DIR__) . '/public/uploads/members';
    if (!empty($member['photo'])) {
        $path = $uploadDir . '/' . $member['photo'];
        if (is_file($path)) {
            @unlink($path);
        }
    }

    $uid = function_exists('currentUserId') ? currentUserId() : null;
    logActivity(
        'member_deleted',
        'Deleted member: ' . $name,
        ['member_id' => $memberId, 'warnings' => $warnings],
        $uid
    );

    return ['ok' => true, 'error' => null, 'name' => $name, 'warnings' => $warnings];
}

/**
 * Whether the current user may permanently delete members.
 */
function canDeleteMembers(): bool
{
    return function_exists('isAdmin') && isAdmin();
}
