<?php $this->start('body');
    $d          = $this->data['doc'] ?? [];
    $grants     = $this->data['grants'] ?? [];
    $ungranted  = $this->data['ungranted'] ?? [];
    $isAdm      = !empty($this->data['is_admin_role']);
    $defaultRoles = $this->data['default_roles'] ?? [];

    $statusColor = ['CURRENT'=>'#7A9E7E','SUPERSEDED'=>'#94A3B8','EXPIRED'=>'#C48579','PENDING_RENEWAL'=>'#D4A574'];
    $sc = $statusColor[$d['status']] ?? '#94A3B8';
    $daysLeft = null;
    if (!empty($d['expiry_date'])) $daysLeft = round((strtotime($d['expiry_date']) - time()) / 86400);
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;color:#334155;"><i class="fas fa-file-alt me-2" style="color:#7A8BA1;"></i><?= htmlspecialchars($d['doc_name']); ?></h5>
        <div class="text-muted small mt-1" style="color:#64748B;"><?= htmlspecialchars((string)$d['doc_type_code']); ?><?php if (!empty($d['type_label'])): ?> · <?= htmlspecialchars((string)$d['type_label']); ?><?php endif; ?></div>
    </div>
    <div class="d-flex align-items-center gap-2">
        <span class="badge" style="background:<?= $sc; ?>;color:#fff;font-size:.72rem;padding:.35rem .7rem;text-transform:capitalize;"><?= ucwords(strtolower(str_replace('_',' ', $d['status']))); ?></span>
        <?php if ($isAdm && UserGroups::can('CompanyDocuments','edit')): ?><a href="<?= PROOT; ?>CompanyDocuments/edit/<?= (int)$d['c0d']; ?>" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;"><i class="fas fa-edit me-1" style="color:#7A8BA1;"></i>Edit</a><?php endif; ?>
        <a href="<?= PROOT; ?>CompanyDocuments" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;"><i class="fas fa-arrow-left me-1"></i>Back</a>
    </div>
</div>

<?php if ($daysLeft !== null && $daysLeft < 0): ?>
<div class="alert py-2 mb-3" style="background:#FDEDEA;border:1px solid #F5C6BF;color:#8A4A3A;font-size:.86rem;">
    <i class="fas fa-exclamation-triangle me-1"></i>
    <strong>This document expired <?= abs((int)$daysLeft); ?> day<?= abs((int)$daysLeft) === 1 ? '' : 's'; ?> ago</strong> — upload the renewed version and mark this one as SUPERSEDED.
</div>
<?php elseif ($daysLeft !== null && $daysLeft <= 60): ?>
<div class="alert py-2 mb-3" style="background:#FEFDF6;border:1px solid #EFE7D2;color:#7A6039;font-size:.86rem;">
    <i class="fas fa-hourglass-half me-1" style="color:#D4A574;"></i>
    <strong>Expires in <?= (int)$daysLeft; ?> days</strong> (<?= htmlspecialchars((string)$d['expiry_date']); ?>) — start the renewal process.
</div>
<?php endif; ?>

