<?php
/**
 * OVP-Sponsorizare
 *
 * @package   OVPSPO_Sponsorizare
 * @author    Ovidiu Pantiru - OVP-Digital
 * @copyright 2024 Ovidiu Pantiru
 * @license   GPL-2.0+
 * @link      https://ovidiupantiru.ro
 */

if ( ! defined( 'ABSPATH' ) ) exit;

if ( ! class_exists('OVPSPO_Settings') ) {
class OVPSPO_Settings {

    const OPT = 'ovpspo_settings';

    public static function init() {
        // Notificare admin daca OVPSPO_TCPDF nu e instalat
        add_action( 'admin_notices', array( __CLASS__, 'tcpdf_notice' ) );
        add_action( 'admin_init',    array( __CLASS__, 'handle_tcpdf_reinstall' ) );
        add_action( 'admin_menu',            array( __CLASS__, 'add_menu' ) );
        add_action( 'admin_init',            array( __CLASS__, 'register_settings' ) );
        add_action( 'admin_init',            array( __CLASS__, 'handle_actions' ) );
        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'admin_assets' ) );
        add_action( 'admin_init',            array( __CLASS__, 'maybe_upgrade_db' ) );
    }

    /* ── Upgrade DB ── */
    public static function maybe_upgrade_db() {
        global $wpdb;
        $charset = $wpdb->get_charset_collate();

        // Upgrade v4 - adauga coloanele xml_path si pdf_path la f177_submissions
        $t177 = $wpdb->prefix . 'f177_submissions';
        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $t177 ) ) === $t177 ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $cols = $wpdb->get_results( "SHOW COLUMNS FROM " . esc_sql($t177), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $col_names = array_column( $cols, 'Field' );
            if ( ! in_array( 'xml_path', $col_names, true ) ) {
                $wpdb->query( "ALTER TABLE " . esc_sql($t177) . " ADD COLUMN xml_path VARCHAR(255) DEFAULT NULL" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange
            }
            if ( ! in_array( 'pdf_path', $col_names, true ) ) {
                $wpdb->query( "ALTER TABLE " . esc_sql($t177) . " ADD COLUMN pdf_path VARCHAR(255) DEFAULT NULL" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange
            }
        }

        // Upgrade v3 - adauga coloana pdf_anaf_path
        if ( ! get_option('ovpspo_db_v3') ) {
            $t230 = $wpdb->prefix . 'f230_submissions';
            if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $t230 ) ) === $t230 ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $col = $wpdb->get_results( "SHOW COLUMNS FROM " . esc_sql($t230) . " LIKE 'pdf_anaf_path'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
                if ( empty($col) ) {
                    $wpdb->query( "ALTER TABLE " . esc_sql($t230) . " ADD COLUMN pdf_anaf_path VARCHAR(255) DEFAULT NULL AFTER pdf_path" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange
                }
            }
            update_option('ovpspo_db_v3', 1);
        }

        // Creeaza tabelul contracte MEREU daca nu exista
        $tc = $wpdb->prefix . 'contracte_sponsorizare';
        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $tc ) ) !== $tc ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta( "CREATE TABLE IF NOT EXISTS $tc (
                id               BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                data_trimitere   DATETIME NOT NULL,
                nr_contract      VARCHAR(50),
                data_contract    DATE,
                tip_sponsor      VARCHAR(20),
                sponsor_nume     VARCHAR(200),
                sponsor_cui      VARCHAR(20),
                sponsor_email    VARCHAR(200),
                tip_sponsorizare VARCHAR(20),
                suma             DECIMAL(12,2) DEFAULT 0,
                pdf_path         VARCHAR(255),
                ip               VARCHAR(45),
                PRIMARY KEY (id)
            ) $charset;" );
        }
    }

    /* ── Meniu admin ── */
    public static function add_menu() {
        // Meniu principal: OVP-Sponsorizare
        add_menu_page(
            'OVP-Sponsorizare', 'OVP-Sponsorizare', 'manage_options',
            'ovp-sponsorizare', array( __CLASS__, 'page_dashboard' ),
            'dashicons-money-alt', 30
        );

        // Submeniu: Dashboard
        add_submenu_page(
            'ovp-sponsorizare', 'Dashboard', 'Dashboard', 'manage_options',
            'ovp-sponsorizare', array( __CLASS__, 'page_dashboard' )
        );

        // Submeniu: Formular 230
        add_submenu_page(
            'ovp-sponsorizare', 'Formulare 230', 'Formulare 230', 'manage_options',
            'ovpspo-f230', array( __CLASS__, 'page_f230' )
        );

        // Submeniu: Formular 177
        add_submenu_page(
            'ovp-sponsorizare', 'Formulare 177', 'Formulare 177', 'manage_options',
            'ovpspo-f177', array( __CLASS__, 'page_f177' )
        );

        // Submeniu: Contracte
        add_submenu_page(
            'ovp-sponsorizare', 'Contracte Sponsorizare', 'Contracte Sponsorizare', 'manage_options',
            'ovpspo-contracte', array( __CLASS__, 'page_contracte' )
        );

        // Submeniu: Setari
        add_submenu_page(
            'ovp-sponsorizare', 'Setări', 'Setări', 'manage_options',
            'ovpspo-settings', array( __CLASS__, 'page_settings' )
        );
    }

    public static function admin_assets( $hook ) {
        if ( strpos($hook, 'ovp') === false && strpos($hook, 'ovp-sponsorizare') === false ) return;
        wp_enqueue_style( 'ovpspo-admin', OVPSPO_URL . 'assets/css/admin.css', array(), OVPSPO_VERSION );
        wp_enqueue_script( 'ovpspo-admin', OVPSPO_URL . 'assets/js/admin.js', array(), OVPSPO_VERSION, true );
    }

    public static function register_settings() {
        register_setting( 'ovpspo_group', self::OPT, array( __CLASS__, 'sanitize' ) );
    }

    public static function sanitize( $input ) {
        $clean = array();

        // Text fields
        $text_fields = array(
            'org_nume', 'org_cif', 'org_adresa', 'org_iban',
            'org_email_from_name', 'org_telefon',
            'email_subiect_admin', 'email_subiect_user',
            'org_judet', 'org_sector', 'org_localitate', 'org_cod_postal',
            'org_strada', 'org_info_adresa', 'org_fax',
            'org_reprezentant', 'org_functie_rep', 'org_banca',
            'org_reg_asociatii', 'org_data_inreg',
        );
        foreach ( $text_fields as $f ) {
            $clean[ $f ] = sanitize_text_field( isset( $input[ $f ] ) ? $input[ $f ] : '' );
        }

        // Hex color for brand color (uses sanitize_hex_color)
        $clean['org_culoare'] = isset( $input['org_culoare'] ) ? sanitize_hex_color( $input['org_culoare'] ) : '#0F408A';

        // Email fields
        $email_fields = array( 'org_email_admin', 'org_email_from', 'org_email_public' );
        foreach ( $email_fields as $f ) {
            $clean[ $f ] = sanitize_email( isset( $input[ $f ] ) ? $input[ $f ] : '' );
        }

        // URL fields
        $clean['org_website'] = isset( $input['org_website'] ) ? esc_url_raw( $input['org_website'] ) : '';

        // Color fields (hex colors)
        $color_fields = array( 'culoare_header', 'culoare_accent', 'culoare_sectiuni', 'culoare_buton', 'culoare_text' );
        foreach ( $color_fields as $f ) {
            $clean[ $f ] = isset( $input[ $f ] ) ? sanitize_hex_color( $input[ $f ] ) : '';
        }
        $clean['an_fiscal']    = absint( isset($input['an_fiscal']) ? $input['an_fiscal'] : (gmdate('Y')-1) );
        $clean['trimite_user'] = !empty($input['trimite_user']) ? 1 : 0;
        $clean['salveaza_pdf'] = !empty($input['salveaza_pdf']) ? 1 : 0;
        return $clean;
    }

    public static function get( $key = null, $default = '' ) {
        $opts = get_option( self::OPT, array() );
        if ( $key === null ) return $opts;
        return isset($opts[$key]) ? $opts[$key] : $default;
    }

    /* ══════════════════════════════════════════
       HANDLE ACTIUNI (download, delete)
    ══════════════════════════════════════════ */
    public static function tcpdf_notice() {
        if ( ! current_user_can('manage_options') ) return;

        // Verifica TOATE locatiile posibile ale OVPSPO_TCPDF
        $tcpdf_locations = array(
            // 1. Bundled in plugin (cel mai important!)
            defined('OVPSPO_PATH')       ? OVPSPO_PATH   . 'lib/tcpdf/tcpdf.php' : '',
            defined('OVPSPO_PATH')     ? OVPSPO_PATH . 'lib/tcpdf/tcpdf.php' : '',
            // 2. Instalat extern
            defined('OVPSPO_TCPDF_PATH') ? OVPSPO_TCPDF_PATH : '',
            ( defined('OVPSPO_TCPDF_PATH') ? OVPSPO_TCPDF_PATH : '' ),
        );

        // OVPSPO_TCPDF e disponibil - totul e ok
        if ( class_exists('OVPSPO_TCPDF') ) {
            delete_option('ovpspo_tcpdf_status');
            return;
        }
        foreach ( $tcpdf_locations as $loc ) {
            if ( $loc && file_exists( $loc ) ) {
                delete_option('ovpspo_tcpdf_status');
                return;
            }
        }

        $status = get_option('ovpspo_tcpdf_status', '');

        // Mesaje diferite in functie de ce a esuat
        $messages = array(
            'download_failed' => array(
                'type' => 'error',
                'msg'  => 'Nu s-a putut descărca OVPSPO_TCPDF automat (serverul nu are acces la internet sau GitHub e blocat). '
                        . 'PDF-urile nu se pot genera deocamdată.',
                'action' => 'retry',
            ),
            'no_zip'          => array(
                'type' => 'error',
                'msg'  => 'Extensia PHP <code>ZipArchive</code> lipsește de pe server. '
                        . 'Contactați hostingul să o activeze, apoi reactivați pluginul.',
                'action' => 'none',
            ),
            'zip_error'       => array(
                'type' => 'error',
                'msg'  => 'Arhiva OVPSPO_TCPDF descărcată este coruptă. Reactivați pluginul pentru a reîncerca.',
                'action' => 'retry',
            ),
            'install_failed'  => array(
                'type' => 'warning',
                'msg'  => 'OVPSPO_TCPDF a fost descărcat dar instalarea a eșuat. Reactivați pluginul sau instalați manual.',
                'action' => 'retry',
            ),
            ''                => array(
                'type' => 'error',
                'msg'  => 'OVPSPO_TCPDF nu este instalat. PDF-urile nu se pot genera.',
                'action' => 'retry',
            ),
        );

        $info = isset($messages[$status]) ? $messages[$status] : $messages[''];

        echo '<div class="notice notice-' . esc_attr($info['type']) . ' is-dismissible"><p>';
        echo '<strong>OVP-Sponsorizare:</strong> ' . wp_kses_post($info['msg']) . ' ';

        if ( $info['action'] === 'retry' ) {
            $retry_url = wp_nonce_url(
                add_query_arg('ovpspo_reinstall_tcpdf', '1', admin_url('admin.php?page=ovpspo-settings')),
                'ovpspo_reinstall_tcpdf'
            );
            echo '<a href="' . esc_url($retry_url) . '" class="button button-small">🔄 Reîncearcă instalarea OVPSPO_TCPDF</a>';
        }

        echo '</p></div>';
    }

    /**
     * Permite reincercarea instalarii OVPSPO_TCPDF din admin
     */
    public static function handle_tcpdf_reinstall() {
        if ( ! isset($_GET['ovpspo_reinstall_tcpdf']) ) return;
        if ( ! current_user_can('manage_options') ) return;
        if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ?? '' ) ), 'ovpspo_reinstall_tcpdf' ) ) return;

        // Verifica mai intai daca OVPSPO_TCPDF bundled exista
        $bundled = defined('OVPSPO_PATH') ? OVPSPO_PATH . 'lib/tcpdf/tcpdf.php' : '';
        if ( $bundled && file_exists( $bundled ) ) {
            delete_option('ovpspo_tcpdf_status');
            wp_safe_redirect( add_query_arg('ovpspo_msg', 'tcpdf_ok', admin_url('admin.php?page=ovpspo-settings')) );
            exit;
        }

        // Incearca download extern
        delete_option('ovpspo_tcpdf_status');
        $ok = ovp_sponsorizare_install_tcpdf();

        $msg = $ok ? 'tcpdf_ok' : 'tcpdf_fail';
        wp_safe_redirect( add_query_arg('ovpspo_msg', $msg, admin_url('admin.php?page=ovpspo-settings')) );
        exit;
    }

    public static function handle_actions() {
        if ( ! current_user_can('manage_options') ) return;
        global $wpdb;

        $action = sanitize_text_field( wp_unslash( $_GET['ovpspo_action'] ?? '' ) );
        $id     = absint( wp_unslash( $_GET['id'] ?? 0 ) );
        $nonce  = sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ?? '' ) );

        if ( ! $action || ! $id ) return;

        /* ── 230: Download PDF Branded ── */
        if ( $action === 'dl230' && wp_verify_nonce($nonce, 'ovpspo_dl230_'.$id) ) {
            $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM " . esc_sql($wpdb->prefix . "f230_submissions") . " WHERE id=%d", $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            if ( $row && $row->pdf_path && file_exists($row->pdf_path) ) {
                self::stream_pdf($row->pdf_path, 'Formular_230_'.sanitize_file_name($row->cnp).'_'.$id.'.pdf');
            }
            wp_safe_redirect(add_query_arg(array('page'=>'ovpspo-f230','msg'=>'missing'), admin_url('admin.php'))); exit;
        }

        /* ── 230: Download PDF ANAF ── */
        if ( $action === 'dl230anaf' && wp_verify_nonce($nonce, 'ovpspo_dl230anaf_'.$id) ) {
            $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM " . esc_sql($wpdb->prefix . "f230_submissions") . " WHERE id=%d", $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
            if ( $row && !empty($row->pdf_anaf_path) && file_exists($row->pdf_anaf_path) ) {
                self::stream_pdf($row->pdf_anaf_path, 'Formular_ANAF_230_'.sanitize_file_name($row->cnp).'_'.$id.'.pdf');
            }
            // Incearca regenerare
            if ( $row ) {
                $data = self::row230_to_data($row);
                try {
                    $path = OVPSPO_PDF_ANAF::generate($data, $id);
                    if ($path) {
                        $wpdb->update( "{$wpdb->prefix}f230_submissions", array('pdf_anaf_path'=>$path), array('id'=>$id) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                        self::stream_pdf($path, 'Formular_ANAF_230_'.sanitize_file_name($row->cnp).'_'.$id.'.pdf');
                    }
                } catch(Exception $e) {}
            }
            wp_safe_redirect(add_query_arg(array('page'=>'ovpspo-f230','msg'=>'missing'), admin_url('admin.php'))); exit;
        }

        /* ── 230: Delete ── */
        if ( $action === 'del230' && wp_verify_nonce($nonce, 'ovpspo_del230_'.$id) ) {
            $row = $wpdb->get_row( $wpdb->prepare( "SELECT pdf_path,pdf_anaf_path FROM {$wpdb->prefix}f230_submissions WHERE id=%d", $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            if ($row) {
                if ($row->pdf_path && file_exists($row->pdf_path)) wp_delete_file($row->pdf_path);
                if (!empty($row->pdf_anaf_path) && file_exists($row->pdf_anaf_path)) wp_delete_file($row->pdf_anaf_path);
            }
            $wpdb->delete( "{$wpdb->prefix}f230_submissions", array('id'=>$id) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            wp_safe_redirect(add_query_arg(array('page'=>'ovpspo-f230','msg'=>'deleted'), admin_url('admin.php'))); exit;
        }

        /* ── 177: Download PDF ── */
        if ( $action === 'dl177' && wp_verify_nonce($nonce, 'ovpspo_dl177_'.$id) ) {
            $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . esc_sql($wpdb->prefix . "f177_submissions") . " WHERE id=%d", $id)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            if ( $row && !empty($row->pdf_path) && file_exists($row->pdf_path) ) {
                self::stream_pdf($row->pdf_path, 'Formular_D177_'.sanitize_file_name($row->cif).'_'.$id.'.pdf');
            }
            wp_safe_redirect(add_query_arg(array('page'=>'ovpspo-f177','msg'=>'missing'), admin_url('admin.php'))); exit;
        }

        /* ── 177: Download XML ── */
        if ( $action === 'dlxml177' && wp_verify_nonce($nonce, 'ovpspo_dlxml177_'.$id) ) {
            $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . esc_sql($wpdb->prefix . "f177_submissions") . " WHERE id=%d", $id)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            if ( $row && !empty($row->xml_path) && file_exists($row->xml_path) ) {
                $filename = 'D177_' . sanitize_file_name($row->cif) . '_' . $id . '.xml';
                header('Content-Type: application/xml; charset=UTF-8');
                header('Content-Disposition: attachment; filename="' . $filename . '"');
                header('Content-Length: ' . filesize($row->xml_path));
                header('Cache-Control: private, no-cache');
                readfile($row->xml_path); // phpcs:ignore
                exit;
            }
            wp_safe_redirect(add_query_arg(array('page'=>'ovpspo-f177','msg'=>'missing'), admin_url('admin.php'))); exit;
        }

        /* ── 177: Delete ── */
        if ( $action === 'del177' && wp_verify_nonce($nonce, 'ovpspo_del177_'.$id) ) {
            $row = $wpdb->get_row( $wpdb->prepare( "SELECT pdf_path, xml_path FROM {$wpdb->prefix}f177_submissions WHERE id=%d", $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            if ($row) {
                if (!empty($row->pdf_path) && file_exists($row->pdf_path)) wp_delete_file($row->pdf_path);
                if (!empty($row->xml_path) && file_exists($row->xml_path)) wp_delete_file($row->xml_path);
            }
            $wpdb->delete( "{$wpdb->prefix}f177_submissions", array('id'=>$id) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            wp_safe_redirect(add_query_arg(array('page'=>'ovpspo-f177','msg'=>'deleted'), admin_url('admin.php'))); exit;
        }

        /* ── Contract: Download PDF ── */
        if ( $action === 'dl_contract' && wp_verify_nonce($nonce, 'ovpspo_dlc_'.$id) ) {
            $tc  = $wpdb->prefix . 'contracte_sponsorizare';
            $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM " . esc_sql($tc) . " WHERE id=%d", $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            if ( $row && $row->pdf_path && file_exists($row->pdf_path) ) {
                self::stream_pdf($row->pdf_path, basename($row->pdf_path));
            }
            wp_safe_redirect(add_query_arg(array('page'=>'ovpspo-contracte','msg'=>'missing'), admin_url('admin.php'))); exit;
        }

        /* ── Contract: Delete ── */
        if ( $action === 'del_contract' && wp_verify_nonce($nonce, 'ovpspo_delc_'.$id) ) {
            $tc  = $wpdb->prefix . 'contracte_sponsorizare';
            $row = $wpdb->get_row( $wpdb->prepare( "SELECT pdf_path FROM " . esc_sql($tc) . " WHERE id=%d", $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            if ($row && $row->pdf_path && file_exists($row->pdf_path)) wp_delete_file($row->pdf_path);
            $wpdb->delete( $tc, array('id'=>$id) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            wp_safe_redirect(add_query_arg(array('page'=>'ovpspo-contracte','msg'=>'deleted'), admin_url('admin.php'))); exit;
        }
    }

    private static function stream_pdf($path, $filename) {
        if (ob_get_level()) ob_end_clean();
        header('Content-Type: application/pdf');
        // Validare path - trebuie sa fie in folderul uploads WordPress
        $upload_dir  = wp_upload_dir();
        $allowed_base = realpath( $upload_dir['basedir'] );
        $real_path    = realpath( $path );
        if ( ! $real_path || false === strpos( $real_path, $allowed_base ) ) {
            wp_die( esc_html__( 'Acces interzis.', 'ovp-sponsorizare' ) );
        }
        header('Content-Disposition: attachment; filename="' . esc_attr( $filename ) . '"');
        header('Content-Length: '.filesize($path));
        header('Cache-Control: private, no-cache');
        readfile( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile
        exit;
    }

    private static function row230_to_data($row) {
        return array(
            'nume'=>$row->nume, 'prenume'=>$row->prenume, 'initiala'=>$row->initiala,
            'cnp'=>$row->cnp, 'email'=>$row->email, 'telefon'=>$row->telefon,
            'judet'=>$row->judet, 'localitate'=>$row->localitate, 'cod_postal'=>$row->cod_postal,
            'strada'=>$row->strada, 'nr'=>$row->nr, 'bloc'=>$row->bloc,
            'scara'=>$row->scara, 'etaj'=>$row->etaj, 'apart'=>$row->apart,
            'perioada'=>$row->perioada, 'an_fiscal'=>$row->an_fiscal,
            'gdpr'=>$row->gdpr, 'signature'=>'',
        );
    }

    /* ══════════════════════════════════════════
       DASHBOARD
    ══════════════════════════════════════════ */
    public static function page_dashboard() {
        global $wpdb;
        $cnt230  = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}f230_submissions" ) ?: 0; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
        $cnt177  = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}f177_submissions" ) ?: 0; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
        $suma177 = $wpdb->get_var( "SELECT SUM(bnf_suma) FROM {$wpdb->prefix}f177_submissions" ) ?: 0; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
        $org = self::get('org_nume', '—');
        ?>
        <div class="wrap ovp-admin">
            <h1>OVP-Sponsorizare <span style="font-size:14px;font-weight:400;color:#666">v<?php echo esc_html( OVPSPO_VERSION ); ?></span></h1>

            <div class="ovp-dashboard-grid">
                <div class="ovp-dash-card ovp-dash-blue">
                    <div class="ovp-dash-icon"><span class="dashicons dashicons-feedback"></span></div>
                    <div class="ovp-dash-info">
                        <div class="ovp-dash-num"><?php echo intval( $cnt230 ); ?></div>
                        <div class="ovp-dash-label">Formulare 230 primite</div>
                        <div class="ovp-dash-sub">Persoane fizice — 3,5% impozit venit</div>
                        <a href="<?php echo esc_url( admin_url('admin.php?page=ovpspo-f230') ); ?>" class="ovp-dash-link">Vezi toate →</a>
                    </div>
                </div>
                <div class="ovp-dash-card ovp-dash-green">
                    <div class="ovp-dash-icon"><span class="dashicons dashicons-building"></span></div>
                    <div class="ovp-dash-info">
                        <div class="ovp-dash-num"><?php echo intval( $cnt177 ); ?></div>
                        <div class="ovp-dash-label">Formulare 177 primite</div>
                        <div class="ovp-dash-sub">Persoane juridice — impozit profit</div>
                        <a href="<?php echo esc_url( admin_url('admin.php?page=ovpspo-f177') ); ?>" class="ovp-dash-link">Vezi toate →</a>
                    </div>
                </div>
                <div class="ovp-dash-card ovp-dash-gold">
                    <div class="ovp-dash-icon"><span class="dashicons dashicons-money-alt"></span></div>
                    <div class="ovp-dash-info">
                        <div class="ovp-dash-num"><?php echo number_format($suma177, 2, ',', '.'); ?> lei</div>
                        <div class="ovp-dash-label">Sumă declarată în formularele 177</div>
                        <div class="ovp-dash-sub">Suma efectivă aprobată de ANAF poate diferi</div>
                    </div>
                </div>
                <div class="ovp-dash-card ovp-dash-purple">
                    <div class="ovp-dash-icon"><span class="dashicons dashicons-edit"></span></div>
                    <div class="ovp-dash-info">
                        <?php
                        $cnt_c = 0;
                        $tc = $wpdb->prefix . 'contracte_sponsorizare';
                        if ($wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $tc ) ) === $tc ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                            $cnt_c = $wpdb->get_var( "SELECT COUNT(*) FROM " . esc_sql($tc) ) ?: 0; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
                        }
                        ?>
                        <div class="ovp-dash-num"><?php echo intval( $cnt_c ); ?></div>
                        <div class="ovp-dash-label">Contracte sponsorizare</div>
                        <div class="ovp-dash-sub">Persoane fizice și juridice</div>
                        <a href="<?php echo esc_url( admin_url('admin.php?page=ovpspo-contracte') ); ?>" class="ovp-dash-link">Vezi toate →</a>
                    </div>
                </div>
                <div class="ovp-dash-card ovp-dash-gray">
                    <div class="ovp-dash-icon"><span class="dashicons dashicons-bank"></span></div>
                    <div class="ovp-dash-info">
                        <div class="ovp-dash-num" style="font-size:16px"><?php echo esc_html($org ?: '— neconfigurat —'); ?></div>
                        <div class="ovp-dash-label">Organizație configurată</div>
                        <a href="<?php echo esc_url( admin_url('admin.php?page=ovpspo-settings') ); ?>" class="ovp-dash-link">Setări →</a>
                    </div>
                </div>
            </div>

            <div class="ovp-info-box">
                <strong><span class="dashicons dashicons-info"></span> Despre sumele afișate:</strong>
                <ul style="margin:8px 0 0 20px;padding:0">
                    <li><strong>Formulare 230</strong> — suma redirecționată (3,5% din impozitul pe venit) este calculată de ANAF după depunere și nu este cunoscută în avans.</li>
                    <li><strong>Formulare 177</strong> — suma afișată este cea declarată de contribuabil în formular. Suma efectiv aprobată de ANAF poate fi diferită.</li>
                </ul>
            </div>

            <div class="ovp-shortcuts">
                <h3>Shortcode-uri</h3>
                <div class="ovp-shortcode-list">
                    <div class="ovp-shortcode-item">
                        <code>[ovpspo_formular230]</code> <code style="opacity:.6">[formular230]</code>
                        <span>Formular 230 — persoane fizice (redirecționare 3,5% impozit venit)</span>
                    </div>
                    <div class="ovp-shortcode-item">
                        <code>[ovpspo_formular177]</code> <code style="opacity:.6">[formular177]</code>
                        <span>Formular 177 — persoane juridice (redirecționare impozit profit)</span>
                    </div>
                    <div class="ovp-shortcode-item">
                        <code>[ovpspo_contract_sponsorizare]</code> <code style="opacity:.6">[contract_sponsorizare]</code>
                        <span>Contract sponsorizare — persoane fizice și juridice</span>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /* ══════════════════════════════════════════
       PAGINA FORMULARE 230
    ══════════════════════════════════════════ */
    public static function page_f230() {
        if ( ! current_user_can('manage_options') ) return;
        global $wpdb;
        $table = $wpdb->prefix . 'f230_submissions';
        $msg = sanitize_text_field( wp_unslash( $_GET['msg'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification
        $rows  = $wpdb->get_results( "SELECT * FROM " . esc_sql( $table ) . " ORDER BY data_trimitere DESC" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
        ?>
        <div class="wrap ovp-admin">
            <h1>Formulare 230 primite <span class="ovp-badge"><?php echo count($rows); ?> total</span></h1>

            <?php if ($msg==='deleted'): ?><div class="notice notice-success is-dismissible"><p>Formularul a fost șters.</p></div><?php endif; ?>
            <?php if ($msg==='missing'):  ?><div class="notice notice-warning is-dismissible"><p>PDF-ul nu a fost găsit. Încearcă regenerarea.</p></div><?php endif; ?>

            <div class="notice notice-info" style="padding:10px 16px">
                <p>Shortcode: <code>[ovpspo_formular230]</code> sau <code>[formular230]</code> — Formular pentru persoane fizice, redirecționare 3,5% din impozitul pe venit.</p>
            </div>

            <?php if ( empty($rows) ) : ?>
                <div class="ovp-empty"><p>Nu există formulare 230 completate încă.</p><p>Adaugă <code>[ovpspo_formular230]</code> pe o pagină.</p></div>
            <?php else : ?>
            <div class="ovp-card">
                <table class="widefat striped">
                    <thead><tr>
                        <th>#</th><th>Data</th><th>Nume complet</th><th>CNP</th>
                        <th>Județ</th><th>Email</th><th>Perioadă</th>
                        <th>PDF Branded</th><th>PDF ANAF</th><th>Acțiuni</th>
                    </tr></thead>
                    <tbody>
                    <?php foreach ($rows as $r):
                        $has_pdf  = !empty($r->pdf_path) && file_exists($r->pdf_path);
                        $has_anaf = !empty($r->pdf_anaf_path) && file_exists($r->pdf_anaf_path);
                        $u = array('page'=>'ovpspo-f230');
                        $dl230     = add_query_arg(array_merge($u,array('ovpspo_action'=>'dl230',     'id'=>$r->id,'_wpnonce'=>wp_create_nonce('ovpspo_dl230_'.$r->id))),     admin_url('admin.php'));
                        $dl230anaf = add_query_arg(array_merge($u,array('ovpspo_action'=>'dl230anaf', 'id'=>$r->id,'_wpnonce'=>wp_create_nonce('ovpspo_dl230anaf_'.$r->id))), admin_url('admin.php'));
                        $del230    = add_query_arg(array_merge($u,array('ovpspo_action'=>'del230',    'id'=>$r->id,'_wpnonce'=>wp_create_nonce('ovpspo_del230_'.$r->id))),    admin_url('admin.php'));
                    ?>
                        <tr>
                            <td><?php echo intval($r->id); ?></td>
                            <td><?php echo esc_html( gmdate('d.m.Y H:i', strtotime($r->data_trimitere)) ); ?></td>
                            <td><strong><?php echo esc_html($r->nume.' '.$r->prenume); ?></strong></td>
                            <td><code><?php echo esc_html($r->cnp); ?></code></td>
                            <td><?php echo esc_html($r->judet); ?></td>
                            <td><?php echo $r->email ? esc_html($r->email) : '—'; ?></td>
                            <td><?php echo esc_html( $r->perioada == 2 ? '2 ani' : '1 an' ); ?></td>
                            <td>
                                <?php if ($has_pdf): ?>
                                    <a href="<?php echo esc_url($dl230); ?>" class="button button-small button-primary"><span class="dashicons dashicons-download"></span> PDF</a>
                                <?php else: ?>
                                    <span style="color:#999;font-size:12px">lipsă</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($has_anaf): ?>
                                    <a href="<?php echo esc_url($dl230anaf); ?>" class="button button-small" style="background:#1a7a42;color:#fff;border-color:#1a7a42">⬇ ANAF</a>
                                <?php else: ?>
                                    <a href="<?php echo esc_url($dl230anaf); ?>" class="button button-small">↺ Gen. ANAF</a>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="<?php echo esc_url($del230); ?>" class="button button-small ovp-confirm-del" style="color:#a00" data-confirm="<?php esc_attr_e( 'Ștergi definitiv?', 'ovp-sponsorizare' ); ?>">Șterge</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
        <?php
    }

    /* ══════════════════════════════════════════
       PAGINA FORMULARE 177
    ══════════════════════════════════════════ */
    public static function page_f177() {
        if ( ! current_user_can('manage_options') ) return;
        global $wpdb;
        $table = $wpdb->prefix . 'f177_submissions';
        $msg = sanitize_text_field( wp_unslash( $_GET['msg'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification

        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $table ) ) !== $table ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            echo '<div class="wrap"><div class="notice notice-warning"><p>Tabelul D177 nu există. Dezactivați și reactivați pluginul.</p></div></div>';
            return;
        }

        $rows = $wpdb->get_results( "SELECT * FROM " . esc_sql( $table ) . " ORDER BY data_trimitere DESC" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
        $tip_labels = array(
            1 => 'Sponsorizare juridice / cult',
            2 => 'Sponsorizare alți beneficiari',
            3 => 'Acte de mecenat',
            4 => 'UNICEF / Internaționale',
        );
        ?>
        <div class="wrap ovp-admin">
            <h1>Formulare 177 primite <span class="ovp-badge"><?php echo count($rows); ?> total</span></h1>

            <?php if ($msg==='deleted'): ?><div class="notice notice-success is-dismissible"><p>Formularul a fost șters.</p></div><?php endif; ?>
            <?php if ($msg==='missing'):  ?><div class="notice notice-warning is-dismissible"><p>PDF-ul nu a fost găsit pe server.</p></div><?php endif; ?>

            <div class="notice notice-info" style="padding:10px 16px">
                <p>Shortcode: <code>[ovpspo_formular177]</code> sau <code>[formular177]</code> — Formular pentru persoane juridice, redirecționarea impozitului pe profit.</p>
            </div>

            <?php if ( empty($rows) ) : ?>
                <div class="ovp-empty"><p>Nu există formulare 177 completate încă.</p><p>Adaugă <code>[ovpspo_formular177]</code> pe o pagină.</p></div>
            <?php else : ?>
            <div class="ovp-card">
                <table class="widefat striped">
                    <thead><tr>
                        <th>#</th><th>Data</th><th>Denumire contribuabil</th><th>CIF</th>
                        <th>An</th><th>Beneficiar</th>
                        <th>Sumă (lei)</th><th>Descărcări</th><th>Acțiuni</th>
                    </tr></thead>
                    <tbody>
                    <?php foreach ($rows as $r):
                        $has_pdf = !empty($r->pdf_path) && file_exists($r->pdf_path);
                        $has_xml = !empty($r->xml_path) && file_exists($r->xml_path);
                        $u = array('page'=>'ovpspo-f177');
                        $dl177    = add_query_arg(array_merge($u,array('ovpspo_action'=>'dl177',    'id'=>$r->id,'_wpnonce'=>wp_create_nonce('ovpspo_dl177_'.$r->id))),    admin_url('admin.php'));
                        $dlxml177 = add_query_arg(array_merge($u,array('ovpspo_action'=>'dlxml177', 'id'=>$r->id,'_wpnonce'=>wp_create_nonce('ovpspo_dlxml177_'.$r->id))), admin_url('admin.php'));
                        $del177   = add_query_arg(array_merge($u,array('ovpspo_action'=>'del177',   'id'=>$r->id,'_wpnonce'=>wp_create_nonce('ovpspo_del177_'.$r->id))),   admin_url('admin.php'));
                    ?>
                        <tr>
                            <td><?php echo intval($r->id); ?></td>
                            <td><?php echo esc_html( gmdate('d.m.Y H:i', strtotime($r->data_trimitere)) ); ?></td>
                            <td><strong><?php echo esc_html($r->denumire); ?></strong><br><span style="font-size:11px;color:#666"><?php echo esc_html($r->email); ?></span></td>
                            <td><code><?php echo esc_html($r->cif); ?></code></td>
                            <td><?php echo esc_html($r->an); ?></td>
                            <td><?php echo esc_html($r->bnf_denumire); ?><br><span style="font-size:11px;color:#666"><?php echo esc_html($tip_labels[$r->tip_beneficiar] ?? '—'); ?></span></td>
                            <td><strong><?php echo number_format($r->bnf_suma, 2, ',', '.'); ?></strong> lei</td>
                            <td style="white-space:nowrap">
                                <?php if ($has_pdf): ?>
                                    <a href="<?php echo esc_url($dl177); ?>" class="button button-small button-primary" title="Descarcă PDF D177"><span class="dashicons dashicons-download"></span> PDF</a>
                                <?php else: ?>
                                    <span style="color:#bbb;font-size:11px">PDF lipsă</span>
                                <?php endif; ?>
                                &nbsp;
                                <?php if ($has_xml): ?>
                                    <a href="<?php echo esc_url($dlxml177); ?>" class="button button-small" style="background:#2271b1;color:#fff;border-color:#2271b1" title="Descarcă XML pentru SPV"><span class="dashicons dashicons-download"></span> XML</a>
                                <?php else: ?>
                                    <span style="color:#bbb;font-size:11px">XML lipsă</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="<?php echo esc_url($del177); ?>" class="button button-small ovp-confirm-del" style="color:#a00" data-confirm="<?php esc_attr_e( 'Ștergi definitiv formularul și fișierele asociate?', 'ovp-sponsorizare' ); ?>"><span class="dashicons dashicons-trash"></span> Șterge</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
        <?php
    }

    /* ══════════════════════════════════════════
       PAGINA SETARI - Design modern
    ══════════════════════════════════════════ */
    public static function page_settings() {
        if ( ! current_user_can('manage_options') ) return;
        $o   = self::get();
        $opt = self::OPT;
        ?>
        <div class="wrap ovp-admin">
            <div class="ovp-settings-header">
                <div>
                    <h1>Setări OVP-Sponsorizare</h1>
                    <p class="ovp-settings-subtitle">Configurează datele organizației, emailurile și opțiunile formularelor</p>
                </div>
            </div>

            <?php settings_errors('ovpspo_group'); ?>

            <form method="post" action="options.php">
                <?php settings_fields('ovpspo_group'); ?>

                <!-- Tabs nav -->
                <div class="ovp-settings-nav">
                    <button type="button" class="ovp-snav-btn active" data-tab="org">
                        <span class="ovp-snav-icon">🏛️</span>
                        <span class="ovp-snav-label">Organizație</span>
                    </button>
                    <button type="button" class="ovp-snav-btn" data-tab="email">
                        <span class="ovp-snav-icon dashicons dashicons-email-alt"></span>
                        <span class="ovp-snav-label">Email</span>
                    </button>
                    <button type="button" class="ovp-snav-btn" data-tab="form">
                        <span class="ovp-snav-icon">📋</span>
                        <span class="ovp-snav-label">Formular</span>
                    </button>
                </div>

                <!-- Tab: Organizatie -->
                <div class="ovp-stab active" id="stab-org">
                    <div class="ovp-settings-card">
                        <div class="ovp-settings-card-header">
                            <h2>Date Organizație</h2>
                            <p>Informațiile organizației tale care vor apărea pe documentele PDF generate</p>
                        </div>
                        <div class="ovp-settings-card-body">
                            <div class="ovp-sfield-grid">
                                <div class="ovp-sfield ovp-sfield-full">
                                    <label>Denumire organizație <span class="ovp-req">*</span></label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_nume]" value="<?php echo esc_attr($o['org_nume']??''); ?>" placeholder="ex. Asociația Balint din România">
                                    <span class="ovp-shint">Numele complet al organizației, conform actelor</span>
                                </div>
                                <div class="ovp-sfield">
                                    <label>CIF / CUI</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_cif]" value="<?php echo esc_attr($o['org_cif']??''); ?>" placeholder="ex. 5023579">
                                </div>
                                <div class="ovp-sfield">
                                    <label>IBAN</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_iban]" value="<?php echo esc_attr($o['org_iban']??''); ?>" placeholder="ex. RO26CECEHR0143RON0029733">
                                </div>
                                <div class="ovp-sfield">
                                    <label>Bancă</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_banca]" value="<?php echo esc_attr($o['org_banca']??''); ?>" placeholder="ex. CEC Bank">
                                </div>
                                <div class="ovp-sfield">
                                    <label>Reprezentant legal</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_reprezentant]" value="<?php echo esc_attr($o['org_reprezentant']??''); ?>" placeholder="ex. Ion Popescu">
                                    <span class="ovp-shint">Apare pe contractele de sponsorizare</span>
                                </div>
                                <div class="ovp-sfield">
                                    <label>Funcția reprezentantului</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_functie_rep]" value="<?php echo esc_attr($o['org_functie_rep']??''); ?>" placeholder="ex. Președinte">
                                </div>
                                <div class="ovp-sfield">
                                    <label>Nr. înregistrare Registrul Asociațiilor</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_reg_asociatii]" value="<?php echo esc_attr($o['org_reg_asociatii']??''); ?>" placeholder="ex. 12/A/2010">
                                    <span class="ovp-shint">Apare pe contractul de sponsorizare</span>
                                </div>
                                <div class="ovp-sfield">
                                    <label>Data înregistrării</label>
                                    <input type="date" name="<?php echo esc_attr( $opt ); ?>[org_data_inreg]" value="<?php echo esc_attr($o['org_data_inreg']??''); ?>">
                                </div>
                                <div class="ovp-sfield ovp-sfield-full">
                                    <label>Stradă și Număr sediu</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_strada]" value="<?php echo esc_attr($o['org_strada']??''); ?>" placeholder="ex. Str. Exemplu nr. 1">
                                    <span class="ovp-shint">Strada și numărul sediului social</span>
                                </div>
                                <div class="ovp-sfield ovp-sfield-full">
                                    <label>Informații suplimentare adresă <span style="font-weight:400;font-size:11px;color:#9aa5b4">(bloc, scară, etaj, ap...)</span></label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_info_adresa]" value="<?php echo esc_attr($o['org_info_adresa']??''); ?>" placeholder="ex. Bl. A1, Sc. 2, Et. 3, Ap. 14">
                                </div>
                                <div class="ovp-sfield">
                                    <label>Județ</label>
                                    <?php
                                    $judete_s = array('Alba','Arad','Argeș','Bacău','Bihor','Bistrița-Năsăud','Botoșani',
                                        'Brașov','Brăila','Buzău','Caraș-Severin','Călărași','Cluj','Constanța',
                                        'Covasna','Dâmbovița','Dolj','Galați','Giurgiu','Gorj','Harghita','Hunedoara',
                                        'Ialomița','Iași','Ilfov','Maramureș','Mehedinți','Mureș','Neamț','Olt',
                                        'Prahova','Satu Mare','Sălaj','Sibiu','Suceava','Teleorman','Timiș','Tulcea',
                                        'Vaslui','Vâlcea','Vrancea','București');
                                    $sel_judet = $o['org_judet'] ?? '';
                                    ?>
                                    <select name="<?php echo esc_attr( $opt ); ?>[org_judet]">
                                        <option value="">— Selectează —</option>
                                        <?php foreach ($judete_s as $j): ?>
                                        <option value="<?php echo esc_attr($j); ?>" <?php selected($sel_judet, $j); ?>><?php echo esc_html($j); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="ovp-sfield">
                                    <label>Sector <span style="font-weight:400;font-size:11px;color:#9aa5b4">(doar București)</span></label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_sector]" value="<?php echo esc_attr($o['org_sector']??''); ?>" placeholder="ex. 1" maxlength="10">
                                </div>
                                <div class="ovp-sfield">
                                    <label>Localitate</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_localitate]" value="<?php echo esc_attr($o['org_localitate']??''); ?>" placeholder="ex. Cluj-Napoca">
                                </div>
                                <div class="ovp-sfield">
                                    <label>Cod Poștal</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_cod_postal]" value="<?php echo esc_attr($o['org_cod_postal']??''); ?>" placeholder="ex. 400001" maxlength="10">
                                </div>
                                <div class="ovp-sfield ovp-sfield-full">
                                    <label>Adresă completă <span style="font-weight:400;font-size:11px;color:#9aa5b4">(generată automat)</span></label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_adresa]" id="ovp_adresa_preview" value="<?php echo esc_attr($o['org_adresa']??''); ?>" placeholder="Se completează automat" readonly style="background:#f5f7fa;color:#888">
                                    <span class="ovp-shint">Câmp generat automat din câmpurile de mai sus — folosit în PDF-ul branded</span>
                                </div>
                                <div class="ovp-sfield">
                                    <label>Website</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_website]" value="<?php echo esc_attr($o['org_website']??''); ?>" placeholder="ex. https://site.ro">
                                </div>
                                <div class="ovp-sfield">
                                    <label>Telefon</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_telefon]" value="<?php echo esc_attr($o['org_telefon']??''); ?>" placeholder="ex. 0700 000 000" maxlength="10">
                                    <span class="ovp-shint">Maxim 10 caractere (fără spații)</span>
                                </div>
                                <div class="ovp-sfield">
                                    <label>Fax <span style="font-weight:400;font-size:11px;color:#9aa5b4">(opțional)</span></label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_fax]" value="<?php echo esc_attr($o['org_fax']??''); ?>" placeholder="ex. 0700 000 001" maxlength="10">
                                </div>
                                <div class="ovp-sfield">
                                    <label>E-mail public organizație</label>
                                    <input type="email" name="<?php echo esc_attr( $opt ); ?>[org_email_public]" value="<?php echo esc_attr($o['org_email_public']??''); ?>" placeholder="ex. contact@organizatie.ro">
                                    <span class="ovp-shint">Precompletat automat în câmpul E-mail din formularul 177</span>
                                </div>
                                <div class="ovp-sfield">
                                    <label>Culoare brand principală</label>
                                    <div class="ovp-color-wrap">
                                        <input type="color" class="ovp-cpick" id="ovp_color_pick" name="<?php echo esc_attr( $opt ); ?>[org_culoare]" value="<?php echo esc_attr($o['org_culoare']??'#0F408A'); ?>">
                                        <input type="text" class="ovp-chex" value="<?php echo esc_attr($o['org_culoare']??'#0F408A'); ?>" placeholder="#0F408A" maxlength="7">
                                        <div class="ovp-color-preview" style="background:<?php echo esc_attr($o['org_culoare']??'#0F408A'); ?>"></div>
                                    </div>
                                    <span class="ovp-shint">Folosită în PDF-ul cu branding. Introdu HEX sau alege din picker.</span>
                                </div>
                            </div>

                            <div class="ovp-colors-section">
                                <h3 class="ovp-colors-title">Culori formulare</h3>
                                <p class="ovp-shint" style="margin-bottom:16px">Personalizează culorile afișate pe formularul online. Modificările se aplică instant pe ambele formulare (230 și 177).</p>

                                <div class="ovp-colors-preview-wrap">
                                    <div class="ovp-form-preview">
                                        <div class="ovp-prev-hero" id="prev_hero">
                                            <div class="ovp-prev-badge">Formular 230</div>
                                            <div class="ovp-prev-title">Susține <span id="prev_orgname"><?php echo esc_html($o['org_nume']??'Organizația Ta'); ?></span></div>
                                        </div>
                                        <div class="ovp-prev-body">
                                            <div class="ovp-prev-section" id="prev_section">
                                                <div class="ovp-prev-sh3" id="prev_h3">I. Date de identificare</div>
                                                <div class="ovp-prev-field"></div>
                                                <div class="ovp-prev-field"></div>
                                            </div>
                                            <div class="ovp-prev-btn" id="prev_btn">Trimite formularul →</div>
                                        </div>
                                    </div>
                                </div>

                                <div class="ovp-sfield-grid" style="margin-top:20px">
                                    <div class="ovp-sfield">
                                        <label>Culoare header formular</label>
                                        <div class="ovp-color-wrap">
                                            <input type="color" class="ovp-cpick" name="<?php echo esc_attr( $opt ); ?>[culoare_header]" value="<?php echo esc_attr($o['culoare_header']??'#0F408A'); ?>">
                                            <input type="text" class="ovp-chex" value="<?php echo esc_attr($o['culoare_header']??'#0F408A'); ?>" placeholder="#0F408A" maxlength="7">
                                            <div class="ovp-color-preview" style="background:<?php echo esc_attr($o['culoare_header']??'#0F408A'); ?>"></div>
                                        </div>
                                        <span class="ovp-shint">Culoarea de bază a gradientului din header</span>
                                    </div>
                                    <div class="ovp-sfield">
                                        <label>Culoare accent (titlu organizație)</label>
                                        <div class="ovp-color-wrap">
                                            <input type="color" class="ovp-cpick" name="<?php echo esc_attr( $opt ); ?>[culoare_accent]" value="<?php echo esc_attr($o['culoare_accent']??'#c8a84b'); ?>">
                                            <input type="text" class="ovp-chex" value="<?php echo esc_attr($o['culoare_accent']??'#c8a84b'); ?>" placeholder="#c8a84b" maxlength="7">
                                            <div class="ovp-color-preview" style="background:<?php echo esc_attr($o['culoare_accent']??'#c8a84b'); ?>"></div>
                                        </div>
                                        <span class="ovp-shint">Culoarea numelui organizației în header (implicit auriu)</span>
                                    </div>
                                    <div class="ovp-sfield">
                                        <label>Culoare secțiuni formular</label>
                                        <div class="ovp-color-wrap">
                                            <input type="color" class="ovp-cpick" name="<?php echo esc_attr( $opt ); ?>[culoare_sectiuni]" value="<?php echo esc_attr($o['culoare_sectiuni']??'#0F408A'); ?>">
                                            <input type="text" class="ovp-chex" value="<?php echo esc_attr($o['culoare_sectiuni']??'#0F408A'); ?>" placeholder="#0F408A" maxlength="7">
                                            <div class="ovp-color-preview" style="background:<?php echo esc_attr($o['culoare_sectiuni']??'#0F408A'); ?>"></div>
                                        </div>
                                        <span class="ovp-shint">Bordura stângă și textul titlurilor de secțiuni</span>
                                    </div>
                                    <div class="ovp-sfield">
                                        <label>Culoare buton Submit</label>
                                        <div class="ovp-color-wrap">
                                            <input type="color" class="ovp-cpick" name="<?php echo esc_attr( $opt ); ?>[culoare_buton]" value="<?php echo esc_attr($o['culoare_buton']??'#0F408A'); ?>">
                                            <input type="text" class="ovp-chex" value="<?php echo esc_attr($o['culoare_buton']??'#0F408A'); ?>" placeholder="#0F408A" maxlength="7">
                                            <div class="ovp-color-preview" style="background:<?php echo esc_attr($o['culoare_buton']??'#0F408A'); ?>"></div>
                                        </div>
                                        <span class="ovp-shint">Culoarea butonului de trimitere a formularului</span>
                                    </div>
                                    <div class="ovp-sfield">
                                        <label>Culoare text principal</label>
                                        <div class="ovp-color-wrap">
                                            <input type="color" class="ovp-cpick" name="<?php echo esc_attr( $opt ); ?>[culoare_text]" value="<?php echo esc_attr($o['culoare_text']??'#1c2333'); ?>">
                                            <input type="text" class="ovp-chex" value="<?php echo esc_attr($o['culoare_text']??'#1c2333'); ?>" placeholder="#1c2333" maxlength="7">
                                            <div class="ovp-color-preview" style="background:<?php echo esc_attr($o['culoare_text']??'#1c2333'); ?>"></div>
                                        </div>
                                        <span class="ovp-shint">Culoarea textului principal din formular</span>
                                    </div>
                                    <div class="ovp-sfield">
                                        <label>Reset culori implicite</label>
                                        <button type="button" id="ovp_reset_colors" class="button" style="margin-top:4px">↺ Resetează la culori implicite</button>
                                        <span class="ovp-shint">Revine la paleta albastru-auriu implicită</span>
                                    </div>
                                </div>
                            </div>

                            <div class="ovp-sfield-grid" style="display:none">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Tab: Email -->
                <div class="ovp-stab" id="stab-email">
                    <div class="ovp-settings-card">
                        <div class="ovp-settings-card-header">
                            <h2>Configurare Email</h2>
                            <p>Setări pentru trimiterea automată a formularelor pe email</p>
                        </div>
                        <div class="ovp-settings-card-body">
                            <div class="ovp-sfield-grid">
                                <div class="ovp-sfield">
                                    <label>Email administrator <span class="ovp-req">*</span></label>
                                    <input type="email" name="<?php echo esc_attr( $opt ); ?>[org_email_admin]" value="<?php echo esc_attr($o['org_email_admin']??''); ?>" placeholder="admin@organizatie.ro">
                                    <span class="ovp-shint">Pe această adresă primești notificările și PDF-urile</span>
                                </div>
                                <div class="ovp-sfield">
                                    <label>Email expeditor</label>
                                    <input type="email" name="<?php echo esc_attr( $opt ); ?>[org_email_from]" value="<?php echo esc_attr($o['org_email_from']??''); ?>" placeholder="noreply@organizatie.ro">
                                    <span class="ovp-shint">Adresa care apare ca expeditor în emailuri</span>
                                </div>
                                <div class="ovp-sfield ovp-sfield-full">
                                    <label>Nume expeditor</label>
                                    <input type="text" name="<?php echo esc_attr( $opt ); ?>[org_email_from_name]" value="<?php echo esc_attr($o['org_email_from_name']??''); ?>" placeholder="ex. Asociația Balint">
                                </div>
                                <div class="ovp-sfield ovp-sfield-full">
                                    <label class="ovp-toggle-label">
                                        <div class="ovp-toggle-wrap">
                                            <input type="checkbox" name="<?php echo esc_attr( $opt ); ?>[trimite_user]" value="1" <?php checked($o['trimite_user']??1, 1); ?> class="ovp-toggle-input" id="toggle_user">
                                            <span class="ovp-toggle"></span>
                                        </div>
                                        <div>
                                            <strong>Trimite email și contribuabilului</strong>
                                            <span class="ovp-shint">Contribuabilul primește o copie a formularului pe email</span>
                                        </div>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Tab: Formular -->
                <div class="ovp-stab" id="stab-form">
                    <div class="ovp-settings-card">
                        <div class="ovp-settings-card-header">
                            <h2>Setări Formular</h2>
                            <p>Configurări generale pentru formulare</p>
                        </div>
                        <div class="ovp-settings-card-body">
                            <div class="ovp-sfield-grid">
                                <div class="ovp-sfield">
                                    <label>Anul fiscal</label>
                                    <input type="number" name="<?php echo esc_attr( $opt ); ?>[an_fiscal]" value="<?php echo esc_attr($o['an_fiscal']??gmdate('Y')-1); ?>" min="2020" max="2030" style="max-width:120px">
                                    <span class="ovp-shint">Anul pentru care se completează formularele</span>
                                </div>
                                <div class="ovp-sfield ovp-sfield-full">
                                    <label class="ovp-toggle-label">
                                        <div class="ovp-toggle-wrap">
                                            <input type="checkbox" name="<?php echo esc_attr( $opt ); ?>[salveaza_pdf]" value="1" <?php checked($o['salveaza_pdf']??1, 1); ?> class="ovp-toggle-input" id="toggle_pdf">
                                            <span class="ovp-toggle"></span>
                                        </div>
                                        <div>
                                            <strong>Salvează copie PDF pe server</strong>
                                            <span class="ovp-shint">PDF-urile generate vor fi stocate și pe serverul site-ului</span>
                                        </div>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Shortcodes info -->
                    <div class="ovp-settings-card">
                        <div class="ovp-settings-card-header">
                            <h2>Shortcode-uri disponibile</h2>
                            <p>Adaugă aceste shortcode-uri pe paginile dorite</p>
                        </div>
                        <div class="ovp-settings-card-body">
                            <div class="ovp-sc-list">
                                <div class="ovp-sc-item">
                                    <code>[formular230]</code>
                                    <div>
                                        <strong>Formular 230</strong> — Persoane fizice
                                        <span class="ovp-shint">Redirecționarea a 3,5% din impozitul pe venit</span>
                                    </div>
                                </div>
                                <div class="ovp-sc-item">
                                    <code>[formular177]</code>
                                    <div>
                                        <strong>Formular 177</strong> — Persoane juridice
                                        <span class="ovp-shint">Redirecționarea impozitului pe profit / microîntreprinderi</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="ovp-settings-footer">
                    <button type="submit" class="ovp-save-btn">Salvează setările</button>
                </div>

            </form>
        </div>
        <?php
    }
    /* ══ PAGINA CONTRACTE SPONSORIZARE ══ */
    public static function page_contracte() {
        if (!current_user_can('manage_options')) return;
        global $wpdb;
        $table = $wpdb->prefix . 'contracte_sponsorizare';
        $msg = sanitize_text_field( wp_unslash( $_GET['msg'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification

        if ($wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $table ) ) !== $table) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            echo '<div class="wrap"><div class="notice notice-warning"><p>Tabelul contracte nu există. Dezactivați și reactivați pluginul.</p></div></div>';
            return;
        }

        $rows = $wpdb->get_results( "SELECT * FROM " . esc_sql( $table ) . " ORDER BY data_trimitere DESC" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
        $tip_labels = array('baneasca'=>'Bănească','bunuri'=>'Bunuri','servicii'=>'Servicii');
        ?>
        <div class="wrap ovp-admin">
            <h1>Contracte de Sponsorizare <span class="ovp-badge"><?php echo count($rows); ?> total</span></h1>
            <?php if ($msg==='deleted'): ?><div class="notice notice-success is-dismissible"><p>Contractul a fost șters.</p></div><?php endif; ?>
            <?php if ($msg==='missing'):  ?><div class="notice notice-warning is-dismissible"><p>PDF-ul nu a fost găsit pe server.</p></div><?php endif; ?>
            <div class="notice notice-info" style="padding:10px 16px">
                <p>Shortcode: <code>[ovpspo_contract_sponsorizare]</code> sau <code>[contract_sponsorizare]</code> — Formular contract de sponsorizare pentru sponsori.</p>
            </div>
            <?php if (empty($rows)): ?>
                <div class="ovp-empty"><p>Nu există contracte încă.</p><p>Adaugă <code>[ovpspo_contract_sponsorizare]</code> pe o pagină.</p></div>
            <?php else: ?>
            <div class="ovp-card">
                <table class="widefat striped">
                    <thead><tr>
                        <th>#</th><th>Data</th><th>Nr. Contract</th><th>Sponsor</th>
                        <th>CUI/CNP</th><th>Tip</th><th>Sumă</th><th>PDF</th><th>Acțiuni</th>
                    </tr></thead>
                    <tbody>
                    <?php foreach ($rows as $r):
                        $has_pdf = !empty($r->pdf_path) && file_exists($r->pdf_path);
                        $u = array('page'=>'ovpspo-contracte');
                        $dl  = add_query_arg(array_merge($u,array('ovpspo_action'=>'dl_contract', 'id'=>$r->id,'_wpnonce'=>wp_create_nonce('ovpspo_dlc_'.$r->id))),  admin_url('admin.php'));
                        $del = add_query_arg(array_merge($u,array('ovpspo_action'=>'del_contract','id'=>$r->id,'_wpnonce'=>wp_create_nonce('ovpspo_delc_'.$r->id))), admin_url('admin.php'));
                    ?>
                        <tr>
                            <td><?php echo intval($r->id); ?></td>
                            <td><?php echo esc_html( gmdate('d.m.Y H:i', strtotime($r->data_trimitere)) ); ?></td>
                            <td><strong><?php echo esc_html($r->nr_contract); ?></strong></td>
                            <td><?php echo esc_html($r->sponsor_nume); ?></td>
                            <td><code><?php echo esc_html($r->sponsor_cui); ?></code></td>
                            <td><?php echo esc_html($tip_labels[$r->tip_sponsorizare]??'—'); ?></td>
                            <td><?php echo $r->suma ? esc_html( number_format($r->suma,2,',','.') ) . ' lei' : '—'; ?></td>
                            <td>
                                <?php if ($has_pdf): ?>
                                    <a href="<?php echo esc_url($dl); ?>" class="button button-small button-primary"><span class="dashicons dashicons-download"></span> PDF</a>
                                <?php else: ?>
                                    <span style="color:#999;font-size:12px">lipsă</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="<?php echo esc_url($del); ?>" class="button button-small ovp-confirm-del" style="color:#a00" data-confirm="<?php esc_attr_e( 'Ștergi definitiv?', 'ovp-sponsorizare' ); ?>">Șterge</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
        <?php
    }
}
} // end class_exists
