<?php
    $status_map = [
        'pending'  => ['warning',   'text-dark', 'hourglass-split', 'En attente d\'approbation'],
        'approved' => ['success',   '',          'check-circle',    'Approuvée'],
        'rejected' => ['danger',    '',          'x-circle',        'Rejetée'],
        'paid'     => ['info',      '',          'credit-card',     'Payée — dépense créée'],
        'closed'   => ['secondary', '',          'lock',            'Clôturée'],
    ];
    $s = $status_map[$request->status] ?? ['secondary', '', 'circle', $request->status];
?>

<div class="row justify-content-center">
    <div class="col-lg-8">
        <a href="<?= site_url('requests'); ?>" class="text-decoration-none text-muted small">
            <i class="bi bi-arrow-left"></i> Retour aux demandes
        </a>

        <div class="card shadow-sm mt-2">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bi bi-file-earmark-text"></i> <?= $request->reference; ?>
                </h5>
                <span class="badge bg-<?= $s[0]; ?> <?= $s[1]; ?> fs-6">
                    <i class="bi bi-<?= $s[2]; ?>"></i> <?= $s[3]; ?>
                </span>
            </div>
            <div class="card-body">

                <!-- Workflow visuel -->
                <div class="d-flex justify-content-between align-items-center mb-4 px-3">
                    <?php
                        $steps = [
                            ['label' => 'Soumise',   'done' => true],
                            ['label' => 'Approuvée', 'done' => in_array($request->status, ['approved','paid','closed'])],
                            ['label' => 'Payée',     'done' => in_array($request->status, ['paid','closed'])],
                            ['label' => 'Clôturée',  'done' => $request->status === 'closed'],
                        ];
                        $rejected = $request->status === 'rejected';
                    ?>
                    <?php foreach ($steps as $i => $step): ?>
                    <div class="text-center flex-fill">
                        <div class="rounded-circle d-inline-flex align-items-center justify-content-center 
                                    <?= $rejected && $i == 1 ? 'bg-danger' : ($step['done'] ? 'bg-success' : 'bg-light'); ?>"
                             style="width:32px; height:32px;">
                            <?php if ($rejected && $i == 1): ?>
                                <i class="bi bi-x text-white"></i>
                            <?php elseif ($step['done']): ?>
                                <i class="bi bi-check text-white"></i>
                            <?php else: ?>
                                <span class="text-muted small"><?= $i + 1; ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="small mt-1 <?= $step['done'] ? 'fw-semibold' : 'text-muted'; ?>">
                            <?= $step['label']; ?>
                        </div>
                    </div>
                    <?php if ($i < count($steps) - 1): ?>
                    <div class="flex-fill" style="border-top: 2px <?= $step['done'] ? 'solid #198754' : 'dashed #dee2e6'; ?>; margin-top: -16px;"></div>
                    <?php endif; ?>
                    <?php endforeach; ?>
                </div>

                <div class="row">
                    <div class="col-md-7">
                        <table class="table table-sm table-borderless">
                            <tr>
                                <td class="text-muted" style="width:35%">Référence</td>
                                <td class="fw-semibold"><code><?= $request->reference; ?></code></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Date</td>
                                <td><?= date('d/m/Y', strtotime($request->request_date)); ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Catégorie</td>
                                <td><span class="badge bg-light text-dark"><?= $request->category_label; ?></span></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Localisation</td>
                                <td><i class="bi bi-geo-alt"></i> <?= $request->location_name; ?></td>
                            </tr>
                            <?php if ($request->supplier): ?>
                            <tr>
                                <td class="text-muted">Fournisseur</td>
                                <td><?= htmlspecialchars($request->supplier); ?></td>
                            </tr>
                            <?php endif; ?>
                            <tr>
                                <td class="text-muted">Description</td>
                                <td><?= nl2br(htmlspecialchars($request->description)); ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Demandé par</td>
                                <td><?= htmlspecialchars($request->requested_by_name); ?>
                                    <small class="text-muted">(<?= date('d/m/Y H:i', strtotime($request->created_at)); ?>)</small>
                                </td>
                            </tr>
                            <?php if ($request->approved_by_name): ?>
                            <tr>
                                <td class="text-muted"><?= $request->status === 'rejected' ? 'Rejeté par' : 'Approuvé par'; ?></td>
                                <td><?= htmlspecialchars($request->approved_by_name); ?>
                                    <small class="text-muted">(<?= date('d/m/Y H:i', strtotime($request->approved_at)); ?>)</small>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </table>
                    </div>
                    <div class="col-md-5">
                        <!-- Montant -->
                        <div class="card bg-light mb-3">
                            <div class="card-body text-center py-3">
                                <small class="text-muted">Montant estimé</small>
                                <div class="h2 fw-bold mb-0">
                                    <?= number_format($request->estimated_amount, 0, ',', ' '); ?> 
                                    <small class="fs-5">KMF</small>
                                </div>
                            </div>
                        </div>

                        <!-- Motif de rejet -->
                        <?php if ($request->status === 'rejected' && $request->rejection_reason): ?>
                        <div class="alert alert-danger py-2">
                            <strong><i class="bi bi-x-circle"></i> Motif du rejet :</strong><br>
                            <?= nl2br(htmlspecialchars($request->rejection_reason)); ?>
                        </div>
                        <?php endif; ?>

                        <!-- Dépense liée -->
                        <?php if ($linked_expense): ?>
                        <div class="card border-success mb-3">
                            <div class="card-header bg-success bg-opacity-10 py-1">
                                <strong class="small"><i class="bi bi-link-45deg text-success"></i> Dépense liée</strong>
                            </div>
                            <div class="card-body py-2">
                                <table class="table table-sm table-borderless mb-0">
                                    <tr>
                                        <td class="text-muted">Réf.</td>
                                        <td>
                                            <a href="<?= site_url('expenses/view/' . $linked_expense->id); ?>">
                                                <code><?= $linked_expense->expense_id; ?></code>
                                            </a>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">Montant réel</td>
                                        <td class="fw-semibold"><?= number_format($linked_expense->amount, 0, ',', ' '); ?> KMF
                                            <?php if (abs($linked_expense->amount - $request->estimated_amount) > 0): ?>
                                            <small class="text-<?= $linked_expense->amount > $request->estimated_amount ? 'danger' : 'success'; ?>">
                                                (<?= $linked_expense->amount > $request->estimated_amount ? '+' : ''; ?><?= number_format($linked_expense->amount - $request->estimated_amount, 0, ',', ' '); ?>)
                                            </small>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">Caisse</td>
                                        <td><?= $linked_expense->cashbox_name ?? '—'; ?></td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">Statut</td>
                                        <td>
                                            <?php
                                                $exp_colors = ['pending'=>'warning','validated'=>'success','batched'=>'info','rejected'=>'danger'];
                                                $ec = $exp_colors[$linked_expense->status] ?? 'secondary';
                                            ?>
                                            <span class="badge bg-<?= $ec; ?>"><?= $linked_expense->status; ?></span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">Justificatif</td>
                                        <td>
                                            <?php if ( ! empty($linked_expense->invoice_path)): ?>
                                                <a href="<?= base_url($linked_expense->invoice_path); ?>" target="_blank" class="text-success">
                                                    <i class="bi bi-check-circle-fill"></i> Joint
                                                </a>
                                            <?php else: ?>
                                                <span class="text-danger"><i class="bi bi-x-circle-fill"></i> Manquant</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        <?php elseif ($request->status === 'approved'): ?>
                        <div class="alert alert-warning py-2">
                            <i class="bi bi-exclamation-triangle"></i> <strong>Aucune dépense créée</strong> pour cette demande approuvée.
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Actions -->
                <?php if ($request->status === 'pending'): ?>
                <hr>
                <div class="d-flex gap-2 flex-wrap">
                    <?php if ($this->auth_lib->has_permission('request_approve')): ?>
                    <a href="<?= site_url('requests/approve/' . $request->id); ?>"
                       class="btn btn-success"
                       onclick="return confirm('Approuver cette demande de <?= number_format($request->estimated_amount, 0, ',', ' '); ?> KMF ?');">
                        <i class="bi bi-check-lg"></i> Approuver
                    </a>

                    <button class="btn btn-outline-danger" data-bs-toggle="collapse" data-bs-target="#rejectForm">
                        <i class="bi bi-x-lg"></i> Rejeter
                    </button>
                    <?php endif; ?>

                    <?php
                        $can_edit = ($request->requested_by == $this->auth_lib->user_id()) || $this->auth_lib->is_manager_or_admin();
                    ?>
                    <?php if ($can_edit): ?>
                    <a href="<?= site_url('requests/edit/' . $request->id); ?>" class="btn btn-outline-primary">
                        <i class="bi bi-pencil"></i> Modifier
                    </a>
                    <?php endif; ?>
                </div>

                <!-- Formulaire de rejet -->
                <?php if ($this->auth_lib->has_permission('request_approve')): ?>
                <div class="collapse mt-3" id="rejectForm">
                    <div class="card border-danger">
                        <div class="card-body">
                            <?= form_open('requests/reject/' . $request->id); ?>
                                <div class="mb-2">
                                    <label class="form-label">Motif du rejet <span class="text-danger">*</span></label>
                                    <textarea name="rejection_reason" class="form-control" rows="2" required
                                              placeholder="Raison du rejet..."></textarea>
                                </div>
                                <button type="submit" class="btn btn-danger btn-sm"
                                        onclick="return confirm('Confirmer le rejet ?');">
                                    <i class="bi bi-x-lg"></i> Confirmer le rejet
                                </button>
                            <?= form_close(); ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                <?php endif; ?>

                <!-- Si approuvée, proposer de créer la dépense -->
                <?php if ($request->status === 'approved' && $this->auth_lib->has_permission('expense_create')): ?>
                <hr>
                <div class="alert alert-success py-2">
                    <i class="bi bi-check-circle"></i> Cette demande est approuvée.
                    <a href="<?= site_url('expenses/create_from_request/' . $request->id); ?>" class="btn btn-sm btn-success ms-2">
                        <i class="bi bi-receipt"></i> Créer la dépense correspondante
                    </a>
                    <div class="form-text mt-1">Dans le formulaire de dépense, sélectionnez cette demande dans le champ "Lier à une demande".</div>
                </div>
                <?php endif; ?>

            </div>
        </div>
    </div>
</div>
