<?php
$__template->layout('Layout.main');
use App\Modules\Audit\Services\AuditService;
?>
<?php $__template->section('title'); ?>سجل <?= e(AuditService::getEntityTypeLabel($entityType)) ?><?php if ($entityLabel): ?> — <?= e($entityLabel) ?><?php else: ?> #<?= $entityId ?><?php endif; ?><?php $__template->endSection(); ?>
<?php $__template->section('page_actions'); ?>
<a href="/audit" class="btn btn-sm btn-outline">العودة لسجل المراجعة</a>
<?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>

<div class="card" style="margin-bottom:20px;padding:16px 20px;">
    <div style="display:flex;align-items:center;gap:12px;">
        <div style="width:40px;height:40px;border-radius:50%;background:#0D7377;display:flex;align-items:center;justify-content:center;color:#fff;font-size:18px;flex-shrink:0;">
            <?= e(mb_substr(AuditService::getEntityTypeLabel($entityType), 0, 1)) ?>
        </div>
        <div>
            <div style="font-size:18px;font-weight:700;color:#1A1A2E;"><?= e(AuditService::getEntityTypeLabel($entityType)) ?><?php if ($entityLabel): ?> — <?= e($entityLabel) ?><?php endif; ?></div>
            <div style="font-size:13px;color:#6B7280;">الجدول: <?= e($entityType) ?> | الرقم: #<?= $entityId ?> | عدد السجلات: <?= count($history) ?></div>
        </div>
    </div>
</div>

<?php if (empty($history)): ?>
    <div class="card" style="padding:60px;text-align:center;color:#6B7280;font-size:16px;">لا يوجد سجل لهذا الكيان</div>
<?php else: ?>

