<?php

declare(strict_types=1);

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

auth_require();

$useApiContracts = api_can_use_partner_api();
$contracts = [];
$apiError = null;

if ($useApiContracts) {
    try {
        $contracts = api_fetch_partner_contracts('partner');
    } catch (Throwable $e) {
        $apiError = api_error_message($e);
    }
} else {
    try {
        $contracts = array_values(array_filter(
            api_all_contracts(),
            'invoice_contract_is_partner_record'
        ));
    } catch (Throwable $e) {
        $apiError = api_error_message($e);
    }
}

render_header('title_dashboard', ['layout' => 'admin', 'page' => 'dashboard']);
render_flash();

auth_start();
$duplicatedLink = $_SESSION['duplicated_contract_link'] ?? null;
unset($_SESSION['duplicated_contract_link']);

$requireDeletePassword = admin_delete_password_required();
$dashboardScripts = ['/assets/js/admin-dashboard.js'];
if ($useApiContracts) {
    $dashboardScripts = [
        '/assets/js/admin-dashboard-contracts.js',
        '/assets/js/admin-dashboard.js',
    ];
}
?>

<?php if ($duplicatedLink): ?>
<div class="link-success-box mb-6 animate-fade-in">
    <div class="flex items-start gap-4 mb-4">
        <div class="w-10 h-10 rounded-xl bg-karvi-950 text-white flex items-center justify-center shrink-0">
            <span class="material-symbols-rounded">content_copy</span>
        </div>
        <div>
            <h3 class="font-display font-bold text-base text-karvi-950"><?= e(__('duplicated_contract_ready')) ?></h3>
            <p class="text-xs text-karvi-500 mt-1"><?= e(__('duplicated_contract_ready_sub')) ?></p>
        </div>
    </div>
    <div class="copy-link-box">
        <input type="text" id="duplicatedContractLink" readonly value="<?= e($duplicatedLink) ?>" class="form-input">
        <button type="button" data-copy="duplicatedContractLink" class="btn-secondary whitespace-nowrap !py-2 !px-3 !text-sm">
            <span class="material-symbols-rounded text-base">content_copy</span>
            <?= e(__('copy_link_btn')) ?>
        </button>
    </div>
</div>
<?php endif; ?>

<?php if ($useApiContracts): ?>
<div id="dashboardApiError" class="hidden mb-6 flex items-start gap-3 p-4 rounded-2xl border border-karvi-950 bg-karvi-950 text-white">
    <span class="material-symbols-rounded shrink-0">cloud_off</span>
    <div>
        <p class="font-semibold text-sm"><?= e(__('api_error_title')) ?></p>
        <p id="dashboardApiErrorText" class="text-sm text-karvi-300 mt-1"></p>
    </div>
</div>
<?php elseif ($apiError): ?>
<div class="mb-6 flex items-start gap-3 p-4 rounded-2xl border border-karvi-950 bg-karvi-950 text-white">
    <span class="material-symbols-rounded shrink-0">cloud_off</span>
    <div>
        <p class="font-semibold text-sm"><?= e(__('api_error_title')) ?></p>
        <p class="text-sm text-karvi-300 mt-1"><?= e($apiError) ?></p>
    </div>
</div>
<?php endif; ?>

<div class="grid grid-cols-1 sm:grid-cols-3 gap-4 sm:gap-6 mb-8">
    <?php if ($useApiContracts): ?>
        <?php stat_card('stat_total', '0', 'description', 'dashboardStatTotal'); ?>
        <?php stat_card('stat_pending', '0', 'hourglass_empty', 'dashboardStatPending'); ?>
        <?php stat_card('stat_signed', '0', 'verified', 'dashboardStatSigned'); ?>
    <?php else: ?>
        <?php
        $total = count($contracts);
        $signed = count(array_filter($contracts, fn($c) => ($c['status'] ?? '') === 'signed'));
        $pending = $total - $signed;
        stat_card('stat_total', (string)$total, 'description');
        stat_card('stat_pending', (string)$pending, 'hourglass_empty');
        stat_card('stat_signed', (string)$signed, 'verified');
        ?>
    <?php endif; ?>
</div>

<?php page_heading('all_contracts', 'all_contracts_sub', '/admin/create', 'nav_new_contract'); ?>

<?php if ($useApiContracts): ?>
<div id="dashboardContractsLoading" class="card mb-4">
    <div class="empty-state !py-10">
        <div class="empty-state-icon">
            <span class="material-symbols-rounded animate-pulse">sync</span>
        </div>
        <p class="text-karvi-500 text-sm"><?= e(__('dashboard_loading_contracts')) ?></p>
    </div>
