<?php
/** @var RayanPanelService $rayanService */
$rows = $requestData['rows'] ?? [];
$clubCounts = $requestData['club_counts'] ?? [];
$statusCounts = $requestData['status_counts'] ?? [];
$userCounts = $requestData['user_counts'] ?? [];
$isAdminView = !empty($requestData['is_admin_view']);
$pagination = $requestData['pagination'] ?? [
    'page' => 1,
    'per_page' => 25,
    'total' => count($rows),
    'last_page' => 1,
    'from' => count($rows) ? 1 : 0,
    'to' => count($rows),
];
$statusOptions = [
    '' => 'همه وضعیت‌ها',
    'new' => 'آماده ثبت',
    'awaiting_otp' => 'منتظر کد تایید',
    'external_done' => 'مرحله اول انجام شد',
    'hesaban_done' => 'مرحله دوم انجام شد',
    'completed' => 'تکمیل شده',
    'failed' => 'ناموفق',
    'invalid' => 'اطلاعات ناقص',
    'ignored' => 'نادیده گرفته شده',
    'processing' => 'در حال پردازش',
];
$sourceModeOptions = ['فروش کالا مشتریان', 'انبار خودم', 'از همکار خریدم'];
$perPageOptions = [10, 25, 50, 100];
$currentPage = max(1, (int)($pagination['page'] ?? 1));
$lastPage = max(1, (int)($pagination['last_page'] ?? 1));
$columnFilters = is_array($filters['col'] ?? null) ? (array)$filters['col'] : [];
$dateFilterKeys = ['created_from', 'created_to', 'submitted_from', 'submitted_to'];
$queryBase = [
    'club' => (string)($filters['club'] ?? ''),
    'status' => (string)($filters['status'] ?? ''),
    'created_by' => (string)($filters['created_by'] ?? ''),
    'q' => (string)($filters['q'] ?? ''),
    'created_from' => (string)($filters['created_from'] ?? ''),
    'created_to' => (string)($filters['created_to'] ?? ''),
    'submitted_from' => (string)($filters['submitted_from'] ?? ''),
    'submitted_to' => (string)($filters['submitted_to'] ?? ''),
    'col' => $columnFilters,
    'per_page' => (int)($pagination['per_page'] ?? 25),
];
$paginationWindowStart = max(1, $currentPage - 2);
$paginationWindowEnd = min($lastPage, $currentPage + 2);
$manualFormOpen = (string)($_GET['new'] ?? '') === '1';
$manualSettings = is_array($manualSettings ?? null) ? $manualSettings : $rayanService->getManualFormSettings();
$salesPlanOptions = array_values((array)($manualSettings['sales_plans'] ?? []));
$productOptions = array_values((array)($manualSettings['products'] ?? []));
$reportColumns = $rayanService->requestReportColumns();
$amountFieldVisible = $rayanService->requestAmountFieldVisibility();
$hiddenAmountColumnKeys = [];
foreach (['installment_amount', 'sales_amount', 'purchase_amount'] as $amountColumnKey) {
    if (empty($amountFieldVisible[$amountColumnKey])) {
        $hiddenAmountColumnKeys[$amountColumnKey] = true;
        unset($reportColumns[$amountColumnKey]);
    }
}
$canDeleteReports = $isAdminView;
$emptyColspan = count($reportColumns) + 1 + ($canDeleteReports ? 1 : 0);
$selected = static fn($a, $b): string => (string)$a === (string)$b ? 'selected' : '';
$actorReportLabel = static function (string $username, string $displayName, string $fallback = '-'): string {
    $username = trim($username);
    $displayName = trim($displayName);
    if ($displayName === 'مدیر اصلی') {
        return 'مدیر اصلی';
    }
    if ($username !== '') {
        return $username;
    }
    if ($displayName !== '') {
        return $displayName;
    }
    return $fallback;
};
?>

<a class="fab-new-request" href="<?= e(url('rayan-requests', ['new' => 1])) ?>#manual-request-form">ثبت فاکتور جدید</a>

