<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>سجل التعديلات — <?= e($member->full_name_ar) ?><?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>
<?php
use App\Modules\Audit\Services\AuditService;

$sections = [
    'member'  => ['label' => 'العضو الرئيسي', 'icon' => '👤', 'logs' => $memberLogs, 'color' => '#1e3a5f'],
    'spouse'  => ['label' => 'الزوجات', 'icon' => '💍', 'logs' => $spouseLogs, 'color' => '#7C3AED'],
    'child'   => ['label' => 'الأبناء', 'icon' => '👶', 'logs' => $childLogs, 'color' => '#0284C7'],
    'temp'    => ['label' => 'الأعضاء المؤقتون', 'icon' => '👥', 'logs' => $tempLogs, 'color' => '#D97706'],
];

$totalLogs = count($memberLogs) + count($spouseLogs) + count($childLogs) + count($tempLogs);
?>

<div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;">
    <a href="/members/<?= (int) $member->id ?>" class="btn btn-outline btn-sm">&larr; العودة للملف</a>
    <h2 style="margin:0;font-size:18px;color:#1F2937;">سجل التعديلات — <?= e($member->full_name_ar) ?></h2>
    <span style="background:#E5E7EB;color:#374151;padding:3px 10px;border-radius:12px;font-size:12px;font-weight:600;"><?= $totalLogs ?> تعديل</span>
</div>

<!-- Tab Navigation -->
<div style="display:flex;gap:4px;margin-bottom:20px;border-bottom:2px solid #E5E7EB;padding-bottom:0;">
<?php foreach ($sections as $key => $sec): ?>
    <button class="changelog-tab" data-tab="<?= $key ?>" style="padding:10px 20px;border:none;background:none;cursor:pointer;font-size:14px;font-weight:600;color:#6B7280;border-bottom:3px solid transparent;margin-bottom:-2px;transition:all 0.2s;" onclick="switchTab('<?= $key ?>')">
        <?= $sec['icon'] ?> <?= $sec['label'] ?> <span style="background:#F3F4F6;color:#374151;padding:1px 6px;border-radius:8px;font-size:11px;margin-right:4px;"><?= count($sec['logs']) ?></span>
    </button>
<?php endforeach; ?>
</div>

<!-- Tab Content -->
<?php foreach ($sections as $key => $sec): ?>
<div id="tab-<?= $key ?>" class="changelog-panel" style="display:none;">
<?php if (empty($sec['logs'])): ?>
    <div class="card" style="padding:40px;text-align:center;color:#9CA3AF;">
        <div style="font-size:48px;margin-bottom:10px;">📋</div>
        <p>لا توجد تعديلات مسجلة في هذا القسم</p>
    </div>
