<?php
declare(strict_types=1);

require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\AffiliateService;
use App\Core\Auth;
use App\Core\Database;
use App\Core\FinanceEngine;
use App\Core\ModuleCrud;
use App\Core\Security;
use App\Core\SmartForm;
use App\Core\WithdrawalService;

Auth::requireRole(['admin', 'staff']);
$moduleKey = $moduleKey ?? ($_GET['module'] ?? 'dashboard');
$module = ph_admin_module($moduleKey) ?: [
    'title' => ucwords(str_replace('-', ' ', $moduleKey)),
    'description' => 'Module configuration and records.',
    'table' => 'settings',
    'group' => 'Admin',
];
$pageTitle = $module['title'] . ' | Admin';
$table = (string)($module['table'] ?? 'settings');
$errors = [];

$readOnlyTables = [
    'stock_ledgers','psa_transactions','royalty_cycles','leadership_royalties','affiliate_clicks','affiliate_statements',
    'wallets','admin_wallets','wallet_transfer_requests','reward_points','tax_vat_entries','payments','payment_logs',
    'report_exports','order_items','product_metrics','coupon_usages','activity_logs','login_history','cron_runs',
    'pos_shifts','pos_cash_movements','pos_sales','pos_sale_items','pos_payments','pos_sync_queue','pos_day_closings',
    'management_psa_allocations','royalty_distributions','affiliate_conversions','login_history','payment_logs',
];
$readOnly = (($module['group'] ?? '') === 'Reports & Analytics') || in_array($table, $readOnlyTables, true);
$allFields = ModuleCrud::allowedColumns($table);
$fields = $readOnly ? [] : $allFields;
$hasId = ModuleCrud::hasId($table);
$editingId = $hasId ? max(0, (int)($_GET['edit'] ?? $_POST['id'] ?? 0)) : 0;
$editing = $editingId ? ModuleCrud::find($table, $editingId) : null;

if ($editingId > 0 && !$editing) {
    $errors[] = 'The requested record was not found.';
    $editingId = 0;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($readOnly) {
        $errors[] = 'This screen is read-only. Use the related workflow action instead.';
    } elseif (!verify_csrf()) {
        $errors[] = 'Invalid security token. Refresh the page and try again.';
    } else {
        $action = (string)($_POST['_action'] ?? 'save');
        $id = $hasId ? max(0, (int)($_POST['id'] ?? 0)) : 0;
        try {
            if ($action === 'delete') {
                if (!$hasId || $id < 1) throw new RuntimeException('This record cannot be removed from the generic form.');
                $ok = ModuleCrud::delete($table, $id);
                if (!$ok) throw new RuntimeException('Could not remove or disable the record.');
                Security::logActivity(Auth::id(), 'admin_record_deleted', ['module' => $moduleKey, 'table' => $table, 'id' => $id]);
                set_flash('success', 'Record removed or disabled successfully.');
                redirect('admin/' . basename((string)$_SERVER['SCRIPT_NAME']));
            }

            $existing = $id ? ModuleCrud::find($table, $id) : null;
            if ($id && !$existing) throw new RuntimeException('The record no longer exists.');
            $payload = SmartForm::prepare($table, $_POST, $_FILES, $id ?: null, $existing);

            if ($table === 'withdraw_requests' && $id && in_array((string)($payload['status'] ?? ''), ['approved','paid','rejected','cancelled'], true)) {
                $result = WithdrawalService::process($id, (string)$payload['status'], (int)Auth::id());
                $ok = (bool)($result['ok'] ?? false);
                if (!$ok) throw new RuntimeException((string)($result['message'] ?? 'Withdrawal processing failed.'));
            } else {
                $ok = ModuleCrud::save($table, $payload, $id ?: null);
            }

            if (!$ok) throw new RuntimeException('The record could not be saved. Check required and unique values.');
            if ($table === 'orders' && $id && (($payload['order_status'] ?? '') === 'delivered')) {
                if (($payload['payment_method'] ?? '') === 'cod') {
                    Database::safeExecute('UPDATE orders SET payment_status="paid",paid_amount=total_amount,due_amount=0,updated_at=NOW() WHERE id=?', [$id]);
                }
                AffiliateService::processOrder($id);
            }

            Security::logActivity(Auth::id(), $id ? 'admin_record_updated' : 'admin_record_created', [
                'module' => $moduleKey, 'table' => $table, 'id' => $id ?: Database::lastInsertId(),
            ]);
            set_flash('success', $id ? 'Record updated successfully.' : 'Record created successfully.');
            redirect('admin/' . basename((string)$_SERVER['SCRIPT_NAME']));
        } catch (Throwable $exception) {
            error_log('Admin smart form failed: ' . $exception->getMessage());
            $errors[] = APP_ENV === 'production' && !($exception instanceof RuntimeException)
                ? 'The database rejected the request. Check required or duplicate values.'
                : $exception->getMessage();
            $editing = array_merge($editing ?? [], $_POST);
            $editingId = $id;
        }
    }
}