<details class="card manual-request-card" id="manual-request-form" <?= $manualFormOpen ? 'open' : '' ?>>
    <summary><span>ثبت فاکتور جدید</span></summary>

    <form method="post" class="manual-request-form async-task-form" data-task="rayan_manual_create" data-return-page="rayan-requests" data-progress-title="ثبت فاکتور جدید">
        <input type="hidden" name="action" value="create_manual_request">

        <div class="manual-section-title">اطلاعات مشتری</div>
        <div class="form-grid manual-grid">
            <label>طرح فروش *
                <select name="club_level" required>
                    <option value="">انتخاب طرح فروش</option>
                    <?php foreach ($salesPlanOptions as $plan): ?>
                        <?php $planName = is_array($plan) ? (string)($plan['name'] ?? '') : (string)$plan; ?>
                        <?php if (trim($planName) !== ''): ?>
                            <option value="<?= e($planName) ?>"><?= e($planName) ?></option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </label>
            <label>نام مشتری *
                <input type="text" name="buyer_name" required>
            </label>
            <label>کد ملی *
                <input type="text" name="national_id" inputmode="numeric" maxlength="10" required>
            </label>
            <label>موبایل *
                <input type="text" name="mobile" inputmode="numeric" maxlength="11" required>
            </label>
        </div>

        <div class="manual-section-title">کالا و مبالغ</div>
        <div class="form-grid manual-grid">
            <label>نام کالا *
                <select name="product_code" required <?= empty($productOptions) ? 'disabled' : '' ?>>
                    <option value=""><?= empty($productOptions) ? 'کالا تعریف نشده' : 'انتخاب کالا' ?></option>
                    <?php foreach ($productOptions as $product): ?>
                        <?php
                            $productTitle = is_array($product) ? (string)($product['title'] ?? '') : '';
                            $productCode = is_array($product) ? (string)($product['code'] ?? '') : '';
                        ?>
                        <?php if (trim($productTitle) !== '' && trim($productCode) !== ''): ?>
                            <option value="<?= e($productCode) ?>"><?= e($productTitle) ?></option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </label>
            <?php if (!empty($amountFieldVisible['installment_amount'])): ?>
            <label>مبلغ خرید اعتباری / با سود
                <input type="text" name="installment_amount" inputmode="numeric">
            </label>
            <?php endif; ?>
            <?php if (!empty($amountFieldVisible['sales_amount'])): ?>
            <label>مبلغ فاکتور فروش حسابان‌وب
                <input type="text" name="sales_amount" inputmode="numeric">
            </label>
            <?php endif; ?>
            <?php if (!empty($amountFieldVisible['purchase_amount'])): ?>
            <label>مبلغ خرید حسابان‌وب
                <input type="text" name="purchase_amount" inputmode="numeric">
            </label>
            <?php endif; ?>
        </div>

        <div class="manual-section-title">آدرس و تأمین کالا</div>
        <div class="form-grid manual-grid">
            <label>کد پستی
                <input type="text" name="postal_code" inputmode="numeric" maxlength="10">
            </label>
            <label>روش تأمین کالا
                <select name="source_mode">
                    <?php foreach ($sourceModeOptions as $option): ?>
                        <option value="<?= e($option) ?>"><?= e($option) ?></option>
                    <?php endforeach; ?>
                </select>
            </label>
            <label>خرید از فروشگاه / همکار
                <input type="text" name="seller_store_title">
            </label>
            <label class="manual-full">آدرس
                <textarea name="address" rows="3"></textarea>
            </label>
        </div>

        <div class="actions manual-actions">
            <button class="btn btn-success" type="submit">ایجاد فرم ثبت فاکتور</button>
            <a class="btn secondary" href="<?= e(url('rayan-requests')) ?>">بستن</a>
        </div>
    </form>
</details>

<div class="grid two">
    <div class="card compact-card">
        <h3>نوع طرح</h3>
        <div class="pill-wrap">
            <a class="pill <?= trim((string)($filters['club'] ?? '')) === '' ? 'active' : '' ?>" href="<?= e(url('rayan-requests')) ?>">همه</a>
            <?php foreach ($clubCounts as $item): ?>
                <a class="pill <?= ($filters['club'] ?? '') === ($item['club_level'] ?? '') ? 'active' : '' ?>" href="<?= e(url('rayan-requests', ['club' => (string)$item['club_level'], 'per_page' => (int)($pagination['per_page'] ?? 25)])) ?>">
                    <?= e((string)$item['club_level']) ?> <span><?= e((string)$item['cnt']) ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    <div class="card compact-card">
        <h3>وضعیت</h3>
        <div class="pill-wrap">
            <?php foreach ($statusCounts as $item): ?>
                <span class="pill muted-pill"><?= e($rayanService->statusLabel((string)$item['status'])) ?> <span><?= e((string)$item['cnt']) ?></span></span>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<?php if ($isAdminView): ?>
<div class="card compact-card">
    <h3>ثبت‌کننده</h3>
    <div class="pill-wrap">
        <a class="pill <?= trim((string)($filters['created_by'] ?? '')) === '' ? 'active' : '' ?>" href="<?= e(url('rayan-requests')) ?>">همه</a>
        <?php foreach ($userCounts as $item): ?>
            <?php $userKey = (string)($item['user_key'] ?? ''); ?>
            <a class="pill <?= (string)($filters['created_by'] ?? '') === $userKey ? 'active' : '' ?>" href="<?= e(url('rayan-requests', ['created_by' => $userKey, 'per_page' => (int)($pagination['per_page'] ?? 25)])) ?>">
                <?= e((string)($item['user_label'] ?? '-')) ?> <span><?= e((string)($item['cnt'] ?? 0)) ?></span>
            </a>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<div class="card filters-card">
    <form method="get" id="rayan-filter-form" class="filters-row rayan-filters-row advanced-rayan-filters">
        <input type="hidden" name="page" value="rayan-requests">
        <input type="text" name="q" value="<?= e((string)($filters['q'] ?? '')) ?>" placeholder="جستجوی کلی">
        <select name="status">
            <?php foreach ($statusOptions as $value => $label): ?>
                <option value="<?= e($value) ?>" <?= (string)($filters['status'] ?? '') === $value ? 'selected' : '' ?>><?= e($label) ?></option>
            <?php endforeach; ?>
        </select>
        <input type="text" name="club" value="<?= e((string)($filters['club'] ?? '')) ?>" placeholder="طرح فروش">
        <?php if ($isAdminView): ?>
            <select name="created_by">
                <option value="">همه ثبت‌کننده‌ها</option>
                <?php foreach ($userCounts as $item): ?>
                    <?php $userKey = (string)($item['user_key'] ?? ''); ?>
                    <option value="<?= e($userKey) ?>" <?= (string)($filters['created_by'] ?? '') === $userKey ? 'selected' : '' ?>><?= e((string)($item['user_label'] ?? '-')) ?> (<?= e((string)($item['cnt'] ?? 0)) ?>)</option>
                <?php endforeach; ?>
            </select>
        <?php endif; ?>
        <input type="text" name="created_from" value="<?= e((string)($filters['created_from'] ?? '')) ?>" placeholder="از تاریخ ایجاد؛ مثلا 1405/02/23 یا 1405/02/23 21:15" title="فرمت مجاز: 1405/02/23 یا 1405/02/23 21:15">
        <input type="text" name="created_to" value="<?= e((string)($filters['created_to'] ?? '')) ?>" placeholder="تا تاریخ ایجاد؛ مثلا 1405/02/23 یا 1405/02/23 21:15" title="فرمت مجاز: 1405/02/23 یا 1405/02/23 21:15">
        <input type="text" name="submitted_from" value="<?= e((string)($filters['submitted_from'] ?? '')) ?>" placeholder="از ثبت نهایی؛ مثلا 1405/02/23 یا 1405/02/23 21:15" title="فرمت مجاز: 1405/02/23 یا 1405/02/23 21:15">
        <input type="text" name="submitted_to" value="<?= e((string)($filters['submitted_to'] ?? '')) ?>" placeholder="تا ثبت نهایی؛ مثلا 1405/02/23 یا 1405/02/23 21:15" title="فرمت مجاز: 1405/02/23 یا 1405/02/23 21:15">
        <select name="per_page">
            <?php foreach ($perPageOptions as $option): ?>
                <option value="<?= e((string)$option) ?>" <?= (int)($pagination['per_page'] ?? 25) === $option ? 'selected' : '' ?>><?= e((string)$option) ?> ردیف</option>
            <?php endforeach; ?>
        </select>
        <button class="btn" type="submit">فیلتر</button>
        <a class="btn secondary" href="<?= e(url('rayan-requests')) ?>">حذف فیلتر</a>
    </form>
