<?php
    $status_map = [
        'draft'        => ['secondary', 'pencil',        'Brouillon'],
        'finalized'    => ['primary',   'check2-circle', 'Finalisé — ZIP prêt'],
        'sent'         => ['success',   'send',          'Envoyé à la compagnie'],
        'acknowledged' => ['info',      'check2-all',    'Accusé de réception'],
    ];
    $s = $status_map[$batch->status] ?? ['secondary', 'circle', $batch->status];
?>

<div class="row justify-content-center">
    <div class="col-lg-11">
        <a href="<?= site_url('batches'); ?>" class="text-decoration-none text-muted small">
            <i class="bi bi-arrow-left"></i> Retour aux batchs
        </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-collection"></i> <?= $batch->batch_id; ?>
                </h5>
                <span class="badge bg-<?= $s[0]; ?> fs-6">
                    <i class="bi bi-<?= $s[1]; ?>"></i> <?= $s[2]; ?>
                </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' => 'Créé',     'done' => true],
                            ['label' => 'Finalisé', 'done' => in_array($batch->status, ['finalized','sent','acknowledged'])],
                            ['label' => 'Envoyé',   'done' => in_array($batch->status, ['sent','acknowledged'])],
                            ['label' => 'Accusé',   'done' => $batch->status === 'acknowledged'],
                        ];
                    ?>
                    <?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 
                                    <?= $step['done'] ? 'bg-success' : 'bg-light'; ?>"
                             style="width:32px; height:32px;">
                            <?php if ($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>

                <!-- Infos -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <table class="table table-sm table-borderless">
                            <tr><td class="text-muted" style="width:35%">Batch ID</td><td class="fw-semibold"><code><?= $batch->batch_id; ?></code></td></tr>
                            <tr><td class="text-muted">Semaine</td><td>S<?= str_pad($batch->week_number, 2, '0', STR_PAD_LEFT); ?> / <?= $batch->year; ?></td></tr>
                            <tr><td class="text-muted">Période</td><td><?= date('d/m/Y', strtotime($batch->period_start)); ?> → <?= date('d/m/Y', strtotime($batch->period_end)); ?></td></tr>
                            <tr><td class="text-muted">Créé par</td><td><?= htmlspecialchars($batch->created_by_name); ?></td></tr>
                            <tr><td class="text-muted">Créé le</td><td><?= date('d/m/Y H:i', strtotime($batch->created_at)); ?></td></tr>
                            <?php if ($batch->finalized_at): ?>
                            <tr><td class="text-muted">Finalisé le</td><td><?= date('d/m/Y H:i', strtotime($batch->finalized_at)); ?></td></tr>
                            <?php endif; ?>
                            <?php if ($batch->sent_at): ?>
                            <tr><td class="text-muted">Envoyé le</td><td><?= date('d/m/Y H:i', strtotime($batch->sent_at)); ?></td></tr>
                            <?php endif; ?>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <!-- Résumé financier -->
                        <div class="card bg-light">
                            <div class="card-body py-3 text-center">
                                <div class="h3 fw-bold text-primary mb-1"><?= number_format($batch->total_amount, 0, ',', ' '); ?> KMF</div>
                                <div class="text-muted"><?= $batch->expense_count; ?> dépense(s)</div>
                            </div>
                        </div>

                        <!-- Par localisation -->
                        <?php if ( ! empty($by_location)): ?>
                        <div class="mt-2">
                            <?php foreach ($by_location as $loc_name => $loc_data): ?>
                            <div class="d-flex justify-content-between small border-bottom py-1">
                                <span><i class="bi bi-geo-alt"></i> <?= htmlspecialchars($loc_name); ?> (<?= $loc_data['count']; ?>)</span>
                                <span class="fw-semibold"><?= number_format($loc_data['total'], 0, ',', ' '); ?></span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Actions -->
                <div class="d-flex gap-2 mb-4 flex-wrap">
                    <?php if ($batch->status === 'draft' && $this->auth_lib->has_permission('batch_finalize')): ?>
                    <a href="<?= site_url('batches/finalize/' . $batch->id); ?>" class="btn btn-primary"
                       onclick="return confirm('Finaliser ce batch ? Les dépenses seront imputées au compte partenaire et le ZIP sera généré.');">
                        <i class="bi bi-check2-circle"></i> Finaliser et générer le ZIP
                    </a>
                    <?php endif; ?>

                    <?php if ($batch->zip_path): ?>
                    <a href="<?= site_url('batches/download/' . $batch->id); ?>" class="btn btn-outline-primary">
                        <i class="bi bi-file-zip"></i> Télécharger le ZIP
                    </a>
                    <?php endif; ?>

                    <?php if ($batch->status === 'finalized' && $this->auth_lib->has_permission('batch_finalize')): ?>
                    <a href="<?= site_url('batches/mark_sent/' . $batch->id); ?>" class="btn btn-success"
                       onclick="return confirm('Marquer comme envoyé ?');">
                        <i class="bi bi-send"></i> Marquer comme envoyé
                    </a>
                    <?php endif; ?>

                    <?php if ($batch->status === 'sent' && $this->auth_lib->has_permission('batch_finalize')): ?>
                    <a href="<?= site_url('batches/mark_acknowledged/' . $batch->id); ?>" class="btn btn-info"
                       onclick="return confirm('Confirmer l\'accusé de réception ?');">
                        <i class="bi bi-check2-all"></i> Accusé de réception
                    </a>
                    <?php endif; ?>
                </div>

                <!-- Tableau des dépenses -->
                <div class="card">
                    <div class="card-header bg-white py-2">
                        <h6 class="mb-0"><i class="bi bi-receipt"></i> Dépenses incluses</h6>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-sm table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>#</th>
                                    <th>Expense ID</th>
                                    <th>Date</th>
                                    <th>Fournisseur</th>
                                    <th>Description</th>
                                    <th>Catégorie</th>
                                    <th>Lieu</th>
                                    <th class="text-end">Montant</th>
                                    <th>Facture</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $n = 0; foreach ($expenses as $e): $n++; ?>
                                <tr>
                                    <td class="text-muted"><?= $n; ?></td>
                                    <td>
                                        <a href="<?= site_url('expenses/view/' . $e->id); ?>" class="text-decoration-none">
                                            <code><?= $e->expense_id; ?></code>
                                        </a>
                                    </td>
                                    <td class="small"><?= date('d/m/Y', strtotime($e->expense_date)); ?></td>
                                    <td class="small"><?= htmlspecialchars($e->supplier); ?></td>
                                    <td class="small"><?= htmlspecialchars(mb_substr($e->description, 0, 40)); ?></td>
                                    <td><span class="badge bg-light text-dark small"><?= $e->category_label; ?></span></td>
                                    <td><span class="badge bg-light text-dark small"><?= $e->location_name; ?></span></td>
                                    <td class="text-end fw-semibold"><?= number_format($e->amount, 0, ',', ' '); ?></td>
                                    <td class="text-center">
                                        <?php if ( ! empty($e->invoice_path)): ?>
                                        <a href="<?= base_url($e->invoice_path); ?>" target="_blank" class="text-success"><i class="bi bi-check-circle-fill"></i></a>
                                        <?php else: ?>
                                        <span class="text-danger"><i class="bi bi-x-circle-fill"></i></span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <tfoot class="table-light">
                                <tr class="fw-bold">
                                    <td colspan="7" class="text-end">TOTAL</td>
                                    <td class="text-end"><?= number_format($batch->total_amount, 0, ',', ' '); ?> KMF</td>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>

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