$query = mb_substr(trim((string)($_GET['q'] ?? '')), 0, 120);
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 25;
$count = ModuleCrud::countFiltered($table, $query);
$totalPages = max(1, (int)ceil($count / $perPage));
$page = min($page, $totalPages);
$rows = ModuleCrud::listFiltered($table, $query, $perPage, ($page - 1) * $perPage);
$sections = SmartForm::sections($table, $fields);
$samplePsa = FinanceEngine::calculatePsa(500, 5000);

$preferredDisplay = ['name','title','shop_name','code','email','order_no','invoice_no','sale_no','sku','status'];
$displayFields = array_values(array_unique(array_merge(array_intersect($preferredDisplay, $allFields), $allFields)));
$displayFields = array_slice($displayFields, 0, 6);

$fieldValue = static function (string $field, mixed $default = '') use ($editing): mixed {
    return $editing[$field] ?? $default;
};
$fileUrl = static function (string $path): string {
    $path = trim($path);
    if ($path === '') return '';
    if (preg_match('#^https?://#i', $path)) return $path;
    if (str_starts_with($path, 'private:')) return url('api/media.php?id=' . (int)substr($path, 8));
    if (str_starts_with($path, 'public/')) return url($path);
    if (str_starts_with($path, 'uploads/')) return url('public/' . $path);
    if (str_starts_with($path, 'assets/')) return url('public/' . $path);
    return url(ltrim($path, '/'));
};

require ROOT_PATH . '/app/Layouts/admin_header.php';
?>
<link rel="stylesheet" href="<?= admin_asset('css/smart-forms.css') ?>">

<div class="d-flex flex-wrap gap-3 align-items-start justify-content-between mb-4">
    <div>
        <h1 class="h3 mb-1"><?= e($module['title']) ?></h1>
        <p class="text-muted mb-0"><?= e($module['description'] ?? '') ?></p>
    </div>
    <div class="d-flex flex-wrap gap-2">
        <a class="btn btn-outline-secondary" href="<?= url('admin/feature-map.php') ?>">Feature map</a>
        <?php if (!$readOnly): ?><a class="btn btn-primary" href="#recordForm"><?= $editing ? 'Continue editing' : 'Add new record' ?></a><?php endif; ?>
    </div>
</div>