</div>

<div class="card wide-card requests-card">
    <div class="table-head-actions">
        <div>
            <h3><?= $isAdminView ? 'همه ثبت فاکتورها' : 'ثبت فاکتورهای من' ?></h3>
            <p class="muted">نمایش <?= e(number_format((int)($pagination['from'] ?? 0))) ?> تا <?= e(number_format((int)($pagination['to'] ?? 0))) ?> از <?= e(number_format((int)($pagination['total'] ?? 0))) ?></p>
        </div>
        <div class="actions table-toolbar-actions">
            <a class="btn btn-success" href="<?= e(url('rayan-requests', ['new' => 1])) ?>#manual-request-form">ثبت فاکتور جدید</a>
            <?php if ($isAdminView): ?>
                <a class="btn secondary" href="<?= e(url('rayan-requests', array_merge($queryBase, ['export' => 'excel']))) ?>">خروجی اکسل</a>
            <?php endif; ?>
            <details class="column-controls" id="rayan-column-controls">
                <summary class="btn secondary">اصلاح نمایش ستون‌ها</summary>
                <div class="column-controls-panel">
                    <div class="column-controls-top">
                        <strong>اصلاح نمایش ستون‌ها</strong>
                        <button class="btn small secondary" type="button" data-column-reset>بازنشانی</button>
                    </div>
                    <div class="column-controls-list">
                        <?php foreach ($reportColumns as $columnKey => $columnTitle): ?>
                            <div class="column-control-row" data-col-control="<?= e($columnKey) ?>">
                                <label>
                                    <input type="checkbox" data-column-toggle="<?= e($columnKey) ?>" checked>
                                    <span><?= e($columnTitle) ?></span>
                                </label>
                                <div class="column-control-buttons">
                                    <button type="button" class="btn small secondary" data-column-move="right" data-column="<?= e($columnKey) ?>">راست</button>
                                    <button type="button" class="btn small secondary" data-column-move="left" data-column="<?= e($columnKey) ?>">چپ</button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </details>
            <?php if ($isAdminView): ?>
                <a class="btn secondary" href="<?= e(url('rayan-form-settings')) ?>">تنظیمات فرم</a>
            <?php endif; ?>
            <?php if ($canDeleteReports): ?>
                <form id="bulk-delete-form" method="post" onsubmit="return confirm('درخواست‌های انتخاب‌شده حذف شوند؟');">
                    <input type="hidden" name="action" value="delete_selected">
                    <button class="btn danger" type="submit">حذف انتخاب‌شده‌ها</button>
                </form>
            <?php endif; ?>
        </div>
    </div>

    <div class="table-wrap rayan-table-wrap">
        <table class="rayan-requests-table full-fields-table">
            <thead>
            <tr>
                <?php if ($canDeleteReports): ?>
                    <th data-col="select" class="select-col"><input type="checkbox" id="select-all-requests" aria-label="انتخاب همه"></th>
                <?php endif; ?>
                <th data-col="id" data-configurable="1" class="col-id">#</th>
                <th data-col="form_id" data-configurable="1" class="col-form-id">شماره فرم</th>
                <th data-col="created_at" data-configurable="1" class="col-date">تاریخ ایجاد</th>
                <th data-col="owner" data-configurable="1" class="col-owner">ایجادکننده</th>
                <th data-col="submitter" data-configurable="1" class="col-submitter">ثبت نهایی توسط</th>
                <th data-col="submitted_at" data-configurable="1" class="col-submitted-at">زمان ثبت نهایی</th>
                <th data-col="plan" data-configurable="1" class="col-plan">طرح فروش</th>
                <th data-col="final" data-configurable="1" class="col-final">تایید</th>
                <th data-col="status" data-configurable="1" class="col-status">وضعیت</th>
                <th data-col="customer" data-configurable="1" class="col-name">نام مشتری</th>
                <th data-col="national" data-configurable="1" class="col-national">کد ملی</th>
                <th data-col="mobile" data-configurable="1" class="col-mobile">موبایل</th>
                <th data-col="product" data-configurable="1" class="col-product">نام کالا</th>
                <?php if (!empty($amountFieldVisible['installment_amount'])): ?><th data-col="installment_amount" data-configurable="1" class="col-money">مبلغ خرید اعتباری / با سود</th><?php endif; ?>
                <?php if (!empty($amountFieldVisible['sales_amount'])): ?><th data-col="sales_amount" data-configurable="1" class="col-money">مبلغ فروش حسابان‌وب</th><?php endif; ?>
                <?php if (!empty($amountFieldVisible['purchase_amount'])): ?><th data-col="purchase_amount" data-configurable="1" class="col-money">مبلغ خرید حسابان‌وب</th><?php endif; ?>
                <th data-col="postal" data-configurable="1" class="col-postal">کد پستی</th>
                <th data-col="source_mode" data-configurable="1" class="col-source-mode">روش تأمین کالا</th>
                <th data-col="store" data-configurable="1" class="col-store">خرید از فروشگاه / همکار</th>
                <th data-col="address" data-configurable="1" class="col-address">آدرس</th>
                <th data-col="step" data-configurable="1" class="col-step">مرحله</th>
                <th data-col="error" data-configurable="1" class="col-error">خطا</th>
                <th data-col="tracking" data-configurable="1" class="col-tracking">کد پیگیری</th>
                <th data-col="actions" class="col-actions">عملیات</th>
            </tr>
            <tr class="column-filter-row">
                <?php if ($canDeleteReports): ?>
                    <th data-col="select" class="select-col"></th>
                <?php endif; ?>
                <?php foreach ($reportColumns as $columnKey => $columnTitle): ?>
                    <?php
                        $filterType = 'text';
                        $filterPlaceholder = in_array($columnKey, ['created_at', 'submitted_at'], true) ? 'مثلا 1405/02/23 یا 1405/02/23 21:15' : 'فیلتر';
                    ?>
                    <th data-col="<?= e($columnKey) ?>" data-configurable="1" class="column-filter-cell">
                        <input
                            form="rayan-filter-form"
                            type="<?= e($filterType) ?>"
                            name="col[<?= e($columnKey) ?>]"
                            value="<?= e((string)($columnFilters[$columnKey] ?? '')) ?>"
                            placeholder="<?= e($filterPlaceholder) ?>"
                            aria-label="فیلتر <?= e($columnTitle) ?>"
                            title="<?= in_array($columnKey, ['created_at', 'submitted_at'], true) ? e('فرمت مجاز: 1405/02/23 یا 1405/02/23 21:15') : e('فیلتر متنی') ?>"
                        >
                    </th>
                <?php endforeach; ?>
                <th data-col="actions" class="column-filter-actions">
                    <button form="rayan-filter-form" class="btn small" type="submit">اعمال</button>
                </th>
            </tr>
            </thead>
            <tbody>
            <?php if (empty($rows)): ?>
                <tr><td colspan="<?= e((string)$emptyColspan) ?>" class="muted center">درخواستی ثبت نشده است.</td></tr>
            <?php endif; ?>
            <?php foreach ($rows as $row): ?>
                <?php
                    $status = (string)($row['status'] ?? '');
                    $statusClass = 'status-' . preg_replace('/[^a-z0-9_\-]/i', '', $status);
                    $rowId = (int)($row['id'] ?? 0);
                    $source = (string)($row['source'] ?? 'webhook');
                    $formValues = is_array($row['_manual_values'] ?? null) ? (array)$row['_manual_values'] : $rayanService->getManualRequestFormValues($row);
                    $provider = rayanResolveRequestProvider($rayanService->config(), (string)($row['club_level'] ?? ''));
                    $isCoreClubRow = in_array($provider, ['rayan', 'minipay_direct'], true);
                    $hasExternalSuccess = $isCoreClubRow && (
                        $status === 'external_done'
                        || $status === 'completed'
                        || trim((string)($row['minipay_tracking_code'] ?? '')) !== ''
                        || (int)($row['minipay_invoice_id'] ?? 0) > 0
                        || (int)($row['minipay_transaction_id'] ?? 0) > 0
                    );
                    $hasHesabanInvoiceSuccess = $rayanService->requestHasSuccessfulHesabanInvoices($row);
                    $isFullyRegistered = $isCoreClubRow
                        ? ($hasExternalSuccess && $hasHesabanInvoiceSuccess)
                        : ($hasHesabanInvoiceSuccess || $status === 'completed');
                    $isBusyForStageAction = in_array($status, ['processing', 'awaiting_otp'], true);
                    $canStartStageOne = $isCoreClubRow && !$hasExternalSuccess && !$isBusyForStageAction;
                    $canSeeStageOne = $canStartStageOne;
                    $canRunStageOne = $canStartStageOne;
                    // مرحله دوم برای مدیر مستقل از مرحله اول است؛ اگر فاکتورهای حسابان‌وب هنوز ثبت نشده‌اند، مدیر می‌تواند آن را جداگانه اجرا کند.
                    $canSeeStageTwo = $isAdminView && $isCoreClubRow && !$hasHesabanInvoiceSuccess;
                    $canRunStageTwo = $isAdminView && $isCoreClubRow && $status !== 'processing' && !$hasHesabanInvoiceSuccess;
                    $canProcessHesabanOnly = $isAdminView && !$isCoreClubRow && in_array($status, ['new'], true) && !$isFullyRegistered;
                    $canRetry = ($isAdminView && !$isCoreClubRow && in_array($status, ['failed'], true) && !$hasHesabanInvoiceSuccess);
                    $needsOtp = $isCoreClubRow && $status === 'awaiting_otp';
                    $canEdit = $rayanService->canEditManualRequest($row);
                    $canDeleteRow = $rayanService->canDeleteRequest($row);

                    $buyerName = trim((string)($formValues['buyer_name'] ?? $row['buyer_name'] ?? ''));
                    $productDisplay = trim((string)($formValues['product_name'] ?? $row['product_name'] ?? ''));
                    $installmentDisplay = trim((string)($formValues['installment_amount'] ?? $row['installment_amount'] ?? ''));
                    $salesDisplay = trim((string)($formValues['sales_amount'] ?? ''));
                    $purchaseDisplay = trim((string)($formValues['purchase_amount'] ?? ''));
                    $postalDisplay = trim((string)($formValues['postal_code'] ?? $row['postal_code'] ?? ''));
                    $sourceModeDisplay = trim((string)($formValues['source_mode'] ?? ''));
                    $sellerStoreDisplay = trim((string)($formValues['seller_store_title'] ?? ''));
                    $addressDisplay = trim((string)($formValues['address'] ?? $row['address'] ?? ''));

                    $createdBy = trim((string)($row['created_by'] ?? ''));
                    $createdByDisplay = trim((string)($row['created_by_display'] ?? ''));
                    $ownerLabel = $actorReportLabel($createdBy, $createdByDisplay, 'وبهوک / فرم‌افزار');

                    $submittedBy = trim((string)($row['submitted_by'] ?? ''));
                    $submittedByDisplay = trim((string)($row['submitted_by_display'] ?? ''));
                    $submittedAt = trim((string)($row['submitted_at'] ?? ''));
                    $submitterLabel = $actorReportLabel($submittedBy, $submittedByDisplay, '-');
                ?>
                <tr>
                    <?php if ($canDeleteReports): ?>
                    <td data-col="select" class="select-col">
                        <input type="checkbox" class="request-row-checkbox" form="bulk-delete-form" name="request_ids[]" value="<?= e((string)$rowId) ?>" aria-label="انتخاب درخواست <?= e((string)$rowId) ?>">
                    </td>
                    <?php endif; ?>
                    <td data-col="id" class="col-id"><strong><?= e((string)$rowId) ?></strong></td>
                    <td data-col="form_id" class="col-form-id"><?= e((string)($row['form_entry_id'] ?? '-')) ?></td>
                    <td data-col="created_at" class="col-date"><?= e($rayanService->formatJalaliDateTime((string)($row['created_at'] ?? ''))) ?></td>
                    <td data-col="owner" class="col-owner"><?= e($ownerLabel) ?></td>
                    <td data-col="submitter" class="col-submitter"><?= e($submitterLabel) ?></td>
                    <td data-col="submitted_at" class="col-submitted-at"><?= e($submittedAt !== '' ? $rayanService->formatJalaliDateTime($submittedAt) : '-') ?></td>
                    <td data-col="plan" class="col-plan"><strong><?= e((string)($row['club_level'] ?? '-')) ?></strong></td>
                    <td data-col="final" class="col-final"><?= e((string)($row['final_status'] ?? '-')) ?></td>
                    <td data-col="status" class="col-status"><span class="status-badge <?= e($statusClass) ?>"><?= e($rayanService->statusLabel($status)) ?></span></td>
                    <td data-col="customer" class="col-name"><strong><?= e($buyerName !== '' ? $buyerName : '-') ?></strong></td>
                    <td data-col="national" class="col-national"><?= e((string)($row['national_id'] ?? '-')) ?></td>
                    <td data-col="mobile" class="col-mobile"><?= e((string)($row['mobile'] ?? '-')) ?></td>
                    <td data-col="product" class="col-product"><?= e($productDisplay !== '' ? $productDisplay : '-') ?></td>
                    <?php if (!empty($amountFieldVisible['installment_amount'])): ?><td data-col="installment_amount" class="col-money"><?= e($installmentDisplay !== '' ? rayanFormatMoney($installmentDisplay) : '-') ?></td><?php endif; ?>
                    <?php if (!empty($amountFieldVisible['sales_amount'])): ?><td data-col="sales_amount" class="col-money"><?= e($salesDisplay !== '' ? rayanFormatMoney($salesDisplay) : '-') ?></td><?php endif; ?>
                    <?php if (!empty($amountFieldVisible['purchase_amount'])): ?><td data-col="purchase_amount" class="col-money"><?= e($purchaseDisplay !== '' ? rayanFormatMoney($purchaseDisplay) : '-') ?></td><?php endif; ?>
                    <td data-col="postal" class="col-postal"><?= e($postalDisplay !== '' ? $postalDisplay : '-') ?></td>
                    <td data-col="source_mode" class="col-source-mode"><?= e($sourceModeDisplay !== '' ? $sourceModeDisplay : '-') ?></td>
                    <td data-col="store" class="col-store"><?= e($sellerStoreDisplay !== '' ? $sellerStoreDisplay : '-') ?></td>
                    <td data-col="address" class="col-address cell-long"><?= e($addressDisplay !== '' ? $addressDisplay : '-') ?></td>
                    <td data-col="step" class="col-step cell-long"><?= e((string)($row['last_step'] ?? '-')) ?></td>
                    <td data-col="error" class="col-error cell-long"><?= e(trim((string)($row['error_message'] ?? '')) !== '' ? (string)$row['error_message'] : '-') ?></td>
                    <td data-col="tracking" class="col-tracking"><?= e(trim((string)($row['minipay_tracking_code'] ?? '')) !== '' ? (string)$row['minipay_tracking_code'] : '-') ?></td>
                    <td data-col="actions" class="actions-cell col-actions">
                        <?php if ($canEdit): ?>
                            <button class="btn small secondary request-edit-toggle" type="button" data-edit-target="request-edit-<?= e((string)$rowId) ?>">ویرایش</button>
                        <?php endif; ?>
                        <?php if ($isCoreClubRow): ?>
                            <?php if ($canSeeStageOne): ?>
                                <form method="post" class="async-task-form inline-form" data-task="rayan_process" data-return-page="rayan-requests" data-progress-title="ثبت مرحله اول درخواست <?= e((string)$rowId) ?>">
                                    <input type="hidden" name="action" value="process_stage_one">
                                    <input type="hidden" name="request_id" value="<?= e((string)$rowId) ?>">
                                    <button class="btn small" type="submit" <?= $canRunStageOne ? '' : 'disabled title="مرحله اول قبلاً انجام شده یا فعلاً قابل اجرا نیست."' ?>>ثبت مرحله اول</button>
                                </form>
                            <?php endif; ?>
                            <?php if ($canSeeStageTwo): ?>
                                <form method="post" class="async-task-form inline-form" data-task="rayan_process" data-return-page="rayan-requests" data-progress-title="ثبت مرحله دوم درخواست <?= e((string)$rowId) ?>">
                                    <input type="hidden" name="action" value="process_stage_two">
                                    <input type="hidden" name="request_id" value="<?= e((string)$rowId) ?>">
                                    <button class="btn small btn-success" type="submit" <?= $canRunStageTwo ? '' : 'disabled title="در حال پردازش است یا فاکتورهای حسابان‌وب قبلاً ثبت شده‌اند."' ?>>ثبت مرحله دوم</button>
                                </form>
                            <?php endif; ?>
                        <?php elseif ($canProcessHesabanOnly): ?>
                            <form method="post" class="async-task-form inline-form" data-task="rayan_process" data-return-page="rayan-requests" data-progress-title="ثبت فاکتور درخواست <?= e((string)$rowId) ?>">
                                <input type="hidden" name="action" value="process_request">
                                <input type="hidden" name="request_id" value="<?= e((string)$rowId) ?>">
                                <button class="btn small" type="submit">ثبت فاکتور</button>
                            </form>
                        <?php endif; ?>
                        <?php if ($canRetry): ?>
                            <form method="post" class="async-task-form inline-form" data-task="rayan_retry" data-return-page="rayan-requests" data-progress-title="تلاش مجدد درخواست <?= e((string)$rowId) ?>">
                                <input type="hidden" name="action" value="retry_request">
                                <input type="hidden" name="request_id" value="<?= e((string)$rowId) ?>">
                                <button class="btn small warning" type="submit">تلاش مجدد</button>
                            </form>
                        <?php endif; ?>
                        <?php if ($needsOtp): ?>
                            <form method="post" class="async-task-form otp-form" data-task="rayan_submit_otp" data-return-page="rayan-requests" data-progress-title="ارسال کد تایید درخواست <?= e((string)$rowId) ?>">
                                <input type="hidden" name="action" value="submit_otp">
                                <input type="hidden" name="request_id" value="<?= e((string)$rowId) ?>">
                                <input type="text" name="otp_code" inputmode="numeric" placeholder="کد تایید" required>
                                <button class="btn small" type="submit">ثبت کد</button>
                            </form>
                        <?php endif; ?>
                        <?php if ($canDeleteRow): ?>
                            <form method="post" class="inline-form" onsubmit="return confirm('درخواست #<?= e((string)$rowId) ?> حذف شود؟');">
                                <input type="hidden" name="action" value="delete_request">
                                <input type="hidden" name="request_id" value="<?= e((string)$rowId) ?>">
                                <button class="btn small danger" type="submit">حذف</button>
                            </form>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php if ($canEdit): ?>
                    <tr class="request-edit-row" id="request-edit-<?= e((string)$rowId) ?>" hidden>
                        <td colspan="<?= e((string)$emptyColspan) ?>">
                            <div class="request-edit-panel">
                                <form method="post" class="manual-request-form edit-request-form">
                                    <input type="hidden" name="action" value="update_manual_request">
                                    <input type="hidden" name="request_id" value="<?= e((string)$rowId) ?>">
                                    <div class="form-grid manual-grid compact-edit-grid">
                                        <label>طرح فروش *
                                            <select name="club_level" required>
                                                <option value="">انتخاب طرح فروش</option>
                                                <?php foreach ($salesPlanOptions as $plan): ?>
                                                    <?php $planName = is_array($plan) ? (string)($plan['name'] ?? '') : (string)$plan; ?>
                                                    <?php if (trim($planName) !== ''): ?>
                                                        <option value="<?= e($planName) ?>" <?= $selected($formValues['club_level'] ?? '', $planName) ?>><?= e($planName) ?></option>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            </select>
                                        </label>
                                        <label>نام مشتری *
                                            <input type="text" name="buyer_name" value="<?= e((string)($formValues['buyer_name'] ?? '')) ?>" required>
                                        </label>
                                        <label>کد ملی *
                                            <input type="text" name="national_id" inputmode="numeric" maxlength="10" value="<?= e((string)($formValues['national_id'] ?? '')) ?>" required>
                                        </label>
                                        <label>موبایل *
                                            <input type="text" name="mobile" inputmode="numeric" maxlength="11" value="<?= e((string)($formValues['mobile'] ?? '')) ?>" required>
                                        </label>
                                        <label>نام کالا *
                                            <select name="product_code" required>
                                                <option value="">انتخاب کالا</option>
                                                <?php foreach ($productOptions as $product): ?>
                                                    <?php
                                                        $productTitle = is_array($product) ? (string)($product['title'] ?? '') : '';
                                                        $productCode = is_array($product) ? (string)($product['code'] ?? '') : '';
                                                    ?>
                                                    <?php if (trim($productTitle) !== '' && trim($productCode) !== ''): ?>
                                                        <option value="<?= e($productCode) ?>" <?= $selected($formValues['product_code'] ?? '', $productCode) ?>><?= e($productTitle) ?></option>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            </select>
                                        </label>
                                        <?php if (!empty($amountFieldVisible['installment_amount'])): ?>
                                        <label>مبلغ خرید اعتباری / با سود
                                            <input type="text" name="installment_amount" inputmode="numeric" value="<?= e((string)($formValues['installment_amount'] ?? '')) ?>">
                                        </label>
                                        <?php endif; ?>
                                        <?php if (!empty($amountFieldVisible['sales_amount'])): ?>
                                        <label>مبلغ فاکتور فروش حسابان‌وب
                                            <input type="text" name="sales_amount" inputmode="numeric" value="<?= e((string)($formValues['sales_amount'] ?? '')) ?>">
                                        </label>
                                        <?php endif; ?>
                                        <?php if (!empty($amountFieldVisible['purchase_amount'])): ?>
                                        <label>مبلغ خرید حسابان‌وب
                                            <input type="text" name="purchase_amount" inputmode="numeric" value="<?= e((string)($formValues['purchase_amount'] ?? '')) ?>">
                                        </label>
                                        <?php endif; ?>
                                        <label>کد پستی
                                            <input type="text" name="postal_code" inputmode="numeric" maxlength="10" value="<?= e((string)($formValues['postal_code'] ?? '')) ?>">
                                        </label>
                                        <label>روش تأمین کالا
                                            <select name="source_mode">
                                                <?php foreach ($sourceModeOptions as $option): ?>
                                                    <option value="<?= e($option) ?>" <?= $selected($formValues['source_mode'] ?? '', $option) ?>><?= e($option) ?></option>
                                                <?php endforeach; ?>
                                                <?php if (trim((string)($formValues['source_mode'] ?? '')) !== '' && !in_array((string)$formValues['source_mode'], $sourceModeOptions, true)): ?>
                                                    <option value="<?= e((string)$formValues['source_mode']) ?>" selected><?= e((string)$formValues['source_mode']) ?></option>
                                                <?php endif; ?>
                                            </select>
                                        </label>
                                        <label>خرید از فروشگاه / همکار
                                            <input type="text" name="seller_store_title" value="<?= e((string)($formValues['seller_store_title'] ?? '')) ?>">
                                        </label>
                                        <label class="manual-full">آدرس
                                            <textarea name="address" rows="2"><?= e((string)($formValues['address'] ?? '')) ?></textarea>
                                        </label>
                                    </div>
                                    <div class="actions manual-actions">
                                        <button class="btn btn-success small" type="submit">ذخیره ویرایش</button>
                                    </div>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endif; ?>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <?php if ($lastPage > 1): ?>
        <div class="pagination-row">
            <a class="pagination-btn <?= $currentPage <= 1 ? 'disabled' : '' ?>" href="<?= e(url('rayan-requests', array_merge($queryBase, ['p' => max(1, $currentPage - 1)]))) ?>">قبلی</a>

            <?php if ($paginationWindowStart > 1): ?>
                <a class="pagination-btn" href="<?= e(url('rayan-requests', array_merge($queryBase, ['p' => 1]))) ?>">1</a>
                <?php if ($paginationWindowStart > 2): ?><span class="pagination-dots">...</span><?php endif; ?>
            <?php endif; ?>

            <?php for ($i = $paginationWindowStart; $i <= $paginationWindowEnd; $i++): ?>
                <a class="pagination-btn <?= $i === $currentPage ? 'active' : '' ?>" href="<?= e(url('rayan-requests', array_merge($queryBase, ['p' => $i]))) ?>"><?= e(number_format($i)) ?></a>
            <?php endfor; ?>

            <?php if ($paginationWindowEnd < $lastPage): ?>
                <?php if ($paginationWindowEnd < $lastPage - 1): ?><span class="pagination-dots">...</span><?php endif; ?>
                <a class="pagination-btn" href="<?= e(url('rayan-requests', array_merge($queryBase, ['p' => $lastPage]))) ?>"><?= e(number_format($lastPage)) ?></a>
            <?php endif; ?>

            <a class="pagination-btn <?= $currentPage >= $lastPage ? 'disabled' : '' ?>" href="<?= e(url('rayan-requests', array_merge($queryBase, ['p' => min($lastPage, $currentPage + 1)]))) ?>">بعدی</a>
        </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const selectAll = document.getElementById('select-all-requests');
    if (selectAll) {
        selectAll.addEventListener('change', function () {
            document.querySelectorAll('.request-row-checkbox').forEach(function (checkbox) {
                checkbox.checked = selectAll.checked;
            });
        });
    }

    document.querySelectorAll('.request-edit-toggle').forEach(function (button) {
        button.addEventListener('click', function () {
            const targetId = button.getAttribute('data-edit-target');
            if (!targetId) {
                return;
            }
            const row = document.getElementById(targetId);
            if (!row) {
                return;
            }
            const isOpen = !row.hidden;
            row.hidden = isOpen;
            button.textContent = isOpen ? 'ویرایش' : 'بستن ویرایش';
            button.classList.toggle('warning', !isOpen);
        });
    });

    const table = document.querySelector('.rayan-requests-table.full-fields-table');
    const controls = document.getElementById('rayan-column-controls');
    if (!table || !controls) {
        return;
    }

    const storageKey = 'rayan_requests_columns_v1';
    const defaultOrder = Array.from(table.querySelectorAll('thead th[data-configurable="1"]'))
        .map(function (cell) { return cell.getAttribute('data-col'); })
        .filter(Boolean);

    function readConfig() {
        let parsed = {};
        try {
            parsed = JSON.parse(localStorage.getItem(storageKey) || '{}') || {};
        } catch (error) {
            parsed = {};
        }

        const savedOrder = Array.isArray(parsed.order) ? parsed.order : [];
        const order = savedOrder.filter(function (key) { return defaultOrder.includes(key); });
        defaultOrder.forEach(function (key) {
            if (!order.includes(key)) {
                order.push(key);
            }
        });

        const visible = {};
        defaultOrder.forEach(function (key) {
            visible[key] = !(parsed.visible && parsed.visible[key] === false);
        });

        return {order: order, visible: visible};
    }

    let columnConfig = readConfig();

    function saveConfig() {
        localStorage.setItem(storageKey, JSON.stringify(columnConfig));
    }

    function reorderRow(row) {
        const cells = {};
        Array.from(row.children).forEach(function (cell) {
            const key = cell.getAttribute('data-col');
            if (key) {
                cells[key] = cell;
            }
        });

        if (cells.select) {
            row.appendChild(cells.select);
        }
        columnConfig.order.forEach(function (key) {
            if (cells[key]) {
                row.appendChild(cells[key]);
            }
        });
        if (cells.actions) {
            row.appendChild(cells.actions);
        }
    }

    const hasSelectColumn = table.querySelector('[data-col="select"]') !== null;

    function visibleColumnCount() {
        return (hasSelectColumn ? 1 : 0) + 1 + columnConfig.order.filter(function (key) {
            return columnConfig.visible[key] !== false;
        }).length;
    }

    function renderColumnControls() {
        const list = controls.querySelector('.column-controls-list');
        if (!list) {
            return;
        }

        columnConfig.order.forEach(function (key, index) {
            const row = list.querySelector('[data-col-control="' + key + '"]');
            if (!row) {
                return;
            }
            list.appendChild(row);

            const checkbox = row.querySelector('[data-column-toggle]');
            if (checkbox) {
                checkbox.checked = columnConfig.visible[key] !== false;
            }

            const right = row.querySelector('[data-column-move="right"]');
            const left = row.querySelector('[data-column-move="left"]');
            if (right) {
                right.disabled = index === 0;
            }
            if (left) {
                left.disabled = index === columnConfig.order.length - 1;
            }
        });
    }

    function applyColumns() {
        table.querySelectorAll('thead tr').forEach(function (row) {
            reorderRow(row);
        });

        table.querySelectorAll('tbody tr:not(.request-edit-row)').forEach(function (row) {
            reorderRow(row);
        });

        table.querySelectorAll('[data-col]').forEach(function (cell) {
            const key = cell.getAttribute('data-col');
            const visible = key === 'select' || key === 'actions' || columnConfig.visible[key] !== false;
            cell.hidden = !visible;
            cell.classList.toggle('is-hidden-col', !visible);
        });

        table.querySelectorAll('.request-edit-row > td').forEach(function (cell) {
            cell.colSpan = visibleColumnCount();
        });

        renderColumnControls();
    }

    controls.addEventListener('change', function (event) {
        const checkbox = event.target.closest('[data-column-toggle]');
        if (!checkbox) {
            return;
        }
        const key = checkbox.getAttribute('data-column-toggle');
        if (!key || !defaultOrder.includes(key)) {
            return;
        }
        columnConfig.visible[key] = checkbox.checked;
        saveConfig();
        applyColumns();
    });

    controls.addEventListener('click', function (event) {
        const reset = event.target.closest('[data-column-reset]');
        if (reset) {
            columnConfig = {
                order: defaultOrder.slice(),
                visible: defaultOrder.reduce(function (acc, key) { acc[key] = true; return acc; }, {})
            };
            saveConfig();
            applyColumns();
            return;
        }

        const moveButton = event.target.closest('[data-column-move]');
        if (!moveButton) {
            return;
        }
        const key = moveButton.getAttribute('data-column');
        const direction = moveButton.getAttribute('data-column-move');
        const index = columnConfig.order.indexOf(key);
        if (index === -1) {
            return;
        }
        const targetIndex = direction === 'right' ? index - 1 : index + 1;
        if (targetIndex < 0 || targetIndex >= columnConfig.order.length) {
            return;
        }
        const temp = columnConfig.order[index];
        columnConfig.order[index] = columnConfig.order[targetIndex];
        columnConfig.order[targetIndex] = temp;
        saveConfig();
        applyColumns();
    });

    applyColumns();
});
</script>