</div>

<div id="dashboardContractsEmpty" class="hidden card">
    <div class="empty-state">
        <div class="empty-state-icon">
            <span class="material-symbols-rounded">folder_open</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(__('no_contracts_sub')) ?></p>
        <a href="<?= e(app_path('/admin/create')) ?>" class="btn-primary">
            <span class="material-symbols-rounded">add</span>
            <?= e(__('create_first')) ?>
        </a>
    </div>
</div>

<div id="dashboardContractsTableWrap" class="hidden data-table-wrap">
    <table class="data-table">
        <thead>
            <tr>
                <th><?= e(__('col_contract')) ?></th>
                <th><?= e(__('col_partner')) ?></th>
                <th><?= e(__('col_type')) ?></th>
                <th><?= e(__('col_status')) ?></th>
                <th><?= e(__('col_date')) ?></th>
                <th><?= e(__('col_actions')) ?></th>
            </tr>
        </thead>
        <tbody id="dashboardContractsTableBody"></tbody>
    </table>
</div>

<div id="dashboardContractsMobile" class="hidden mobile-cards space-y-4 mt-4"></div>

<script>
window.KARVI_DASHBOARD = <?= json_encode([
    'apiMode' => true,
    'contractsApiUrl' => app_path('/admin/api/contracts'),
    'baseUrl' => app_base_url(),
    'contractUrlBase' => app_absolute_url('/contract'),
    'contractSignUrlBase' => app_absolute_url('/contracts/sign'),
    'contractPathPrefix' => app_path('/contract'),
    'duplicateUrl' => app_path('/admin/contract/duplicate'),
    'contractDetailsUrl' => app_path('/admin/contracts'),
    'deleteUrl' => app_path('/admin/contract/delete'),
    'createUrl' => app_path('/admin/create'),
    'downloadPdfUrl' => app_path('/admin/download'),
    'downloadSignaturesUrl' => app_path('/admin/download-signatures'),
    'labels' => [
        'copy_link' => __('copy_link'),
        'download_contract' => __('download_contract'),
        'download_signatures' => __('download_signatures'),
        'duplicate_contract' => __('duplicate_contract'),
        'view_contract_details' => __('view_contract_details'),
        'edit_contract' => __('edit_contract'),
        'duplicate_contract_confirm' => __('duplicate_contract_confirm'),
        'delete_contract' => __('delete_contract'),
        'api_error_title' => __('api_error_title'),
        'cache_save_error' => __('cache_save_error'),
        'status_pending' => __('status_pending'),
        'status_signing' => __('status_signing'),
        'status_signed' => __('status_signed'),
    ],
], JSON_UNESCAPED_UNICODE) ?>;
</script>

<?php elseif (empty($contracts) && !$apiError): ?>
<div class="card">
    <div class="empty-state">
        <div class="empty-state-icon">
            <span class="material-symbols-rounded">folder_open</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(__('no_contracts_sub')) ?></p>
        <a href="<?= e(app_path('/admin/create')) ?>" class="btn-primary">
            <span class="material-symbols-rounded">add</span>
            <?= e(__('create_first')) ?>
        </a>
    </div>
</div>
<?php elseif (!empty($contracts)): ?>

<div class="data-table-wrap">
    <table class="data-table">
        <thead>
            <tr>
                <th><?= e(__('col_contract')) ?></th>
                <th><?= e(__('col_partner')) ?></th>
                <th><?= e(__('col_type')) ?></th>
                <th><?= e(__('col_status')) ?></th>
                <th><?= e(__('col_date')) ?></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 = contract_reference($contract);
                $isSignedStatus = ($contract['status'] ?? '') === 'signed';
                $signedPdfReady = contract_download_available($contract) || $isSignedStatus;
                $signedPdfUrl = admin_contract_download_url($contract);
                $signaturesReady = contract_signatures_available($contract) || $isSignedStatus;
                $signaturesUrl = admin_contract_signatures_download_url($contract);
            ?>
            <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($contract['restaurant_name'] ?? $contract['partner_name'] ?? '') ?></div>
                    <div class="text-xs text-karvi-500 mt-0.5"><?= e($contract['partner_email'] ?? '') ?></div>
                </td>
                <td><?= e($contract['partner_type'] ?? $contract['partnership_type'] ?? '') ?></td>
                <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>
                    <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; ?>
                        <?php if ($signaturesReady): ?>
                        <a href="<?= e($signaturesUrl) ?>" class="btn-secondary !py-1.5 !px-2.5 !text-xs whitespace-nowrap" title="<?= e(__('download_signatures')) ?>">
                            <span class="material-symbols-rounded text-base">download</span>
                            <?= e(__('download_signatures')) ?>
                        </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>
                        <form method="POST" action="<?= e(app_path('/admin/contract/duplicate')) ?>" class="inline-flex">
                            <input type="hidden" name="token" value="<?= e(contract_admin_token($contract)) ?>">
                            <input type="hidden" name="id" value="<?= e((string)($contract['id'] ?? '')) ?>">
                            <button
                                type="button"
                                class="btn-secondary !py-1.5 !px-2.5 !text-xs whitespace-nowrap"
                                title="<?= e(__('duplicate_contract')) ?>"
                                data-duplicate-contract
                                data-confirm="<?= e(__('duplicate_contract_confirm')) ?>"
                            >
                                <span class="material-symbols-rounded text-base">library_add</span>
                                <?= e(__('duplicate_contract')) ?>
                            </button>
                        </form>
                        <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>

