<?php

require_once APP_ROOT . '/models/User.php';
require_once APP_ROOT . '/models/Setting.php';
require_once APP_ROOT . '/models/Collection.php';
require_once APP_ROOT . '/models/ConditionOption.php';
require_once APP_ROOT . '/models/VariantTypeOption.php';

class AdminController
{
    private User $userModel;
    private Setting $settingModel;

    public function __construct()
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }
        $this->userModel = new User();
        $this->settingModel = new Setting();
        $this->requireAdmin();
    }

    private function requireAdmin(): void
    {
        $user = $this->userModel->findById(Session::getUserId());
        if (!$user || $user['role'] !== 'admin') {
            header('Location: ' . APP_URL . '/home');
            exit;
        }
    }

    public function exportTemplatesPdf(): void
    {
        $collectionModel = new Collection();
        $allCollections = $collectionModel->getAllForAdmin();
        
        // Filter only templates
        $templates = array_filter($allCollections, function($c) {
            return $c['is_template'] ?? false;
        });

        // Create PDF
        require_once APP_ROOT . '/vendor/tecnickcom/tcpdf/tcpdf.php';
        
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        
        // Set document information
        $pdf->SetCreator('NotaphilyCatalogue');
        $pdf->SetAuthor('NotaphilyCatalogue Admin');
        $pdf->SetTitle('Templates Export');
        
        // Set header and footer
        $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        
        // Set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        
        // Set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        
        // Set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        
        // Add a page
        $pdf->AddPage();
        
        // Set font
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->Cell(0, 10, Lang::get('manage_templates'), 0, 1, 'C');
        $pdf->Ln(10);
        
        // Table headers
        $pdf->SetFont('helvetica', 'B', 10);
        $headers = [
            Lang::get('collection_name'),
            Lang::get('author'),
            Lang::get('type'),
            Lang::get('status'),
            Lang::get('description')
        ];
        
        $colWidths = [50, 30, 20, 20, 70];
        $totalW = array_sum($colWidths);
        $pageW = $pdf->getPageWidth() - 20;
        if ($totalW > $pageW) {
            $ratio = $pageW / $totalW;
            $colWidths = array_map(fn($w) => $w * $ratio, $colWidths);
        }
        
        $pdf->SetFillColor(240, 240, 240);
        foreach ($headers as $i => $header) {
            $pdf->Cell($colWidths[$i], 7, $header, 1, 0, 'C', true);
        }
        $pdf->Ln();
        
        // Table data
        $pdf->SetFont('helvetica', '', 9);
        foreach ($templates as $template) {
            $pdf->Cell($colWidths[0], 8, htmlspecialchars($template['name']), 1, 0, 'L');
            $pdf->Cell($colWidths[1], 8, htmlspecialchars($template['owner_name']), 1, 0, 'L');
            $pdf->Cell($colWidths[2], 8, ($template['type'] ?? 'banknote') === 'coin' ? Lang::get('collection_type_coin') : Lang::get('collection_type_banknote'), 1, 0, 'C');
            $pdf->Cell($colWidths[3], 8, Lang::get('template'), 1, 0, 'C');
            $pdf->Cell($colWidths[4], 8, htmlspecialchars(mb_substr($template['description'] ?? '', 0, 100)), 1, 0, 'L');
            $pdf->Ln();
        }
        
        // Close and output PDF document
        $pdf->Output('templates.pdf', 'D');
        exit;
    }

    public function exportTemplatesXls(): void
    {
        $collectionModel = new Collection();
        $allCollections = $collectionModel->getAllForAdmin();
        
        // Filter only templates
        $templates = array_filter($allCollections, function($c) {
            return $c['is_template'] ?? false;
        });

        // Set headers for CSV download
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="templates.csv"');
        
        // Create output stream
        $output = fopen('php://output', 'w');
        
        // Add BOM for UTF-8
        fwrite($output, "\xEF\xBB\xBF");
        
        // Headers
        $headers = [
            Lang::get('collection_name'),
            Lang::get('author'),
            Lang::get('type'),
            Lang::get('status'),
            Lang::get('description')
        ];
        fputcsv($output, $headers);
        
        // Data
        foreach ($templates as $template) {
            $row = [
                $template['name'] ?? '',
                $template['owner_name'] ?? '',
                ($template['type'] ?? 'banknote') === 'coin' ? Lang::get('collection_type_coin') : Lang::get('collection_type_banknote'),
                Lang::get('template'),
                $template['description'] ?? ''
            ];
            fputcsv($output, $row);
        }
        
        fclose($output);
        exit;
    }

    public function dashboard(): void
    {
        $totalUsers = $this->userModel->countAll();
        $pendingUsers = $this->userModel->countByStatus('pending');
        $collectionModel = new Collection();
        $totalCollections = $collectionModel->countAll();
        $settings = $this->settingModel->getAll();
        require APP_ROOT . '/views/admin/dashboard.php';
    }

    public function users(): void
    {
        $users = $this->userModel->getAll();
        require APP_ROOT . '/views/admin/users.php';
    }

    public function approveUser(string $id): void
    {
        $user = $this->userModel->findById((int)$id);
        $this->userModel->updateStatus((int)$id, 'approved');

        if ($user && !empty($user['email'])) {
            require_once APP_ROOT . '/helpers/Mailer.php';
            Mailer::sendAccountApprovedEmail($user['email'], $user['display_name'] ?? $user['username']);
        }

        Session::flash('success', Lang::get('user_approved'));
        header('Location: ' . APP_URL . '/admin/users');
        exit;
    }

    public function rejectUser(string $id): void
    {
        $this->userModel->updateStatus((int)$id, 'rejected');
        Session::flash('success', Lang::get('user_rejected'));
        header('Location: ' . APP_URL . '/admin/users');
        exit;
    }

    public function editUser(string $id): void
    {
        $editingUser = $this->userModel->findById((int)$id);
        if (!$editingUser) {
            header('Location: ' . APP_URL . '/admin/users');
            exit;
        }
        require APP_ROOT . '/views/admin/edit_user.php';
    }

    public function updateUser(string $id): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/admin/users/' . $id . '/edit');
            exit;
        }

        $displayName = trim($_POST['display_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $role = $_POST['role'] ?? 'user';
        $status = $_POST['status'] ?? 'pending';

        $this->userModel->adminUpdate((int)$id, [
            'display_name' => $displayName,
            'email'        => $email,
            'role'         => $role,
            'status'       => $status,
        ]);

        Session::flash('success', Lang::get('user_updated'));
        header('Location: ' . APP_URL . '/admin/users');
        exit;
    }

    public function deleteUser(string $id): void
    {
        if ((int)$id === Session::getUserId()) {
            Session::flash('error', Lang::get('cannot_delete_self'));
            header('Location: ' . APP_URL . '/admin/users');
            exit;
        }
        $this->userModel->delete((int)$id);
        Session::flash('success', Lang::get('user_deleted'));
        header('Location: ' . APP_URL . '/admin/users');
        exit;
    }

    public function templates(): void
    {
        error_log('AdminController::templates called with GET params: ' . json_encode($_GET)); // Debug log
        
        $collectionModel = new Collection();
        $allCollections = $collectionModel->getAllForAdmin();
        
        // Handle AJAX search
        if (isset($_GET['search']) && !empty($_GET['search'])) {
            $search = strtolower(trim($_GET['search']));
            error_log("Search term: " . $search); // Debug log
            $allCollections = array_filter($allCollections, function($c) use ($search) {
                return strpos(strtolower($c['name']), $search) !== false || 
                       strpos(strtolower($c['owner_name']), $search) !== false;
            });
        }
        
        // Handle sorting
        $sortBy = $_GET['sort'] ?? 'name';
        $order = $_GET['order'] ?? 'asc';
        
        usort($allCollections, function($a, $b) use ($sortBy, $order) {
            $comparison = 0;
            switch ($sortBy) {
                case 'name':
                    $comparison = strcmp($a['name'], $b['name']);
                    break;
                case 'owner':
                    $comparison = strcmp($a['owner_name'], $b['owner_name']);
                    break;
                case 'type':
                    $comparison = strcmp($a['type'] ?? 'banknote', $b['type'] ?? 'banknote');
                    break;
                case 'status':
                    $comparison = ($a['is_template'] ?? 0) - ($b['is_template'] ?? 0);
                    break;
            }
            return $order === 'desc' ? -$comparison : $comparison;
        });
        
        require APP_ROOT . '/views/admin/templates.php';
    }

    public function toggleTemplate(string $id): void
    {
        $collectionModel = new Collection();
        $collection = $collectionModel->findById((int)$id);
        if ($collection) {
            $collectionModel->setTemplate((int)$id, !$collection['is_template']);
            Session::flash('success', Lang::get('template_updated'));
        }
        header('Location: ' . APP_URL . '/admin/templates');
        exit;
    }

    public function settings(): void
    {
        $settings = $this->settingModel->getAll();
        require APP_ROOT . '/views/admin/settings.php';
    }

    public function updateSettings(): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/admin/settings');
            exit;
        }

        $this->settingModel->set('email_provider', trim($_POST['email_provider'] ?? 'sendgrid'));
        $this->settingModel->set('sendgrid_api_key', trim($_POST['sendgrid_api_key'] ?? ''));
        $this->settingModel->set('mailersend_api_token', trim($_POST['mailersend_api_token'] ?? ''));
        $this->settingModel->set('from_email', trim($_POST['from_email'] ?? ''));
        $this->settingModel->set('admin_email', trim($_POST['admin_email'] ?? ''));
        
        // Save registration settings
        $this->settingModel->set('auto_approve_registrations', isset($_POST['auto_approve_registrations']) ? '1' : '0');
        $this->settingModel->set('email_verification_required', isset($_POST['email_verification_required']) ? '1' : '0');

        // Save reCAPTCHA settings
        $this->settingModel->set('recaptcha_enabled', isset($_POST['recaptcha_enabled']) ? '1' : '0');
        $this->settingModel->set('recaptcha_site_key', trim($_POST['recaptcha_site_key'] ?? ''));
        $this->settingModel->set('recaptcha_secret_key', trim($_POST['recaptcha_secret_key'] ?? ''));

        // Save Numista settings
        $this->settingModel->set('download_numista_large_images', isset($_POST['download_numista_large_images']) ? '1' : '0');

        Session::flash('success', Lang::get('settings_saved'));
        header('Location: ' . APP_URL . '/admin/settings');
        exit;
    }

    // --- Condition Options ---

    public function conditionOptions(): void
    {
        $model = new ConditionOption();
        $options = $model->getAll();
        require APP_ROOT . '/views/admin/condition_options.php';
    }

    public function storeConditionOption(): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/admin/condition-options');
            exit;
        }
        $model = new ConditionOption();
        $model->create([
            'label'       => trim($_POST['label'] ?? ''),
            'description' => trim($_POST['description'] ?? ''),
            'sort_order'  => (int)($_POST['sort_order'] ?? 0),
            'type'        => $_POST['type'] ?? 'both',
        ]);
        Session::flash('success', Lang::get('option_saved'));
        header('Location: ' . APP_URL . '/admin/condition-options');
        exit;
    }

    public function updateConditionOption(string $id): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/admin/condition-options');
            exit;
        }
        $model = new ConditionOption();
        $model->update((int)$id, [
            'label'       => trim($_POST['label'] ?? ''),
            'description' => trim($_POST['description'] ?? ''),
            'sort_order'  => (int)($_POST['sort_order'] ?? 0),
            'type'        => $_POST['type'] ?? 'both',
        ]);
        Session::flash('success', Lang::get('option_saved'));
        header('Location: ' . APP_URL . '/admin/condition-options');
        exit;
    }

    public function deleteConditionOption(string $id): void
    {
        $model = new ConditionOption();
        $model->delete((int)$id);
        Session::flash('success', Lang::get('option_deleted'));
        header('Location: ' . APP_URL . '/admin/condition-options');
        exit;
    }

    // --- Variant Type Options ---

    public function variantTypeOptions(): void
    {
        $model = new VariantTypeOption();
        $options = $model->getAll();
        require APP_ROOT . '/views/admin/variant_type_options.php';
    }

    public function storeVariantTypeOption(): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/admin/variant-type-options');
            exit;
        }
        $model = new VariantTypeOption();
        
        $data = [
            'label'      => trim($_POST['label_en'] ?? ''),
            'sort_order' => (int)($_POST['sort_order'] ?? 0),
        ];
        
        // Add all language translations
        $languages = ['en', 'sr', 'de', 'es', 'fr', 'it', 'pt', 'nl', 'pl', 'ru', 'tr', 'cs', 'el', 'hu', 'ro', 'sv', 'no', 'jp', 'cn', 'il'];
        foreach ($languages as $lang) {
            $field = 'label_' . $lang;
            if (isset($_POST[$field])) {
                $data[$field] = trim($_POST[$field]);
            }
        }
        
        $model->create($data);
        Session::flash('success', Lang::get('option_saved'));
        header('Location: ' . APP_URL . '/admin/variant-type-options');
        exit;
    }

    public function updateVariantTypeOption(string $id): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/admin/variant-type-options');
            exit;
        }
        $model = new VariantTypeOption();
        
        $data = [
            'label'      => trim($_POST['label_en'] ?? ''),
            'sort_order' => (int)($_POST['sort_order'] ?? 0),
        ];
        
        // Add all language translations
        $languages = ['en', 'sr', 'de', 'es', 'fr', 'it', 'pt', 'nl', 'pl', 'ru', 'tr', 'cs', 'el', 'hu', 'ro', 'sv', 'no', 'jp', 'cn', 'il'];
        foreach ($languages as $lang) {
            $field = 'label_' . $lang;
            if (isset($_POST[$field])) {
                $data[$field] = trim($_POST[$field]);
            }
        }
        
        $model->update((int)$id, $data);
        Session::flash('success', Lang::get('option_saved'));
        header('Location: ' . APP_URL . '/admin/variant-type-options');
        exit;
    }

    public function deleteVariantTypeOption(string $id): void
    {
        $model = new VariantTypeOption();
        $model->delete((int)$id);
        Session::flash('success', Lang::get('option_deleted'));
        header('Location: ' . APP_URL . '/admin/variant-type-options');
        exit;
    }
}
