<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/invoice_contract.php';

auth_require();

$mode = $invoiceListMode ?? 'website';
$config = invoice_contract_mode_config($mode);
$contracts = invoice_contracts_for_mode($mode);
$total = count($contracts);
$signed = count(array_filter($contracts, static fn(array $c): bool => ($c['status'] ?? '') === 'signed'));
$pending = $total - $signed;
$requireDeletePassword = admin_delete_password_required();

render_header($config['list_title_key'], ['layout' => 'admin', 'page' => $config['list_page']]);
render_flash();
?>

<div class="grid grid-cols-1 sm:grid-cols-3 gap-4 sm:gap-6 mb-8">
    <?php stat_card('stat_total', (string)$total, 'description'); ?>
    <?php stat_card('stat_pending', (string)$pending, 'hourglass_empty'); ?>
    <?php stat_card('stat_signed', (string)$signed, 'verified'); ?>
</div>

<?php
page_heading($config['list_title_key'], $config['list_sub_key'], $config['create_path'], 'nav_new_contract', true);
?>

<?php if (empty($contracts)): ?>
<div class="card">
    <div class="empty-state">
        <div class="empty-state-icon">
            <span class="material-symbols-rounded"><?= e($config['icon']) ?></span>
        </div>
        <h3 class="font-display font-bold text-xl text-karvi-950 mb-2"><?= e(__('no_contracts')) ?></h3>
        <p class="text-karvi-500 text-sm mb-6 max-w-sm mx-auto"><?= e(__('invoice_no_contracts_sub')) ?></p>
        <a href="<?= e(app_path($config['create_path'])) ?>" class="btn-primary">
            <span class="material-symbols-rounded">add</span>
            <?= e(__('nav_new_contract')) ?>
        </a>
    </div>
</div>
<?php else: ?>
<div class="data-table-wrap">
    <table class="data-table">
        <thead>
            <tr>
                <th><?= e(__('col_contract')) ?></th>
                <th><?= e(__('invoice_col_customer')) ?></th>
                <?php if ($mode === 'pos'): ?>
                <th><?= e(__('col_type')) ?></th>
                <?php endif; ?>
                <th><?= e(__('col_status')) ?></th>
                <th><?= e(__('col_date')) ?></th>
                <th><?= e(__('invoice_col_total')) ?></th>
                <th><?= e(__('col_actions')) ?></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($contracts as $contract):
                $url = contract_public_sign_url_from_record($contract);
                if ($url === '') {
                    $url = contract_customer_url($contract) ?: contract_url((string)($contract['token'] ?? ''));
                }
                $ref = invoice_contract_reference($contract, $mode);
                $isSignedStatus = ($contract['status'] ?? '') === 'signed';
                $signedPdfReady = contract_download_available($contract) || $isSignedStatus;
                $signedPdfUrl = admin_contract_download_url($contract);
                $totals = is_array($contract['totals'] ?? null) ? $contract['totals'] : [];
                $totalAmount = invoice_format_money((float)($totals['total'] ?? 0));
            ?>
            <tr>
                <td>
                    <span class="font-mono text-xs font-semibold bg-karvi-100 px-2 py-1 rounded-lg"><?= e($ref) ?></span>
                </td>
                <td>
                    <div class="font-semibold text-karvi-950"><?= e(invoice_customer_label((string)($contract['customer_details'] ?? ''))) ?></div>
                    <div class="text-xs text-karvi-500 mt-0.5 line-clamp-2"><?= e(mb_strimwidth((string)($contract['customer_details'] ?? ''), 0, 80, '…')) ?></div>
                </td>
                <?php if ($mode === 'pos'): ?>
                <td class="text-sm text-karvi-700"><?= e((string)($contract['contract_line'] ?? '')) ?></td>
                <?php endif; ?>
                <td>
                    <span class="status-badge status-<?= e($contract['status'] ?? 'pending') ?>"><?= e(t_status($contract['status'] ?? 'pending')) ?></span>
                </td>
                <td class="text-karvi-500 text-sm"><?= e(format_date($contract['created_at'] ?? null)) ?></td>
                <td class="text-sm font-medium text-karvi-950"><?= e($totalAmount) ?></td>
                <td>
                    <div class="flex items-center gap-2 flex-wrap">
                        <?php if ($signedPdfReady): ?>
                        <a href="<?= e($signedPdfUrl) ?>" class="btn-secondary !py-1.5 !px-2.5 !text-xs whitespace-nowrap" title="<?= e(__('download_contract')) ?>">
                            <span class="material-symbols-rounded text-base">download</span>
                            <?= e(__('download_contract')) ?>
                        </a>
                        <?php endif; ?>
                        <button type="button" class="btn-secondary !py-1.5 !px-2.5 !text-xs whitespace-nowrap copy-row-btn" data-url="<?= e($url) ?>" title="<?= e(__('copy_link')) ?>">
                            <span class="material-symbols-rounded text-base">content_copy</span>
                            <?= e(__('copy_link')) ?>
                        </button>
                        <button
                            type="button"
                            class="btn-danger !py-1.5 !px-2.5 !text-xs whitespace-nowrap"
                            title="<?= e(__('delete_contract')) ?>"
                            data-delete-contract
                            data-token="<?= e($contract['token'] ?? '') ?>"
                            data-id="<?= e((string)($contract['id'] ?? '')) ?>"
                            data-ref="<?= e($ref) ?>"
                        >
                            <span class="material-symbols-rounded text-base">delete</span>
                            <?= e(__('delete_contract')) ?>
                        </button>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<?php if (!empty($contracts)): ?>
<div id="deleteContractModal" class="admin-modal hidden" role="dialog" aria-modal="true" aria-labelledby="deleteContractModalTitle" data-require-password="<?= $requireDeletePassword ? '1' : '0' ?>">
    <div class="admin-modal-backdrop" data-modal-close></div>
    <div class="admin-modal-dialog">
        <div class="admin-modal-head">
            <h3 id="deleteContractModalTitle" class="font-display font-bold text-lg text-karvi-950"><?= e(__('delete_contract_title')) ?></h3>
            <p class="text-sm text-karvi-500 mt-1"><?= e(__('delete_contract_sub')) ?></p>
            <p class="text-xs font-mono font-semibold text-karvi-700 mt-2" id="deleteContractRef"></p>
        </div>
        <form method="POST" action="<?= e(app_path('/admin/contract/delete')) ?>" class="admin-modal-body" id="deleteContractForm">
            <input type="hidden" name="token" id="deleteContractToken" value="">
            <input type="hidden" name="contract_id" id="deleteContractId" value="">
            <?php if ($requireDeletePassword): ?>
            <label class="form-label" for="deleteContractPassword"><?= e(__('delete_contract_password')) ?></label>
            <input type="password" id="deleteContractPassword" name="password" class="form-input" required autocomplete="off">
            <?php else: ?>
            <p class="text-xs text-amber-800 bg-amber-50 border border-amber-200 rounded-xl p-3 mb-1"><?= e(__('delete_dev_mode_note')) ?></p>
            <?php endif; ?>
            <div class="admin-modal-actions">
                <button type="button" class="btn-secondary" data-modal-cancel><?= e(__('cancel')) ?></button>
                <button type="submit" class="btn-danger" id="deleteContractSubmitBtn">
                    <span class="material-symbols-rounded">delete</span>
                    <?= e($requireDeletePassword ? __('delete_contract_confirm') : __('delete_dev_btn')) ?>
                </button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php
$scripts = ['/assets/js/admin-dashboard.js'];
render_footer(['layout' => 'admin', 'scripts' => $scripts]);