<div class="mobile-cards space-y-4 mt-4">
    <?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 = contract_reference($contract);
        $isSignedStatus = ($contract['status'] ?? '') === 'signed';
        $signedPdfReady = contract_download_available($contract) || $isSignedStatus;
        $signedPdfUrl = admin_contract_download_url($contract);
        $signaturesReady = contract_signatures_available($contract) || $isSignedStatus;
        $signaturesUrl = admin_contract_signatures_download_url($contract);
    ?>
    <div class="contract-card-mobile">
        <div class="flex items-start justify-between gap-3 mb-3">
            <div>
                <span class="font-mono text-xs font-semibold bg-karvi-100 px-2 py-1 rounded-lg"><?= e($ref) ?></span>
                <h3 class="font-semibold text-karvi-950 mt-2"><?= e($contract['restaurant_name'] ?? $contract['partner_name'] ?? '') ?></h3>
                <p class="text-xs text-karvi-500"><?= e($contract['partner_email'] ?? '') ?></p>
            </div>
            <span class="status-badge status-<?= e($contract['status'] ?? 'pending') ?>"><?= e(t_status($contract['status'] ?? 'pending')) ?></span>
        </div>
        <div class="flex items-center justify-between text-sm text-karvi-500 mb-4">
            <span><?= e($contract['partnership_type'] ?? '') ?></span>
            <span><?= e(format_date($contract['created_at'] ?? null)) ?></span>
        </div>
        <div class="copy-link-box">
            <input type="text" readonly value="<?= e($url) ?>" class="form-input !py-2 !text-xs">
            <button type="button" class="btn-secondary !py-2 copy-row-btn" data-url="<?= e($url) ?>">
                <span class="material-symbols-rounded text-base">content_copy</span>
                <?= e(__('copy_link')) ?>
            </button>
        </div>
        <?php if ($signedPdfReady): ?>
        <a href="<?= e($signedPdfUrl) ?>" class="btn-primary w-full mt-3 inline-flex justify-center">
            <span class="material-symbols-rounded">download</span>
            <?= e(__('download_contract')) ?>
        </a>
        <?php endif; ?>
        <?php if ($signaturesReady): ?>
        <a href="<?= e($signaturesUrl) ?>" class="btn-secondary w-full mt-3 inline-flex justify-center">
            <span class="material-symbols-rounded">download</span>
            <?= e(__('download_signatures')) ?>
        </a>
        <?php endif; ?>
        <div class="grid grid-cols-2 gap-2 mt-3">
            <form method="POST" action="<?= e(app_path('/admin/contract/duplicate')) ?>" class="contents">
                <input type="hidden" name="token" value="<?= e(contract_admin_token($contract)) ?>">
                <input type="hidden" name="id" value="<?= e((string)($contract['id'] ?? '')) ?>">
                <button
                    type="button"
                    class="btn-secondary w-full inline-flex justify-center"
                    data-duplicate-contract
                    data-confirm="<?= e(__('duplicate_contract_confirm')) ?>"
                >
                    <span class="material-symbols-rounded">library_add</span>
                    <?= e(__('duplicate_contract')) ?>
                </button>
            </form>
            <button
                type="button"
                class="btn-danger w-full inline-flex justify-center"
                data-delete-contract
                data-token="<?= e($contract['token'] ?? '') ?>"
                data-id="<?= e((string)($contract['id'] ?? '')) ?>"
                data-ref="<?= e($ref) ?>"
            >
                <span class="material-symbols-rounded">delete</span>
                <?= e(__('delete_contract')) ?>
            </button>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php endif; ?>

<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 render_footer(['layout' => 'admin', 'scripts' => $dashboardScripts]); ?>