<?php foreach ($errors as $error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endforeach; ?>
<?php if (!Database::tableExists($table)): ?><div class="alert alert-warning">The table <code><?= e($table) ?></code> is missing. Import the current database update before using this module.</div><?php endif; ?>

<div class="row g-3 mb-4">
    <div class="col-6 col-xl-3"><div class="stat-tile"><div class="small text-muted">Module table</div><strong><?= e($table) ?></strong></div></div>
    <div class="col-6 col-xl-3"><div class="stat-tile"><div class="small text-muted">Records</div><strong><?= number_format($count) ?></strong></div></div>
    <div class="col-6 col-xl-3"><div class="stat-tile"><div class="small text-muted">Form fields</div><strong><?= number_format(count($fields)) ?></strong></div></div>
    <div class="col-6 col-xl-3"><div class="stat-tile"><div class="small text-muted">Mode</div><strong><?= $readOnly ? 'Read only' : 'Managed form' ?></strong></div></div>
</div>

<?php if (in_array($moduleKey, ['affiliate','psa-rules','psa-transactions','management-psa','global-royalty','leadership-royalty','incentive-fund'], true)): ?>
<div class="card module-card mb-4"><div class="card-body"><h5>PSA calculation example</h5><div class="row g-2"><div class="col-md-3"><span class="feature-pill">Profit <?= money($samplePsa['profit']) ?></span></div><div class="col-md-3"><span class="feature-pill">Management <?= money($samplePsa['management_psa']) ?></span></div><div class="col-md-3"><span class="feature-pill">Marketing <?= money($samplePsa['marketing_psa']) ?></span></div><div class="col-md-3"><span class="feature-pill">Incentive <?= money($samplePsa['marketing_distribution']['incentive_fund']) ?></span></div></div></div></div>
<?php endif; ?>

<?php if ($readOnly): ?><div class="alert alert-info">This is an operational ledger or report. Changes must be made through the related order, payment, wallet, POS, refund or scheduled workflow.</div><?php endif; ?>

<?php if (!$readOnly): ?>
<div class="card module-card mb-4 smart-form-card" id="recordForm">
    <div class="card-header bg-white d-flex flex-wrap gap-2 align-items-center justify-content-between">
        <div><strong><?= $editing ? 'Edit record #' . (int)$editingId : 'Create new record' ?></strong><div class="small text-muted">Fields are validated using the live database schema.</div></div>
        <?php if ($editing): ?><a href="<?= url('admin/' . basename((string)$_SERVER['SCRIPT_NAME']) . '#recordForm') ?>" class="btn btn-sm btn-outline-secondary">Create another</a><?php endif; ?>
    </div>
    <div class="card-body">
        <?php if (!$fields): ?>
            <div class="alert alert-warning mb-0">No safe editable fields are configured for this table.</div>
        <?php else: ?>
        <form method="post" enctype="multipart/form-data" class="smart-form" data-smart-form data-entity="<?= e($table) ?>">
            <?= csrf_field() ?>
            <input type="hidden" name="_action" value="save">
            <input type="hidden" name="id" value="<?= (int)$editingId ?>">

            <?php foreach ($sections as $section => $sectionFields): ?>
                <section class="smart-form-section">
                    <div class="smart-form-section-heading"><span><?= e($section) ?></span></div>
                    <div class="row g-3">
                    <?php foreach ($sectionFields as $config):
                        $field = (string)$config['name'];
                        $value = $fieldValue($field, '');
                        if (($config['type'] ?? '') === 'datetime-local' && $value && strtotime((string)$value)) $value = date('Y-m-d\TH:i', strtotime((string)$value));
                        if (($config['type'] ?? '') === 'date' && $value && strtotime((string)$value)) $value = date('Y-m-d', strtotime((string)$value));
                        $inputId = 'sf_' . preg_replace('/[^a-z0-9_]/i', '_', $field);
                    ?>
                        <div class="col-12 col-lg-<?= (int)$config['col'] ?> smart-field" data-field-name="<?= e($field) ?>">
                            <label class="form-label <?= $config['required'] ? 'required-label' : '' ?>" for="<?= e($inputId) ?>"><?= e($config['label']) ?></label>

                            <?php if ($config['type'] === 'select'): ?>
                                <?php if (count($config['options']) > 12): ?><input type="search" class="form-control form-control-sm mb-1 smart-select-search" data-target="<?= e($inputId) ?>" placeholder="Search <?= e(strtolower($config['label'])) ?> options"><?php endif; ?>
                                <select class="form-select" name="<?= e($field) ?>" id="<?= e($inputId) ?>" <?= $config['required'] ? 'required' : '' ?>>
                                    <?php if (!$config['required']): ?><option value="">None / not selected</option><?php else: ?><option value="">Select <?= e(strtolower($config['label'])) ?></option><?php endif; ?>
                                    <?php
                                    $foundCurrent = false;
                                    foreach ($config['options'] as $option):
                                        $selected = (string)$value === (string)$option['value'];
                                        if ($selected) $foundCurrent = true;
                                    ?>
                                        <option value="<?= e($option['value']) ?>" <?= $selected ? 'selected' : '' ?>><?= e($option['label']) ?></option>
                                    <?php endforeach; ?>
                                    <?php if ($value !== '' && $value !== null && !$foundCurrent): ?><option value="<?= e($value) ?>" selected>Current: <?= e($value) ?></option><?php endif; ?>
                                </select>
                            <?php elseif ($config['type'] === 'textarea' && $config['rich']): ?>
                                <input type="hidden" name="<?= e($field) ?>" id="<?= e($inputId) ?>" value="<?= e($value) ?>">
                                <div class="smart-editor-toolbar" data-editor-toolbar="<?= e($inputId) ?>_editor"></div>
                                <div class="smart-rich-editor" id="<?= e($inputId) ?>_editor" contenteditable="true" data-target="<?= e($inputId) ?>"><?= sanitize_rich_html((string)$value) ?></div>
                            <?php elseif ($config['type'] === 'textarea'): ?>
                                <textarea class="form-control <?= $config['json'] ? 'font-monospace smart-json-field' : '' ?>" name="<?= e($field) ?>" id="<?= e($inputId) ?>" rows="<?= $config['json'] ? 7 : 4 ?>" placeholder="<?= e($config['placeholder']) ?>" <?= $config['required'] ? 'required' : '' ?>><?= e($value) ?></textarea>
                                <?php if ($config['json']): ?><div class="d-flex gap-2 mt-1"><button type="button" class="btn btn-sm btn-outline-secondary smart-format-json" data-target="<?= e($inputId) ?>">Format JSON</button><span class="small text-muted smart-json-status" data-for="<?= e($inputId) ?>"></span></div><?php endif; ?>
                            <?php elseif ($config['type'] === 'file'): ?>
                                <div class="smart-upload-box">
                                    <?php if ($config['image']): ?><img class="smart-image-preview <?= $value ? '' : 'd-none' ?>" id="<?= e($inputId) ?>_preview" src="<?= $value ? e($fileUrl((string)$value)) : '' ?>" alt="Preview"><?php endif; ?>
                                    <div class="flex-grow-1">
                                        <input class="form-control" type="file" name="<?= e($field) ?>" id="<?= e($inputId) ?>" accept="<?= e($config['accept']) ?>" data-preview="<?= e($inputId) ?>_preview">
                                        <?php if ($value): ?><div class="small mt-2"><a href="<?= e($fileUrl((string)$value)) ?>" target="_blank" rel="noopener">Open current file</a></div><div class="form-check mt-1"><input class="form-check-input" type="checkbox" name="remove_<?= e($field) ?>" value="1" id="remove_<?= e($inputId) ?>"><label class="form-check-label text-danger" for="remove_<?= e($inputId) ?>">Remove current file</label></div><?php endif; ?>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="<?= $config['auto'] === 'code' ? 'input-group' : '' ?>">
                                    <input class="form-control" type="<?= e($config['type']) ?>" name="<?= e($field) ?>" id="<?= e($inputId) ?>" value="<?= e($value) ?>" placeholder="<?= e($config['placeholder']) ?>" <?= $config['required'] ? 'required' : '' ?> <?= $config['step'] !== null ? 'step="' . e($config['step']) . '"' : '' ?> <?= $config['min'] !== null ? 'min="' . e($config['min']) . '"' : '' ?> <?= $config['max'] !== null ? 'max="' . e($config['max']) . '"' : '' ?> data-auto="<?= e((string)$config['auto']) ?>">
                                    <?php if ($config['auto'] === 'code'): ?><button class="btn btn-outline-secondary smart-generate-code" type="button" data-target="<?= e($inputId) ?>" data-field="<?= e($field) ?>">Generate</button><?php endif; ?>
                                </div>
                                <?php if (in_array($config['auto'], ['slug','meta-title'], true)): ?><div class="form-check mt-1"><input class="form-check-input smart-auto-toggle" type="checkbox" id="auto_<?= e($inputId) ?>" data-target="<?= e($inputId) ?>" checked><label class="form-check-label small text-muted" for="auto_<?= e($inputId) ?>">Automatically update from name/title</label></div><?php endif; ?>
                                <?php if ($config['auto'] === 'meta-keywords'): ?><div class="d-flex flex-wrap gap-1 mt-2 smart-keyword-chips" data-target="<?= e($inputId) ?>"></div><?php endif; ?>
                            <?php endif; ?>

                            <?php if ($config['help']): ?><div class="form-text"><?= e($config['help']) ?></div><?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                    </div>
                </section>
            <?php endforeach; ?>

            <div class="smart-form-actions d-flex flex-wrap gap-2 justify-content-end">
                <?php if ($editing): ?><a class="btn btn-outline-secondary btn-lg" href="<?= url('admin/' . basename((string)$_SERVER['SCRIPT_NAME'])) ?>">Cancel</a><?php endif; ?>
                <button class="btn btn-primary btn-lg" type="submit"><?= $editing ? 'Update record' : 'Save record' ?></button>
            </div>
        </form>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<div class="card module-card">
    <div class="card-header bg-white">
        <form class="d-flex flex-wrap gap-2 align-items-center" method="get">
            <input class="form-control" style="max-width:430px" name="q" value="<?= e($query) ?>" placeholder="Search <?= e(strtolower($module['title'])) ?>">
            <button class="btn btn-outline-primary">Search</button>
            <?php if ($query !== ''): ?><a class="btn btn-outline-secondary" href="<?= url('admin/' . basename((string)$_SERVER['SCRIPT_NAME'])) ?>">Clear</a><?php endif; ?>
            <div class="small text-muted ms-lg-auto"><?= number_format($count) ?> result<?= $count === 1 ? '' : 's' ?></div>
            <a class="btn btn-outline-secondary" href="<?= url('api/export.php?table=' . urlencode($table) . '&module=' . urlencode($moduleKey)) ?>">Export CSV</a>
        </form>
    </div>
    <div class="table-responsive">
        <table class="table align-middle mb-0 smart-data-table">
            <thead><tr><?php if ($hasId): ?><th>ID</th><?php endif; ?><?php foreach ($displayFields as $field): ?><th><?= e(ModuleCrud::fieldLabel($field)) ?></th><?php endforeach; ?><?php if (!$readOnly && $hasId): ?><th>Actions</th><?php endif; ?></tr></thead>
            <tbody>
            <?php if (!$rows): ?><?= table_empty(count($displayFields) + ($hasId ? 1 : 0) + (!$readOnly && $hasId ? 1 : 0), 'No records found.') ?><?php endif; ?>
            <?php foreach ($rows as $row): ?>
                <tr>
                    <?php if ($hasId): ?><td><span class="text-muted">#<?= (int)($row['id'] ?? 0) ?></span></td><?php endif; ?>
                    <?php foreach ($displayFields as $field):
                        $value = $row[$field] ?? null;
                        $config = SmartForm::field($table, $field);
                    ?>
                        <td>
                            <?php if ($config['image'] && $value): ?><img src="<?= e($fileUrl((string)$value)) ?>" class="smart-table-thumb" alt="">
                            <?php elseif ($field === 'status' || str_ends_with($field, '_status')): ?><?= badge((string)$value) ?>
                            <?php elseif ($config['type'] === 'select' && count($config['options']) === 2 && in_array((string)$value, ['0','1'], true)): ?><span class="badge bg-<?= (string)$value === '1' ? 'success' : 'secondary' ?>"><?= (string)$value === '1' ? 'Yes' : 'No' ?></span>
                            <?php else: ?><?= e(mb_strimwidth(SmartForm::displayValue($table, $field, $value), 0, 64, '…')) ?><?php endif; ?>
                        </td>
                    <?php endforeach; ?>
                    <?php if (!$readOnly && $hasId): ?><td class="text-nowrap"><a class="btn btn-sm btn-outline-primary" href="?edit=<?= (int)($row['id'] ?? 0) ?>#recordForm">Edit</a> <form method="post" class="d-inline" onsubmit="return confirm('Remove or disable this record?')"><?= csrf_field() ?><input type="hidden" name="_action" value="delete"><input type="hidden" name="id" value="<?= (int)($row['id'] ?? 0) ?>"><button class="btn btn-sm btn-outline-danger">Delete</button></form></td><?php endif; ?>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if ($totalPages > 1): ?>
    <div class="card-footer bg-white d-flex justify-content-between align-items-center">
        <span class="small text-muted">Page <?= $page ?> of <?= $totalPages ?></span>
        <div class="btn-group">
            <a class="btn btn-sm btn-outline-secondary <?= $page <= 1 ? 'disabled' : '' ?>" href="?q=<?= urlencode($query) ?>&page=<?= max(1, $page - 1) ?>">Previous</a>
            <a class="btn btn-sm btn-outline-secondary <?= $page >= $totalPages ? 'disabled' : '' ?>" href="?q=<?= urlencode($query) ?>&page=<?= min($totalPages, $page + 1) ?>">Next</a>
        </div>
    </div>
    <?php endif; ?>
</div>

<script src="<?= admin_asset('js/smart-forms.js') ?>"></script>
<?php require ROOT_PATH . '/app/Layouts/admin_footer.php'; ?>