<div style="position:relative;padding-right:30px;">
    <div style="position:absolute;right:14px;top:0;bottom:0;width:3px;background:linear-gradient(to bottom,#0D7377,#E5E7EB);border-radius:2px;"></div>

    <?php foreach ($history as $i => $entry):
        $action = $entry['action'] ?? '';
        $color = AuditService::getActionColor($action);
        $icon = AuditService::getActionIcon($action);
        $actionLabel = AuditService::getActionLabel($action);

        $changedFields = null;
        if (!empty($entry['changed_fields_json'])) {
            $changedFields = json_decode($entry['changed_fields_json'], true);
        }
        $afterData = null;
        if (!empty($entry['after_data_json'])) {
            $afterData = json_decode($entry['after_data_json'], true);
        }
        $beforeData = null;
        if (!empty($entry['before_data_json'])) {
            $beforeData = json_decode($entry['before_data_json'], true);
        }

        $ts = strtotime($entry['created_at']);
        $diff = time() - $ts;
        if ($diff < 60) $timeAgo = 'الآن';
        elseif ($diff < 3600) $timeAgo = (int)($diff / 60) . ' دقيقة';
        elseif ($diff < 86400) $timeAgo = (int)($diff / 3600) . ' ساعة';
        elseif ($diff < 604800) $timeAgo = (int)($diff / 86400) . ' يوم';
        else $timeAgo = date('Y/m/d', $ts);
    ?>
    <div style="position:relative;margin-bottom:16px;">
        <div style="position:absolute;right:-30px;top:12px;width:28px;height:28px;border-radius:50%;background:<?= $color ?>;display:flex;align-items:center;justify-content:center;font-size:14px;z-index:1;box-shadow:0 0 0 3px #fff;"><?= $icon ?></div>

        <div class="card" style="border-right:4px solid <?= $color ?>;overflow:hidden;">
            <div style="padding:12px 16px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;cursor:pointer;" onclick="toggleHistoryDetail(<?= $i ?>)">
                <div style="flex:1;min-width:200px;">
                    <span style="color:<?= $color ?>;font-weight:700;font-size:14px;"><?= e($actionLabel) ?></span>
                    <span style="color:#9CA3AF;font-size:12px;margin-right:8px;">بواسطة <?= e($entry['employee_name'] ?? 'النظام') ?></span>
                    <?php if ($action === 'update' && is_array($changedFields) && !empty($changedFields)): ?>
                        <span style="background:#E0F2FE;color:#0284C7;padding:1px 8px;border-radius:10px;font-size:11px;"><?= count($changedFields) ?> تغيير</span>
                    <?php elseif ($action === 'create' && is_array($afterData)): ?>
                        <span style="background:#D1FAE5;color:#059669;padding:1px 8px;border-radius:10px;font-size:11px;"><?= count($afterData) ?> حقل</span>
                    <?php endif; ?>
                </div>

                <div style="min-width:200px;max-width:350px;font-size:12px;">
                    <?php if ($action === 'update' && is_array($changedFields) && !empty($changedFields)): ?>
                        <?php $first = array_slice($changedFields, 0, 1, true); ?>
                        <?php foreach ($first as $fname => $fchange): ?>
                            <?php if (is_array($fchange) && isset($fchange['from'])): ?>
                            <span style="color:#374151;font-weight:600;"><?= e(AuditService::getFieldLabel($fname)) ?>:</span>
                            <span style="color:#DC2626;text-decoration:line-through;"><?= e(mb_substr(AuditService::formatFieldValue($fname, $fchange['from']), 0, 20)) ?></span>
                            <span style="color:#9CA3AF;">←</span>
                            <span style="color:#059669;"><?= e(mb_substr(AuditService::formatFieldValue($fname, $fchange['to']), 0, 20)) ?></span>
                            <?php if (count($changedFields) > 1): ?>
                                <span style="color:#9CA3AF;font-size:11px;">+<?= count($changedFields) - 1 ?></span>
                            <?php endif; ?>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <div style="flex-shrink:0;text-align:left;">
                    <div style="font-size:12px;color:#9CA3AF;" title="<?= e($entry['created_at']) ?>"><?= $timeAgo ?></div>
                    <a href="/audit/<?= (int) $entry['id'] ?>" onclick="event.stopPropagation();" style="font-size:11px;color:#0D7377;">تفاصيل</a>
                </div>
            </div>

            <div id="history-detail-<?= $i ?>" style="display:none;border-top:1px solid #E5E7EB;padding:16px;background:#FAFBFC;">
                <?php if ($action === 'create' && is_array($afterData) && !empty($afterData)): ?>
                    <div style="margin-bottom:8px;font-weight:700;color:#059669;font-size:13px;">البيانات المنشأة:</div>
                    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:6px;">
                    <?php foreach ($afterData as $fk => $fv):
                        if (in_array($fk, ['id', 'created_at', 'updated_at'], true) || $fv === null || $fv === '') continue;
                    ?>
                        <div style="background:#F0FDF4;border:1px solid #BBF7D0;border-radius:6px;padding:5px 10px;font-size:12px;">
                            <span style="color:#374151;font-weight:600;"><?= e(AuditService::getFieldLabel($fk)) ?>:</span>
                            <span style="color:#065F46;"><?= e(AuditService::formatFieldValue($fk, $fv)) ?></span>
                        </div>
                    <?php endforeach; ?>
                    </div>

                <?php elseif ($action === 'update' && is_array($changedFields) && !empty($changedFields)): ?>
                    <div style="margin-bottom:8px;font-weight:700;color:#0284C7;font-size:13px;">التغييرات:</div>
                    <table style="width:100%;font-size:12px;border:1px solid #E5E7EB;border-radius:6px;border-collapse:collapse;">
                        <thead>
                            <tr style="background:#F0F9FF;">
                                <th style="padding:8px 12px;text-align:right;border-bottom:1px solid #BAE6FD;width:25%;">الحقل</th>
                                <th style="padding:8px 12px;text-align:right;border-bottom:1px solid #BAE6FD;width:37%;">قبل</th>
                                <th style="padding:8px 12px;text-align:right;border-bottom:1px solid #BAE6FD;width:37%;">بعد</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($changedFields as $fname => $fchange): ?>
                            <?php if (!is_array($fchange) || !isset($fchange['from'])) continue; ?>
                            <tr>
                                <td style="padding:6px 12px;font-weight:600;color:#374151;border-bottom:1px solid #F3F4F6;"><?= e(AuditService::getFieldLabel($fname)) ?></td>
                                <td style="padding:6px 12px;color:#DC2626;background:#FEF2F2;border-bottom:1px solid #F3F4F6;"><?= e(AuditService::formatFieldValue($fname, $fchange['from'])) ?></td>
                                <td style="padding:6px 12px;color:#059669;background:#F0FDF4;border-bottom:1px solid #F3F4F6;"><?= e(AuditService::formatFieldValue($fname, $fchange['to'])) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>

                <?php elseif ($action === 'delete' && is_array($beforeData) && !empty($beforeData)): ?>
                    <div style="margin-bottom:8px;font-weight:700;color:#DC2626;font-size:13px;">البيانات المحذوفة:</div>
                    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:6px;">
                    <?php foreach ($beforeData as $fk => $fv):
                        if ($fv === null || $fv === '') continue;
                    ?>
                        <div style="background:#FEF2F2;border:1px solid #FECACA;border-radius:6px;padding:5px 10px;font-size:12px;">
                            <span style="color:#374151;font-weight:600;"><?= e(AuditService::getFieldLabel($fk)) ?>:</span>
                            <span style="color:#991B1B;"><?= e(AuditService::formatFieldValue($fk, $fv)) ?></span>
                        </div>
                    <?php endforeach; ?>
                    </div>

                <?php elseif ($action === 'archive' && is_array($beforeData) && !empty($beforeData)): ?>
                    <div style="margin-bottom:8px;font-weight:700;color:#D97706;font-size:13px;">البيانات المؤرشفة:</div>
                    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:6px;">
                    <?php foreach ($beforeData as $fk => $fv):
                        if ($fv === null || $fv === '') continue;
                    ?>
                        <div style="background:#FFFBEB;border:1px solid #FDE68A;border-radius:6px;padding:5px 10px;font-size:12px;">
                            <span style="color:#374151;font-weight:600;"><?= e(AuditService::getFieldLabel($fk)) ?>:</span>
                            <span style="color:#92400E;"><?= e(AuditService::formatFieldValue($fk, $fv)) ?></span>
                        </div>
                    <?php endforeach; ?>
                    </div>

                <?php elseif ($entry['notes']): ?>
                    <div style="color:#4B5563;font-size:13px;"><?= e($entry['notes']) ?></div>
                <?php else: ?>
                    <div style="color:#9CA3AF;font-size:13px;">لا توجد تفاصيل إضافية</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php endif; ?>

<script>
function toggleHistoryDetail(idx) {
    var el = document.getElementById('history-detail-' + idx);
    if (!el) return;
    el.style.display = el.style.display === 'none' ? 'block' : 'none';
}
</script>

<style>
.card { transition: box-shadow 0.15s ease; }
.card:hover { box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
</style>

<?php $__template->endSection(); ?>
