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

use App\Core\Auth;
use App\Core\Database;
use App\Core\Exporter;
use App\Core\PosService;
use App\Core\Response;
use App\Core\Security;

$format = strtolower((string)($_GET['format'] ?? 'csv'));
if (!in_array($format, ['csv', 'xls', 'excel', 'pdf'], true)) {
    Response::json(['ok' => false, 'message' => 'Unsupported export format.'], 422);
}

if ((string)($_GET['report'] ?? '') === 'pos') {
    PosService::requireAccess('public/login.php');
    $vendorId = (int)(PosService::currentVendorId() ?? 0);
    if ($vendorId < 1) Response::json(['ok' => false, 'message' => 'No vendor is assigned to this POS session.'], 403);
    if (!Security::rateLimit('export:pos:' . Auth::id(), 10, 300)) {
        Response::json(['ok' => false, 'message' => 'Too many export requests. Try again later.'], 429);
    }
    $rows = Database::safeFetchAll(
        'SELECT ps.sale_no,ps.subtotal,ps.discount_amount,ps.tax_amount,ps.total_amount,ps.paid_amount,ps.change_amount,ps.payment_status,ps.sale_status,ps.created_at,u.name cashier_name,pr.name register_name
         FROM pos_sales ps
         LEFT JOIN users u ON u.id=ps.cashier_id
         LEFT JOIN pos_registers pr ON pr.id=ps.register_id
         WHERE ps.vendor_id=? ORDER BY ps.id DESC LIMIT 5000',
        [$vendorId]
    );
    Security::logActivity(Auth::id(), 'report_exported', ['report' => 'pos', 'vendor_id' => $vendorId, 'rows' => count($rows)]);
    if ($format === 'pdf') Exporter::pdf('pos-sales-report.pdf', 'POS Sales Report', $rows);
    if ($format === 'xls' || $format === 'excel') Exporter::excel('pos-sales-report.xls', $rows);
    Exporter::csv('pos-sales-report.csv', $rows);
}

Auth::requireRole(['admin', 'staff']);
$table = preg_replace('/[^a-z0-9_]/', '', strtolower((string)($_GET['table'] ?? '')));
$moduleKey = Auth::normalizeModuleKey((string)($_GET['module'] ?? ''));
$module = $moduleKey !== '' ? ph_admin_module($moduleKey) : null;

if (!$module || (string)($module['table'] ?? '') !== $table) {
    if (Auth::role() !== 'admin') {
        Response::json(['ok' => false, 'message' => 'A valid authorized module is required for this export.'], 403);
    }
    $module = null;
    foreach (ph_admin_modules() as $candidate) {
        if ((string)($candidate['table'] ?? '') === $table) {
            $module = $candidate;
            $moduleKey = (string)$candidate['key'];
            break;
        }
    }
}
if (!$module || !Database::tableExists($table)) {
    Response::json(['ok' => false, 'message' => 'Export table is not allowed.'], 403);
}
if (Auth::role() === 'staff' && !Auth::canAdminModule($moduleKey)) {
    Response::json(['ok' => false, 'message' => 'You do not have permission to export this module.'], 403);
}
if (!Security::rateLimit('export:' . Auth::id(), 15, 300)) {
    Response::json(['ok' => false, 'message' => 'Too many export requests. Try again later.'], 429);
}

$blockedColumns = [
    'password_hash', 'transaction_pin_hash', 'client_secret', 'token_hash', 'otp_code',
    'auth_token', 'public_key', 'config_json', 'api_config', 'raw_response',
    'payload', 'payload_json', 'response_json',
];
$columns = array_values(array_filter(Database::columns($table), static function (string $column) use ($blockedColumns): bool {
    if (in_array($column, $blockedColumns, true)) return false;
    $lower = strtolower($column);
    return !str_contains($lower, 'password') && !str_contains($lower, 'secret') && !str_ends_with($lower, '_hash');
}));
if (!$columns) Response::json(['ok' => false, 'message' => 'This module has no exportable columns.'], 422);
$quoted = implode(',', array_map(static fn(string $column): string => '`' . $column . '`', $columns));
$where = '1=1';
$params = [];
if ($table === 'users' && in_array($moduleKey, ['customers','customer-report'], true)) $where = 'role="customer"';
if ($table === 'users' && $moduleKey === 'staff') $where = 'role="staff"';
$rows = Database::safeFetchAll("SELECT {$quoted} FROM `{$table}` WHERE {$where} ORDER BY id DESC LIMIT 5000", $params);
Security::logActivity(Auth::id(), 'report_exported', ['module' => $moduleKey, 'table' => $table, 'rows' => count($rows), 'format' => $format]);
$title = ucwords(str_replace(['_', '-'], ' ', (string)($module['title'] ?? $table)));
if ($format === 'pdf') Exporter::pdf($table . '-export.pdf', $title, $rows);
if ($format === 'xls' || $format === 'excel') Exporter::excel($table . '-export.xls', $rows);
Exporter::csv($table . '-export.csv', $rows);
