<?php
declare(strict_types=1);

namespace App\Modules\Death\Services;

use App\Core\App;

final class DeathAuditService
{
    public static function log(
        int $deathCaseId,
        string $actionType,
        string $descriptionAr,
        ?string $entityType = null,
        ?int $entityId = null,
        ?array $details = null
    ): void {
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();

        $db->insert('death_case_audit_log', [
            'death_case_id'        => $deathCaseId,
            'action_type'          => $actionType,
            'action_description_ar'=> $descriptionAr,
            'affected_entity_type' => $entityType,
            'affected_entity_id'   => $entityId,
            'performed_by'         => $employee ? (int) $employee->id : null,
            'performed_at'         => date('Y-m-d H:i:s'),
            'details_json'         => $details ? json_encode($details, JSON_UNESCAPED_UNICODE) : null,
        ]);
    }

    public static function getForCase(int $deathCaseId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT dal.*, e.full_name_ar as performer_name
             FROM death_case_audit_log dal
             LEFT JOIN employees e ON e.id = dal.performed_by
             WHERE dal.death_case_id = ?
             ORDER BY dal.performed_at ASC, dal.id ASC",
            [$deathCaseId]
        );
    }

    public static function getForMember(int $memberId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT dal.*, e.full_name_ar as performer_name, dc.deceased_type, dc.death_date,
                    m.full_name_ar as deceased_member_name
             FROM death_case_audit_log dal
             JOIN death_cases dc ON dc.id = dal.death_case_id
             JOIN members m ON m.id = dc.member_id
             LEFT JOIN employees e ON e.id = dal.performed_by
             WHERE dc.member_id = ? OR dc.transferred_to_member_id = ?
             ORDER BY dal.performed_at ASC, dal.id ASC",
            [$memberId, $memberId]
        );
    }

    public static function getCasesForMember(int $memberId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT dc.*, m.full_name_ar as member_name
             FROM death_cases dc
             JOIN members m ON m.id = dc.member_id
             WHERE dc.member_id = ? OR dc.transferred_to_member_id = ?
             ORDER BY dc.created_at DESC",
            [$memberId, $memberId]
        );
    }
}
