<?php
require_once __DIR__ . '/../app/Core/bootstrap.php';
require_once __DIR__ . '/../app/Core/Auth.php';
require_once __DIR__ . '/../app/Services/LegacyBotService.php';
require_once __DIR__ . '/../app/Core/TaskRunner.php';
require_once __DIR__ . '/../app/Rayan/RayanPanelService.php';

$service = new LegacyBotService();
$page = $_GET['page'] ?? (Auth::check() ? 'dashboard' : 'login');

if ($page === 'task-runner') {
    Auth::requireLogin();
    Auth::requireTask((string)($_GET['task'] ?? ''));
    $runner = new TaskRunner($service);
    $runner->stream((string)($_GET['task'] ?? ''), (string)($_GET['return_page'] ?? 'dashboard'));
}

if ($page !== 'login' && $page !== 'logout') {
    Auth::requireLogin();
    Auth::requirePage((string)$page);
}

try {
    switch ($page) {
        case 'login':
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $username = trim((string)($_POST['username'] ?? ''));
                $password = (string)($_POST['password'] ?? '');
                if (Auth::attempt($username, $password)) {
                    set_flash('success', 'ورود با موفقیت انجام شد.');
                    redirect('dashboard');
                }
                set_flash('error', 'نام کاربری یا رمز عبور اشتباه است.');
                redirect('login');
            }
            $title = 'ورود به پنل';
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/auth/login.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;

        case 'logout':
            Auth::logout();
            set_flash('success', 'از حساب خارج شدید.');
            redirect('login');
            break;

        case 'dashboard':
            $title = 'داشبورد';
            $stats = $service->getDashboardStats();
            $cards = Auth::filterCards($service->getActionCards());
            $recentExports = $service->listRecentExports();
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/dashboard/index.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;

        case 'unmapped':
            if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'run_unmapped') {
                $result = $service->runUnmappedExport();
                set_flash('success', $result['message'] . ' | ' . basename((string)$result['file']));
                redirect('unmapped');
            }
            $title = 'کالاهای مپ نشده';
            $latestFile = $service->getLatestExportByPrefix('unmapped_products_');
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/tools/unmapped.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;

        case 'smart-map':
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $action = (string)($_POST['action'] ?? '');
                if ($action === 'generate_template') {
                    $result = $service->generateSmartMapTemplate();
                    set_flash('success', $result['message'] . ' | ' . basename((string)$result['file']));
                } elseif ($action === 'upload_map') {
                    $result = $service->uploadSmartMap();
                    set_flash('success', $result['message'] . ' | تعداد ردیف: ' . ($result['rows_count'] ?? 0));
                }
                redirect('smart-map');
            }
            $title = 'تنظیم مپ قیمت هوشمند';
            $latestExport = $service->getLatestExportByPrefix('smart_price_map_');
            $latestState = $service->getLatestRuntimeFile('smart_price_map_latest.csv');
            $uploadedFiles = $service->listUploadedFiles();
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/tools/smart-map.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;

        case 'smart-review':
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $action = (string)($_POST['action'] ?? '');
                if ($action === 'generate_review') {
                    $result = $service->generateSmartReview(Auth::user()['username'] ?? 'admin');
                    set_flash('success', $result['message'] . ' | ردیف: ' . ($result['rows_count'] ?? 0));
                } elseif ($action === 'upload_review') {
                    $result = $service->applyUploadedSmartReview('smart_review_file', Auth::user()['username'] ?? 'admin');
                    set_flash('success', $result['message']);
                } elseif ($action === 'apply_saved_review') {
                    $result = $service->applySavedSmartReview(Auth::user()['username'] ?? 'admin');
                    set_flash('success', $result['message']);
                }
                redirect('smart-review');
            }
            $title = 'بررسی قیمت هوشمند';
            $latestReview = $service->getLatestExportByPrefix('smart_price_review_');
            $latestRows = $service->getLatestRuntimeFile('latest_smart_review_rows.json');
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/tools/smart-review.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;

        case 'text-list':
            if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'build_text') {
                $result = $service->buildTextList();
                set_flash('success', $result['message']);
                redirect('text-list');
            }
            $title = 'تولید لیست متنی';
            $textOutput = $service->getTextListFromFile();
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/tools/text-list.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;

        case 'export-all':
            if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'run_exports') {
                $result = $service->runAllExports();
                $msg = $result['message'] . ' | فایل‌های موفق: ' . count($result['files'] ?? []);
                if (!empty($result['warnings'])) {
                    $msg .= ' | هشدارها: ' . implode(' || ', $result['warnings']);
                }
                set_flash('success', $msg);
                redirect('export-all');
            }
            $title = 'استخراج همه فایل‌ها';
            $recentExports = $service->listRecentExports();
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/tools/export-all.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;


        case 'rayan-requests':
            $rayanService = new RayanPanelService();
            $reportColumnFilterKeys = [
                'id', 'created_at', 'owner', 'submitter', 'submitted_at',
                'plan', 'final', 'status', 'customer', 'national', 'mobile',
                'product', 'installment_amount', 'sales_amount', 'purchase_amount',
                'postal', 'source_mode', 'store', 'address', 'step', 'error', 'tracking',
            ];
            $columnFilters = [];
            $rawColumnFilters = is_array($_GET['col'] ?? null) ? (array)$_GET['col'] : [];
            foreach ($reportColumnFilterKeys as $filterKey) {
                $filterValue = trim((string)($rawColumnFilters[$filterKey] ?? ''));
                if ($filterValue !== '') {
                    $columnFilters[$filterKey] = $filterValue;
                }
            }
            $requestQuery = [
                'club' => (string)($_GET['club'] ?? ''),
                'status' => (string)($_GET['status'] ?? ''),
                'created_by' => Auth::isAdmin() ? (string)($_GET['created_by'] ?? '') : '',
                'q' => (string)($_GET['q'] ?? ''),
                'created_from' => (string)($_GET['created_from'] ?? ''),
                'created_to' => (string)($_GET['created_to'] ?? ''),
                'submitted_from' => (string)($_GET['submitted_from'] ?? ''),
                'submitted_to' => (string)($_GET['submitted_to'] ?? ''),
                'col' => $columnFilters,
                'p' => max(1, (int)($_GET['p'] ?? 1)),
                'per_page' => (int)($_GET['per_page'] ?? 25),
            ];
            if ((string)($_GET['export'] ?? '') === 'excel') {
                if (!Auth::isAdmin()) {
                    set_flash('error', 'خروجی اکسل فقط برای ادمین فعال است.');
                    redirect('rayan-requests');
                }
                $rayanService->streamRequestsExcel($requestQuery);
            }
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $action = (string)($_POST['action'] ?? '');
                $requestId = (int)($_POST['request_id'] ?? 0);
                if ($action === 'create_manual_request') {
                    $result = $rayanService->createManualRequest($_POST, false);
                    $message = !empty($result['request_created'])
                        ? ('درخواست دستی #' . (int)$result['request_id'] . ' ساخته شد و آماده ثبت است.')
                        : ((string)($result['message'] ?? 'درخواست دستی ذخیره شد.'));
                    set_flash('success', $message);
                } elseif ($action === 'update_manual_request' && $requestId > 0) {
                    $result = $rayanService->updateManualRequest($requestId, $_POST);
                    set_flash('success', $result['message']);
                } elseif ($action === 'process_request' && $requestId > 0) {
                    $result = $rayanService->processRequest($requestId);
                    set_flash('success', $result['message']);
                } elseif ($action === 'process_stage_one' && $requestId > 0) {
                    $result = $rayanService->processClubStageOne($requestId);
                    set_flash('success', $result['message']);
                } elseif ($action === 'process_stage_two' && $requestId > 0) {
                    $result = $rayanService->processClubStageTwo($requestId);
                    set_flash('success', $result['message']);
                } elseif ($action === 'retry_request' && $requestId > 0) {
                    $result = $rayanService->retryRequest($requestId);
                    set_flash('success', $result['message']);
                } elseif ($action === 'submit_otp' && $requestId > 0) {
                    $result = $rayanService->submitOtp($requestId, (string)($_POST['otp_code'] ?? ''));
                    set_flash('success', $result['message']);
                } elseif ($action === 'delete_request' && $requestId > 0) {
                    $result = $rayanService->deleteRequest($requestId);
                    set_flash('success', $result['message']);
                } elseif ($action === 'delete_selected') {
                    $result = $rayanService->deleteRequests($_POST['request_ids'] ?? []);
                    set_flash('success', $result['message']);
                }
                redirect('rayan-requests', $requestQuery);
            }
            $title = 'ثبت فاکتور';
            $filters = $requestQuery;
            $requestData = $rayanService->listRequests($filters);
            $manualSettings = $rayanService->getManualFormSettings();
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/rayan/requests.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;

        case 'rayan-form-settings':
            if (!Auth::isAdmin()) {
                set_flash('error', 'فقط ادمین می‌تواند تنظیمات فرم را تغییر دهد.');
                redirect('dashboard');
            }
            $rayanService = new RayanPanelService();
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $result = $rayanService->updateManualFormSettings($_POST);
                set_flash('success', (string)($result['message'] ?? 'تنظیمات فرم ذخیره شد.'));
                redirect('rayan-form-settings', [
                    'q' => (string)($_GET['q'] ?? ''),
                    'p' => max(1, (int)($_GET['p'] ?? 1)),
                    'per_page' => (int)($_GET['per_page'] ?? 100),
                ]);
            }
            $title = 'تنظیمات فرم دستی';
            $manualSettings = $rayanService->getManualFormSettings();
            $productFilters = [
                'q' => (string)($_GET['q'] ?? ''),
                'p' => max(1, (int)($_GET['p'] ?? 1)),
                'per_page' => (int)($_GET['per_page'] ?? 100),
            ];
            $productData = $rayanService->paginateManualProducts($manualSettings, $productFilters['q'], $productFilters['p'], $productFilters['per_page']);
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/rayan/form-settings.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;

        case 'rayan-inquiry':
            $rayanService = new RayanPanelService();
            if ((string)($_GET['export'] ?? '') === 'excel') {
                if (!Auth::isAdmin()) {
                    set_flash('error', 'خروجی اکسل استعلام فقط برای ادمین فعال است.');
                    redirect('rayan-inquiry');
                }
                $rayanService->streamCreditInquiryReportsExcel();
            }
            $inquiryResult = $_SESSION['rayan_inquiry_result'] ?? null;
            unset($_SESSION['rayan_inquiry_result']);
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $inquiryResult = $rayanService->runCreditInquiry((string)($_POST['national_id'] ?? ''), (string)($_POST['mobile'] ?? ''));
                $rayanService->saveCreditInquiryReport($inquiryResult);
                set_flash('success', 'استعلام بازنشسته تامین اجتماعی با موفقیت انجام شد.');
            }
            $title = 'استعلام بازنشسته تامین اجتماعی';
            $inquiryReports = $rayanService->listCreditInquiryReports();
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/rayan/inquiry.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;


        case 'users':
            $title = 'مدیریت کاربران و سطح دسترسی';
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $action = (string)($_POST['action'] ?? '');
                if ($action === 'create_user') {
                    Auth::createUser([
                        'username' => (string)($_POST['username'] ?? ''),
                        'display_name' => (string)($_POST['display_name'] ?? ''),
                        'formafzar_creator_id' => (string)($_POST['formafzar_creator_id'] ?? ''),
                        'password' => (string)($_POST['password'] ?? ''),
                        'role' => (string)($_POST['role'] ?? 'user'),
                        'permissions' => (array)($_POST['permissions'] ?? []),
                        'is_active' => !empty($_POST['is_active']),
                    ]);
                    set_flash('success', 'کاربر جدید ساخته شد.');
                } elseif ($action === 'update_user') {
                    Auth::updateUser((string)($_POST['username'] ?? ''), [
                        'new_username' => (string)($_POST['new_username'] ?? ($_POST['username'] ?? '')),
                        'display_name' => (string)($_POST['display_name'] ?? ''),
                        'formafzar_creator_id' => (string)($_POST['formafzar_creator_id'] ?? ''),
                        'password' => (string)($_POST['password'] ?? ''),
                        'role' => (string)($_POST['role'] ?? 'user'),
                        'permissions' => (array)($_POST['permissions'] ?? []),
                        'is_active' => !empty($_POST['is_active']),
                    ]);
                    set_flash('success', 'دسترسی‌های کاربر ذخیره شد.');
                } elseif ($action === 'delete_user') {
                    Auth::deleteUser((string)($_POST['username'] ?? ''));
                    set_flash('success', 'کاربر حذف شد.');
                }
                redirect('users');
            }
            $users = Auth::listUsers();
            $permissions = Auth::permissionsCatalog();
            $currentUser = Auth::user() ?? [];
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/admin/users.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;

        case 'logs':
            $title = 'لاگ‌ها';
            $panelLogs = $service->getPanelLogs();
            $legacyLogs = $service->getLegacyPollingLogs();
            include __DIR__ . '/../app/Views/layout/header.php';
            include __DIR__ . '/../app/Views/tools/logs.php';
            include __DIR__ . '/../app/Views/layout/footer.php';
            break;

        case 'download':
            $meta = $service->downloadFileMeta((string)($_GET['area'] ?? ''), (string)($_GET['name'] ?? ''));
            if (!$meta) {
                http_response_code(404);
                exit('فایل پیدا نشد.');
            }
            header('Content-Type: application/octet-stream');
            header('Content-Length: ' . $meta['size']);
            header('Content-Disposition: attachment; filename="' . basename($meta['name']) . '"');
            readfile($meta['path']);
            exit;

        default:
            http_response_code(404);
            echo 'Page not found';
    }
} catch (Throwable $e) {
    log_app('ERROR ' . $e->getMessage());
    set_flash('error', $e->getMessage());
    if ($page === 'login') {
        redirect('login');
    }
    redirect($page ?: 'dashboard');
}