<div class="row g-3">
    <!-- Details ── -->
    <div class="col-md-7">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white" style="border-bottom:1px solid #E2E8F0;"><strong style="color:#334155;"><i class="fas fa-info-circle me-2" style="color:#7A8BA1;"></i>Document details</strong></div>
            <div class="card-body p-3">
                <dl class="row mb-0" style="color:#334155;font-size:.86rem;">
                    <dt class="col-md-4" style="color:#64748B;">Reference number</dt><dd class="col-md-8"><?= htmlspecialchars((string)$d['ref_no']) ?: '—'; ?></dd>
                    <dt class="col-md-4" style="color:#64748B;">Issued</dt><dd class="col-md-8"><?= htmlspecialchars((string)($d['issue_date'] ?? '—')); ?></dd>
                    <dt class="col-md-4" style="color:#64748B;">Expires</dt><dd class="col-md-8"><?= htmlspecialchars((string)($d['expiry_date'] ?? '—')); ?><?php if ($daysLeft !== null && $daysLeft >= 0): ?> <span style="color:#94A3B8;font-size:.72rem;">(<?= (int)$daysLeft; ?> days left)</span><?php endif; ?></dd>
                    <?php if (!empty($d['notes'])): ?>
                        <dt class="col-md-4" style="color:#64748B;">Notes</dt><dd class="col-md-8"><?= nl2br(htmlspecialchars((string)$d['notes'])); ?></dd>
                    <?php endif; ?>
                    <?php if (!empty($d['file_path'])): ?>
                        <dt class="col-md-4" style="color:#64748B;">File</dt><dd class="col-md-8"><?= htmlspecialchars((string)$d['file_path']); ?></dd>
                    <?php endif; ?>
                    <dt class="col-md-4" style="color:#64748B;">Uploaded by</dt><dd class="col-md-8"><?= htmlspecialchars((string)$d['uploaded_by_name']); ?><?php if (!empty($d['uploaded_by_role'])): ?> <span style="color:#94A3B8;font-size:.72rem;">(<?= htmlspecialchars((string)$d['uploaded_by_role']); ?>)</span><?php endif; ?></dd>
                    <dt class="col-md-4" style="color:#64748B;">Uploaded on</dt><dd class="col-md-8"><?= htmlspecialchars((string)$d['created_on']); ?></dd>
                </dl>
            </div>
        </div>
    </div>

    <!-- Access ── -->
    <div class="col-md-5">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white" style="border-bottom:1px solid #E2E8F0;">
                <strong style="color:#334155;"><i class="fas fa-users-cog me-2" style="color:#7A8BA1;"></i>Access</strong>
                <div class="text-muted small mt-1" style="color:#64748B;font-size:.72rem;">Default access: <strong><?= implode('</strong>, <strong>', $defaultRoles); ?></strong>. They can grant view access to other roles.</div>
            </div>
            <div class="card-body p-2">
                <?php if ($isAdm && !empty($ungranted) && UserGroups::can('CompanyDocuments','shareAj')): ?>
                <div class="d-flex gap-2 mb-2 p-2" style="background:#F8FAFC;border-radius:3px;">
                    <select id="grant_group" class="form-select form-select-sm">
                        <?php foreach ($ungranted as $g): ?>
                            <option value="<?= (int)$g['c0d']; ?>"><?= htmlspecialchars((string)$g['user_group_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" id="btn_share" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;white-space:nowrap;"><i class="fas fa-plus me-1"></i>Grant</button>
                </div>
                <?php endif; ?>
                <table class="table table-sm mb-0 align-middle">
                    <tbody>
                        <?php foreach ($grants as $g):
                            $isDefault = in_array($g['user_group_name'], $defaultRoles, true);
                        ?>
                        <tr>
                            <td style="color:#334155;font-size:.82rem;"><?= htmlspecialchars((string)$g['user_group_name']); ?>
                                <?php if ($isDefault): ?><span style="color:#94A3B8;font-size:.66rem;margin-left:.35rem;">default</span><?php endif; ?>
                                <div style="color:#94A3B8;font-size:.66rem;">granted by <?= htmlspecialchars((string)$g['granted_by_name']); ?> · <?= htmlspecialchars(date('d M', strtotime((string)$g['granted_on']))); ?></div>
                            </td>
                            <td class="text-end" style="width:1%;">
                                <?php if ($isAdm && !$isDefault && UserGroups::can('CompanyDocuments','revokeAj')): ?>
                                <button type="button" class="btn btn-sm btn-revoke" data-gid="<?= (int)$g['user_group_id']; ?>" style="background:transparent;border:none;color:#C48579;padding:.2rem .4rem;" title="Revoke access"><i class="fas fa-times"></i></button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php $this->end(); ?>

<?php $this->start('section_js'); ?>
<script>
$(function () {
    var PROOT = '<?= PROOT; ?>';
    var DOC_ID = <?= (int)$d['c0d']; ?>;

    $('#btn_share').on('click', function () {
        var gid = parseInt($('#grant_group').val(), 10);
        if (!gid) return;
        $.post(PROOT + 'CompanyDocuments/shareAj', { doc_id: DOC_ID, user_group_id: gid }, 'json')
            .done(function (res) {
                if (res && res.ok) { rsToast('Access granted.', 'success'); setTimeout(function () { location.reload(); }, 400); }
                else                { rsToast('Failed: ' + (res.msg || 'unknown'), 'error'); }
            });
    });

    $('.btn-revoke').on('click', function () {
        var gid = parseInt($(this).data('gid'), 10);
        $.confirm({
            title: 'Revoke access?',
            content: 'That role will no longer see this document.',
            type: 'orange',
            buttons: {
                yes: { text: 'Revoke', btnClass: 'btn-warning', action: function () {
                    $.post(PROOT + 'CompanyDocuments/revokeAj', { doc_id: DOC_ID, user_group_id: gid }, 'json')
                        .done(function (res) {
                            if (res && res.ok) { rsToast('Access revoked.', 'success'); setTimeout(function () { location.reload(); }, 400); }
                            else                { rsToast('Failed: ' + (res.msg || 'unknown'), 'error'); }
                        });
                }},
                cancel: { text: 'Cancel', btnClass: 'btn-light' }
            }
        });
    });
});
</script>
<?php $this->end(); ?>