<?php else: ?>
    <div style="display:flex;flex-direction:column;gap:12px;">
    <?php foreach ($sec['logs'] as $log):
        $action = $log['action'] ?? '';
        $actionLabel = AuditService::getActionLabel($action);
        $actionColor = AuditService::getActionColor($action);
        $actionIcon = AuditService::getActionIcon($action);
        $changedFields = !empty($log['changed_fields_json']) ? json_decode($log['changed_fields_json'], true) : null;
        $beforeData = !empty($log['before_data_json']) ? json_decode($log['before_data_json'], true) : null;
        $afterData = !empty($log['after_data_json']) ? json_decode($log['after_data_json'], true) : null;
        $entityLabel = $log['entity_label'] ?? '';
    ?>
    <div class="card" style="padding:0;overflow:hidden;border-right:4px solid <?= $actionColor ?>;">
        <!-- Header -->
        <div style="padding:12px 16px;display:flex;align-items:center;justify-content:space-between;background:#F9FAFB;border-bottom:1px solid #E5E7EB;">
            <div style="display:flex;align-items:center;gap:10px;">
                <span style="font-size:18px;"><?= $actionIcon ?></span>
                <span style="font-weight:700;color:<?= $actionColor ?>;font-size:14px;"><?= e($actionLabel) ?></span>
                <?php if ($entityLabel): ?>
                <span style="color:#6B7280;font-size:12px;"> — <?= e($entityLabel) ?></span>
                <?php endif; ?>
            </div>
            <div style="display:flex;align-items:center;gap:15px;font-size:12px;color:#6B7280;">
                <?php if (!empty($log['ip_address'])): ?>
                <span title="IP Address" style="display:flex;align-items:center;gap:3px;"><i data-lucide="globe" style="width:13px;height:13px;"></i> <?= e($log['ip_address']) ?></span>
                <?php endif; ?>
                <span title="التاريخ والوقت" style="display:flex;align-items:center;gap:3px;"><i data-lucide="clock" style="width:13px;height:13px;"></i> <?= e($log['created_at']) ?></span>
                <?php if (!empty($log['employee_name'])): ?>
                <span title="بواسطة" style="display:flex;align-items:center;gap:3px;"><i data-lucide="user" style="width:13px;height:13px;"></i> <?= e($log['employee_name']) ?></span>
                <?php endif; ?>
            </div>
        </div>

        <!-- Body: Changed Fields -->
        <div style="padding:12px 16px;">
        <?php if (!empty($log['notes'])): ?>
            <div style="margin-bottom:10px;padding:8px 12px;background:#FEF3C7;border:1px solid #FCD34D;border-radius:6px;font-size:13px;color:#92400E;">
                <strong>السبب:</strong> <?= e($log['notes']) ?>
            </div>
        <?php endif; ?>

        <?php if ($action === 'create' && $afterData): ?>
            <div style="font-size:12px;color:#059669;margin-bottom:6px;font-weight:600;">تم إنشاء السجل بالبيانات التالية:</div>
            <table style="width:100%;font-size:13px;border-collapse:collapse;">
            <?php
            $displayFields = array_filter($afterData, function($v, $k) {
                return !in_array($k, ['id', 'created_at', 'updated_at', 'fee_breakdown_json', 'password_hash'], true) && $v !== null && $v !== '';
            }, ARRAY_FILTER_USE_BOTH);
            foreach ($displayFields as $field => $value): ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:4px 8px;color:#6B7280;width:30%;font-weight:500;"><?= e(AuditService::getFieldLabel($field)) ?></td>
                    <td style="padding:4px 8px;color:#059669;font-weight:600;"><?= e(AuditService::formatFieldValue($field, $value)) ?></td>
                </tr>
            <?php endforeach; ?>
            </table>

        <?php elseif ($action === 'delete' && $beforeData): ?>
            <div style="font-size:12px;color:#DC2626;margin-bottom:6px;font-weight:600;">تم حذف السجل — البيانات قبل الحذف:</div>
            <table style="width:100%;font-size:13px;border-collapse:collapse;">
            <?php
            $displayFields = array_filter($beforeData, function($v, $k) {
                return !in_array($k, ['id', 'created_at', 'updated_at', 'fee_breakdown_json', 'password_hash'], true) && $v !== null && $v !== '';
            }, ARRAY_FILTER_USE_BOTH);
            foreach ($displayFields as $field => $value): ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:4px 8px;color:#6B7280;width:30%;font-weight:500;"><?= e(AuditService::getFieldLabel($field)) ?></td>
                    <td style="padding:4px 8px;color:#DC2626;text-decoration:line-through;"><?= e(AuditService::formatFieldValue($field, $value)) ?></td>
                </tr>
            <?php endforeach; ?>
            </table>

        <?php elseif ($changedFields && is_array($changedFields)): ?>
            <table style="width:100%;font-size:13px;border-collapse:collapse;">
                <thead>
                    <tr style="background:#F9FAFB;">
                        <th style="padding:6px 8px;text-align:right;color:#6B7280;font-weight:600;width:30%;">الحقل</th>
                        <th style="padding:6px 8px;text-align:right;color:#DC2626;font-weight:600;width:35%;">قبل</th>
                        <th style="padding:6px 8px;text-align:right;color:#059669;font-weight:600;width:35%;">بعد</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($changedFields as $field => $change): ?>
                    <tr style="border-bottom:1px solid #F3F4F6;">
                        <td style="padding:5px 8px;color:#374151;font-weight:600;"><?= e(AuditService::getFieldLabel($field)) ?></td>
                        <td style="padding:5px 8px;color:#DC2626;background:#FEF2F2;border-radius:3px;">
                            <?= e(AuditService::formatFieldValue($field, $change['from'] ?? null)) ?>
                        </td>
                        <td style="padding:5px 8px;color:#059669;background:#ECFDF5;border-radius:3px;">
                            <?= e(AuditService::formatFieldValue($field, $change['to'] ?? null)) ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

        <?php else: ?>
            <span style="font-size:13px;color:#9CA3AF;">لا توجد تفاصيل إضافية</span>
        <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
<?php endif; ?>
</div>
<?php endforeach; ?>

<script>
function switchTab(tab) {
    document.querySelectorAll('.changelog-panel').forEach(function(p) { p.style.display = 'none'; });
    document.querySelectorAll('.changelog-tab').forEach(function(t) {
        t.style.color = '#6B7280';
        t.style.borderBottomColor = 'transparent';
    });
    var panel = document.getElementById('tab-' + tab);
    var btn = document.querySelector('.changelog-tab[data-tab="' + tab + '"]');
    if (panel) panel.style.display = 'block';
    if (btn) {
        btn.style.color = '#1e3a5f';
        btn.style.borderBottomColor = '#1e3a5f';
    }
}
document.addEventListener('DOMContentLoaded', function() {
    switchTab('member');
    if (typeof lucide !== 'undefined') lucide.createIcons();
});
</script>
<?php $__template->endSection(); ?>
