<?php
/**
 * @var \App\View\AppView $this
 * @var \Cake\Datasource\ResultSetInterface|\App\Model\Entity\ChangeRequest[] $requests
 */
$this->assign('title', 'My Change Requests');

$fieldLabels = [
    'category' => 'Category',
    'question' => 'Question',
    'answer'   => 'Answer',
    'link'     => 'Link',
    'tags'     => 'Tags',
];

$getFaqSnapshot = function ($faq) use ($fieldLabels) {
    if (!$faq) return [];
    $snap = [];
    foreach (array_keys($fieldLabels) as $k) {
        $snap[$k] = $faq->{$k} ?? '';
    }
    return $snap;
};

$getPayloadData = function ($payload) use ($fieldLabels) {
    $data = [];
    foreach (array_keys($fieldLabels) as $k) {
        if (array_key_exists($k, $payload)) {
            $data[$k] = $payload[$k];
        }
    }
    return $data;
};
?>

<div class="container mt-5" style="max-width: 1100px;">
    <div class="card shadow-sm p-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
                <h2 class="mb-0">My Change Requests</h2>
                <p class="text-muted mb-0">Track the status of your submissions</p>
            </div>
            <?= $this->Html->link('← Back to Dashboard', ['controller' => 'Admin', 'action' => 'index'], [
                'class' => 'btn btn-outline-secondary'
            ]) ?>
        </div>

        <?php if ($requests->isEmpty()): ?>
            <div class="text-center py-5 text-muted">
                <p>No pending requests at the moment 🎉</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-striped align-middle">
                    <thead class="table-light">
                    <tr>
                        <th>Action</th>
                        <th>FAQ ID</th>
                        <th>Category</th>
                        <th>Question Preview</th>
                        <th>Submitted</th>
                        <th>Status</th>
                        <th class="text-center">Details</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($requests as $r): ?>
                        <?php
                        $payloadArr = json_decode((string)$r->payload, true) ?: [];

                        $readSnap = function($v) {
                            if (is_array($v)) return $v;
                            if (is_string($v) && $v !== '') {
                                $d = json_decode($v, true);
                                return is_array($d) ? $d : null;
                            }
                            return null;
                        };

                        $fieldKeys = array_keys($fieldLabels);

                        $beforeSnap = $readSnap($r->before_json);
                        $afterSnap  = $readSnap($r->after_json);

                        if ($r->action === 'add') {
                            $before = $beforeSnap ?? null;
                            $after  = $afterSnap  ?? array_intersect_key($payloadArr, array_flip($fieldKeys));
                        } elseif ($r->action === 'edit') {
                            // before
                            $before = $beforeSnap ?? (function() use($r, $fieldKeys){
                                $arr = [];
                                foreach ($fieldKeys as $k) { $arr[$k] = $r->faq->{$k} ?? ''; }
                                return $arr;
                            })();
                            // after
                            $after = $before;
                            $delta = $afterSnap ?? array_intersect_key($payloadArr, array_flip($fieldKeys));
                            foreach ($delta as $k => $v) { $after[$k] = $v; }
                        } elseif ($r->action === 'delete') {
                            $before = $beforeSnap ?? (function() use($r, $fieldKeys){
                                $arr = [];
                                foreach ($fieldKeys as $k) { $arr[$k] = $r->faq->{$k} ?? ''; }
                                return $arr;
                            })();
                            $after  = $afterSnap ?? null;
                        } else {
                            $before = null; $after = null;
                        }

                        $question = $after['question'] ?? ($before['question'] ?? ($payloadArr['question'] ?? ($r->faq->question ?? '')));
                        $category = $after['category'] ?? ($before['category'] ?? ($payloadArr['category'] ?? ($r->faq->category ?? '')));

                        $isPending = $r->status === 'pending';
                        $modalId   = 'reqDetails_' . $r->id;

                        $hasChanges = false;
                        if ($r->action === 'edit') {
                            foreach ($fieldKeys as $k) {
                                if ((string)($before[$k] ?? '') !== (string)($after[$k] ?? '')) { $hasChanges = true; break; }
                            }
                        } elseif ($r->action === 'add') {
                            $hasChanges = !empty(array_filter(($after ?? []), fn($v) => $v !== '' && $v !== null));
                        } elseif ($r->action === 'delete') {
                            $hasChanges = !empty(array_filter(($before ?? []), fn($v) => $v !== '' && $v !== null));
                        }
                        ?>
                        <tr>
                            <td><span class="badge bg-primary"><?= h($r->action) ?></span></td>
                            <td>
                                <?php if ($r->faq_id): ?>
                                    <?= (int)$r->faq_id ?>
                                <?php else: ?>
                                    <span class="text-muted">(new)</span>
                                <?php endif; ?>
                            </td>
                            <td><?= h($category) ?></td>
                            <td><?= h(mb_strimwidth((string)$question, 0, 50, '...')) ?></td>
                            <td><?= $r->created->i18nFormat('yyyy-MM-dd HH:mm') ?></td>
                            <td>
                                <?php if ($r->status === 'pending'): ?>
                                    <span class="badge bg-warning text-dark">Pending</span>
                                <?php elseif ($r->status === 'approved'): ?>
                                    <span class="badge bg-success">Approved</span>
                                <?php else: ?>
                                    <span class="badge bg-danger">Rejected</span>
                                <?php endif; ?>
                            </td>

                            <td class="text-center">
                                <button type="button"
                                        class="btn btn-outline-primary btn-sm <?= $hasChanges ? 'pulse-once' : '' ?>"
                                        data-bs-toggle="modal"
                                        data-bs-target="#<?= h($modalId) ?>">
                                    Details
                                </button>
                            </td>
                        </tr>

                        <!-- Details Modal -->
                        <div class="modal fade" id="<?= h($modalId) ?>" tabindex="-1" aria-labelledby="<?= h($modalId) ?>Label" aria-hidden="true">
                            <div class="modal-dialog modal-lg modal-dialog-scrollable">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="<?= h($modalId) ?>Label">
                                            Request Details — <?= h(ucfirst($r->action)) ?>
                                            <?php if ($r->faq_id): ?>
                                                <small class="text-muted ms-2">FAQ #<?= (int)$r->faq_id ?></small>
                                            <?php endif; ?>
                                        </h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>

                                    <div class="modal-body">
                                        <?php if ($r->action === 'add'): ?>
                                            <p class="text-muted mb-2">This will <strong>add</strong> the following item:</p>
                                            <div class="list-group">
                                                <?php foreach ($fieldLabels as $k => $label): ?>
                                                    <?php $val = $after[$k] ?? ''; ?>
                                                    <?php if ($val !== '' && $val !== null): ?>
                                                        <div class="list-group-item">
                                                            <div class="small text-uppercase text-muted fw-semibold"><?= h($label) ?></div>
                                                            <div><?= h($val) ?></div>
                                                        </div>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            </div>

                                        <?php elseif ($r->action === 'edit'): ?>
                                            <p class="text-muted mb-2">This will <strong>edit</strong> the following fields:</p>
                                            <div class="list-group">
                                                <?php foreach ($fieldLabels as $k => $label): ?>
                                                    <?php
                                                    $oldVal  = $before[$k] ?? '';
                                                    $newVal  = $after[$k]  ?? '';
                                                    $changed = ((string)$oldVal !== (string)$newVal);
                                                    ?>
                                                    <div class="list-group-item <?= $changed ? 'changed' : '' ?>">
                                                        <div class="d-flex justify-content-between align-items-start">
                                                            <div class="small text-uppercase text-muted fw-semibold"><?= h($label) ?></div>
                                                            <?php if ($changed): ?>
                                                                <span class="badge bg-info-subtle text-dark border">Changed</span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="mt-1">
                                                            <div class="diff-block">
                                                                <div class="diff-label text-muted">Before</div>
                                                                <div class="diff-value"><?= h($oldVal) ?></div>
                                                            </div>
                                                            <div class="diff-block mt-2">
                                                                <div class="diff-label text-muted">After</div>
                                                                <div class="diff-value fw-semibold"><?= h($newVal) ?></div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>

                                        <?php elseif ($r->action === 'delete'): ?>
                                            <p class="text-muted mb-2">This will <strong>delete</strong> the following item (snapshot):</p>
                                            <div class="list-group">
                                                <?php foreach ($fieldLabels as $k => $label): ?>
                                                    <?php $val = $before[$k] ?? ''; ?>
                                                    <?php if ($val !== '' && $val !== null): ?>
                                                        <div class="list-group-item">
                                                            <div class="small text-uppercase text-muted fw-semibold"><?= h($label) ?></div>
                                                            <div><?= h($val) ?></div>
                                                        </div>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php else: ?>
                                            <p class="text-muted">Unknown action.</p>
                                        <?php endif; ?>


                                    </div>

                                    <div class="modal-footer">
                                         <span class="text-muted small me-auto">
                                             Status:
                                             <?php if ($r->status === 'pending'): ?>
                                                 <span class="badge bg-warning text-dark">Pending</span>
                                             <?php elseif ($r->status === 'approved'): ?>
                                                 <span class="badge bg-success">Approved</span>
                                             <?php else: ?>
                                                 <span class="badge bg-danger">Rejected</span>
                                             <?php endif; ?>
                                        </span>
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <!-- /Details Modal -->

                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
    .badge {
        font-size: 0.85rem;
        padding: 6px 10px;
    }
    .list-group-item.changed {
        border-left: 4px solid #0dcaf0; /* info color */
        background: #f8fdff;
    }
    .diff-label {
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: .02em;
    }
    .diff-value {
        white-space: pre-wrap;
        word-break: break-word;
    }
    .pulse-once {
        animation: pulse 1.2s ease-in-out 1;
    }
    @keyframes pulse {
        0% { box-shadow: 0 0 0 0 rgba(13,202,240,.5); }
        100% { box-shadow: 0 0 0 16px rgba(13,202,240,0); }
    }
</style>
