<?php
$__template->layout('Layout.main');
use App\Modules\Audit\Services\AuditService;
?>
<?php $__template->section('title'); ?>سجل المراجعة<?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>

<div class="card" style="margin-bottom:20px;padding:15px;">
    <form method="GET" action="/audit" style="display:flex;gap:10px;flex-wrap:wrap;align-items:end;">
        <div>
            <label class="form-label" style="font-size:12px;">بحث</label>
            <input type="text" name="q" value="<?= e($filters['search']) ?>" placeholder="بحث في السجلات..." class="form-input" style="min-width:180px;">
        </div>
        <div>
            <label class="form-label" style="font-size:12px;">الإجراء</label>
            <select name="action" class="form-select" style="min-width:130px;">
                <option value="">الكل</option>
                <?php foreach ($actions as $a): ?>
                    <option value="<?= e($a) ?>" <?= $filters['action'] === $a ? 'selected' : '' ?>><?= e(AuditService::getActionLabel($a)) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label class="form-label" style="font-size:12px;">نوع الكيان</label>
            <select name="entity_type" class="form-select" style="min-width:130px;">
                <option value="">الكل</option>
                <?php foreach ($entityTypes as $et): ?>
                    <option value="<?= e($et) ?>" <?= $filters['entity_type'] === $et ? 'selected' : '' ?>><?= e(AuditService::getEntityTypeLabel($et)) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label class="form-label" style="font-size:12px;">الموظف</label>
            <select name="employee_id" class="form-select" style="min-width:160px;">
                <option value="">الكل</option>
                <?php foreach ($employees as $emp): ?>
                    <option value="<?= (int) $emp['id'] ?>" <?= $filters['employee_id'] == $emp['id'] ? 'selected' : '' ?>><?= e($emp['full_name_ar']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label class="form-label" style="font-size:12px;">من</label>
            <input type="date" name="date_from" value="<?= e($filters['date_from']) ?>" class="form-input">
        </div>
        <div>
            <label class="form-label" style="font-size:12px;">إلى</label>
            <input type="date" name="date_to" value="<?= e($filters['date_to']) ?>" class="form-input">
        </div>
        <button type="submit" class="btn btn-outline">بحث</button>
        <a href="/audit" class="btn btn-sm btn-outline" style="color:#6B7280;">مسح</a>
    </form>
</div>

<?php if (empty($rows)): ?>
    <div class="card" style="padding:60px;text-align:center;color:#6B7280;font-size:16px;">لا توجد سجلات مطابقة</div>
<?php else: ?>

<div style="display:flex;flex-direction:column;gap:8px;">
<?php foreach ($rows as $idx => $r):
    $action = $r['action'] ?? '';
    $color = AuditService::getActionColor($action);
    $icon = AuditService::getActionIcon($action);
    $actionLabel = AuditService::getActionLabel($action);
    $entityLabel = AuditService::getEntityTypeLabel($r['entity_type'] ?? '');

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

    $ts = strtotime($r['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 class="card audit-row" style="border-right:4px solid <?= $color ?>;padding:0;overflow:hidden;cursor:pointer;" onclick="toggleAuditDetail(<?= $idx ?>)">
    <div style="padding:12px 16px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
        <div style="font-size:20px;flex-shrink:0;width:32px;text-align:center;"><?= $icon ?></div>

        <div style="flex:1;min-width:200px;">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:3px;">
                <span style="color:<?= $color ?>;font-weight:700;font-size:14px;"><?= e($actionLabel) ?></span>
                <span style="background:#F3F4F6;padding:1px 8px;border-radius:10px;font-size:12px;color:#4B5563;"><?= e($entityLabel) ?></span>
                <?php if ($r['entity_label']): ?>
                    <span style="color:#1A1A2E;font-weight:500;font-size:13px;"><?= e($r['entity_label']) ?></span>
                <?php elseif ($r['entity_id']): ?>
                    <span style="color:#9CA3AF;font-size:12px;">#<?= (int) $r['entity_id'] ?></span>
                <?php endif; ?>
            </div>

            <div style="display:flex;gap:12px;flex-wrap:wrap;font-size:12px;color:#6B7280;">
                <span><?= e($r['employee_name'] ?? 'النظام') ?></span>
                <?php if ($r['ip_address']): ?>
                    <span style="direction:ltr;display:inline-block;"><?= e($r['ip_address']) ?></span>
                <?php endif; ?>
            </div>
        </div>

        <div style="min-width:250px;max-width:400px;font-size:12px;">
            <?php if ($action === 'update' && is_array($changedFields) && !empty($changedFields)): ?>
                <?php $preview = array_slice($changedFields, 0, 2, true); ?>
                <?php foreach ($preview as $fname => $fchange): ?>
                    <?php if (is_array($fchange) && isset($fchange['from'])): ?>
                    <div style="margin-bottom:1px;">
                        <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, 25)) ?></span>
                        <span style="color:#9CA3AF;margin:0 2px;">←</span>
                        <span style="color:#059669;"><?= e(mb_substr(AuditService::formatFieldValue($fname, $fchange['to']), 0, 25)) ?></span>
                    </div>
                    <?php endif; ?>
                <?php endforeach; ?>
                <?php if (count($changedFields) > 2): ?>
                    <span style="color:#9CA3AF;font-size:11px;">+<?= count($changedFields) - 2 ?> تغيير آخر</span>
                <?php endif; ?>
            <?php elseif ($action === 'create' && is_array($afterData) && !empty($afterData)): ?>
                <span style="color:#059669;font-size:11px;">سجل جديد (<?= count($afterData) ?> حقل)</span>
            <?php elseif ($action === 'delete' && is_array($beforeData) && !empty($beforeData)): ?>
                <span style="color:#DC2626;font-size:11px;">تم الحذف (<?= count($beforeData) ?> حقل)</span>
            <?php elseif ($r['notes']): ?>
                <span style="color:#6B7280;"><?= e(mb_substr($r['notes'], 0, 60)) ?></span>
            <?php endif; ?>
        </div>

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

    <div id="audit-detail-<?= $idx ?>" 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(280px,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:6px 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 #E5E7EB;width:25%;">الحقل</th>
                        <th style="padding:8px 12px;text-align:right;border-bottom:1px solid #E5E7EB;width:37%;">قبل</th>
                        <th style="padding:8px 12px;text-align:right;border-bottom:1px solid #E5E7EB;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(280px,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:6px 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(280px,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:6px 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 ($r['notes']): ?>
            <div style="color:#4B5563;font-size:13px;"><?= e($r['notes']) ?></div>
        <?php else: ?>
            <div style="color:#9CA3AF;font-size:13px;">لا توجد تفاصيل إضافية</div>
        <?php endif; ?>

        <?php if ($r['entity_type'] && $r['entity_id']): ?>
        <div style="margin-top:10px;padding-top:8px;border-top:1px solid #E5E7EB;">
            <a href="/audit/entity/<?= urlencode($r['entity_type']) ?>/<?= (int) $r['entity_id'] ?>" style="color:#0D7377;font-size:12px;font-weight:600;">عرض كل سجل هذا الكيان ←</a>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endforeach; ?>
</div>

<?php if ($pagination['last_page'] > 1): ?>
<div style="padding:20px 0;">
    <nav>
        <ul style="display:flex;gap:5px;list-style:none;padding:0;justify-content:center;flex-wrap:wrap;">
            <?php if ($pagination['has_prev']): ?>
                <li><a href="?page=<?= $pagination['prev_page'] ?>&q=<?= urlencode($filters['search']) ?>&action=<?= urlencode($filters['action']) ?>&entity_type=<?= urlencode($filters['entity_type']) ?>&employee_id=<?= urlencode($filters['employee_id']) ?>&date_from=<?= urlencode($filters['date_from']) ?>&date_to=<?= urlencode($filters['date_to']) ?>" class="btn btn-sm btn-outline">السابق</a></li>
            <?php endif; ?>
            <?php foreach ($pagination['pages'] as $p): ?>
                <?php if ($p === '...'): ?>
                    <li style="padding:5px;">...</li>
                <?php else: ?>
                    <li><a href="?page=<?= $p ?>&q=<?= urlencode($filters['search']) ?>&action=<?= urlencode($filters['action']) ?>&entity_type=<?= urlencode($filters['entity_type']) ?>&employee_id=<?= urlencode($filters['employee_id']) ?>&date_from=<?= urlencode($filters['date_from']) ?>&date_to=<?= urlencode($filters['date_to']) ?>" class="btn btn-sm <?= $p === $pagination['current_page'] ? 'btn-primary' : 'btn-outline' ?>"><?= $p ?></a></li>
                <?php endif; ?>
            <?php endforeach; ?>
            <?php if ($pagination['has_next']): ?>
                <li><a href="?page=<?= $pagination['next_page'] ?>&q=<?= urlencode($filters['search']) ?>&action=<?= urlencode($filters['action']) ?>&entity_type=<?= urlencode($filters['entity_type']) ?>&employee_id=<?= urlencode($filters['employee_id']) ?>&date_from=<?= urlencode($filters['date_from']) ?>&date_to=<?= urlencode($filters['date_to']) ?>" class="btn btn-sm btn-outline">التالي</a></li>
            <?php endif; ?>
        </ul>
    </nav>
</div>
<?php endif; ?>

<?php endif; ?>

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

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

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