<?php
namespace ComptaFlowUK\Admin\Actions;

use ComptaFlowUK\Services\InvoiceService;
use ComptaFlowUK\Services\ClientService;
use ComptaFlowUK\Services\PDFGenerator;

defined('ABSPATH') || exit;

class PDFActions {

    public static function boot(): void {
        add_action('admin_post_comptaflow_uk_pdf_download', [self::class, 'handleDownload']);
        add_action('admin_post_comptaflow_uk_pdf_view', [self::class, 'handleView']);
    }

    public static function handleDownload(): void {
        self::handle(true);
    }

    public static function handleView(): void {
        self::handle(false);
    }

    private static function handle(bool $download): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions.', 'comptaflow-uk-by-meetempo'));
        }

        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
        if (!wp_verify_nonce($nonce, 'comptaflow_uk_pdf')) {
            wp_die(esc_html__('Security check failed.', 'comptaflow-uk-by-meetempo'));
        }

        $id = isset($_GET['id']) ? absint($_GET['id']) : 0;
        if (!$id) {
            wp_die(esc_html__('Invalid invoice.', 'comptaflow-uk-by-meetempo'));
        }

        $invoice = InvoiceService::getById($id);
        if (!$invoice) {
            wp_die(esc_html__('Invoice not found.', 'comptaflow-uk-by-meetempo'));
        }

        $lines = InvoiceService::getLines($id);
        $client = $invoice['client_id'] ? ClientService::getById((int) $invoice['client_id']) : [];
        $company = get_option('comptaflow_uk_company_settings', []);

        PDFGenerator::streamPDF($invoice, $lines, $client ?: [], $company, $download);
    }
}
