<?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_Ajax') ) {
class OVPSPO_Ajax {

    public static function init() {
        add_action( 'wp_ajax_ovpspo_submit230',        array( __CLASS__, 'handle' ) ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
        add_action( 'wp_ajax_nopriv_ovpspo_submit230', array( __CLASS__, 'handle' ) ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
    }

    public static function handle() {
        if ( ! check_ajax_referer( 'ovpspo_submit230', 'ovpspo_nonce230', false ) ) {
            wp_send_json_error( array( 'message' => 'Cerere invalida. Reincarca pagina.' ) );
        }

        $data = array(
            'nume'       => sanitize_text_field( wp_unslash( $_POST['nume']       ?? '' ) ),
            'prenume'    => sanitize_text_field( wp_unslash( $_POST['prenume']    ?? '' ) ),
            'initiala'   => sanitize_text_field( wp_unslash( $_POST['initiala']   ?? '' ) ),
            'cnp'        => sanitize_text_field( wp_unslash( $_POST['cnp']        ?? '' ) ),
            'email'      => sanitize_email(      wp_unslash( $_POST['email']      ?? '' ) ),
            'telefon'    => sanitize_text_field( wp_unslash( $_POST['telefon']    ?? '' ) ),
            'judet'      => sanitize_text_field( wp_unslash( $_POST['judet']      ?? '' ) ),
            'localitate' => sanitize_text_field( wp_unslash( $_POST['localitate'] ?? '' ) ),
            'cod_postal' => sanitize_text_field( wp_unslash( $_POST['cod_postal'] ?? '' ) ),
            'strada'     => sanitize_text_field( wp_unslash( $_POST['strada']     ?? '' ) ),
            'nr'         => sanitize_text_field( wp_unslash( $_POST['nr']         ?? '' ) ),
            'bloc'       => sanitize_text_field( wp_unslash( $_POST['bloc']       ?? '' ) ),
            'scara'      => sanitize_text_field( wp_unslash( $_POST['scara']      ?? '' ) ),
            'etaj'       => sanitize_text_field( wp_unslash( $_POST['etaj']       ?? '' ) ),
            'apart'      => sanitize_text_field( wp_unslash( $_POST['apart']      ?? '' ) ),
            'perioada'   => in_array( sanitize_text_field( wp_unslash( $_POST['perioada'] ?? '1' ) ), array('1','2') ) ? intval( $_POST['perioada'] ) : 1,
            'gdpr'       => ! empty( $_POST['gdpr'] ) ? 1 : 0,
            'signature'  => sanitize_text_field( wp_unslash( $_POST['signature'] ?? '' ) ),
            'an_fiscal'  => OVPSPO_Settings::get( 'an_fiscal', gmdate('Y') - 1 ),
        );

        $errors = self::validate( $data );
        if ( ! empty($errors) ) {
            wp_send_json_error( array( 'message' => implode('<br>', $errors) ) );
        }

        global $wpdb;
        $table = $wpdb->prefix . 'f230_submissions';

        // Verifica si creeaza tabela daca nu exista
        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $table ) ) !== $table ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
            $charset = $wpdb->get_charset_collate();
            dbDelta( "CREATE TABLE IF NOT EXISTS $table (
                id               BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                data_trimitere   DATETIME NOT NULL,
                nume             VARCHAR(100),
                prenume          VARCHAR(100),
                initiala         VARCHAR(5),
                cnp              VARCHAR(13),
                email            VARCHAR(200),
                telefon          VARCHAR(20),
                judet            VARCHAR(50),
                localitate       VARCHAR(100),
                cod_postal       VARCHAR(10),
                strada           VARCHAR(200),
                nr               VARCHAR(20),
                bloc             VARCHAR(20),
                scara            VARCHAR(10),
                etaj             VARCHAR(10),
                apart            VARCHAR(10),
                perioada         TINYINT(1) DEFAULT 1,
                an_fiscal        YEAR,
                gdpr             TINYINT(1) DEFAULT 0,
                pdf_path         VARCHAR(255),
                pdf_anaf_path    VARCHAR(255),
                ip               VARCHAR(45),
                PRIMARY KEY (id)
            ) $charset;" );
        }

        $wpdb->insert( $table, array( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            'data_trimitere' => current_time('mysql'),
            'nume'           => $data['nume'],       'prenume'    => $data['prenume'],
            'initiala'       => $data['initiala'],   'cnp'        => $data['cnp'],
            'email'          => $data['email'],      'telefon'    => $data['telefon'],
            'judet'          => $data['judet'],      'localitate' => $data['localitate'],
            'cod_postal'     => $data['cod_postal'], 'strada'     => $data['strada'],
            'nr'             => $data['nr'],         'bloc'       => $data['bloc'],
            'scara'          => $data['scara'],      'etaj'       => $data['etaj'],
            'apart'          => $data['apart'],      'perioada'   => $data['perioada'],
            'an_fiscal'      => $data['an_fiscal'],  'gdpr'       => $data['gdpr'],
            'ip'             => sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ?? '' ) ),
        ) );
        $insert_id = $wpdb->insert_id;

        // Log eroare daca insert a esuat
        if ( ! $insert_id ) {

        }

        // ── PDF ANAF oficial (singurul trimis pe email) ──
        $pdf_anaf = '';
        try {
            $pdf_anaf = OVPSPO_PDF_ANAF::generate( $data, $insert_id );
            if ( $pdf_anaf ) {
                $wpdb->update( $table, array('pdf_anaf_path' => $pdf_anaf), array('id' => $insert_id) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            }
        } catch (Exception $e) {
        }

        // ── PDF branded (salvat in DB pentru download din admin, dar nu trimis pe email) ──
        $pdf_branded = '';
        try {
            $pdf_branded = OVPSPO_PDF::generate( $data, $insert_id );
            if ( $pdf_branded ) {
                $wpdb->update( $table, array('pdf_path' => $pdf_branded), array('id' => $insert_id) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            }
        } catch (Exception $e) {
        }

        // ── Email doar cu PDF-ul oficial ANAF ──
        $attachments = array();
        if ( $pdf_anaf && file_exists($pdf_anaf) ) $attachments[] = $pdf_anaf;

        OVPSPO_Email::send_admin( $data, $attachments );
        if ( $data['email'] && OVPSPO_Settings::get('trimite_user', 1) ) {
            OVPSPO_Email::send_user( $data, $attachments );
        }

        wp_send_json_success( array(
            'message' => 'Formularul a fost trimis cu succes! Echipa noastra va depune documentul la ANAF. Va multumim!'
        ) );
    }

    private static function validate($data) {
        $errors = array();
        if ( strlen($data['nume']) < 2 )        $errors[] = 'Campul Nume este obligatoriu.';
        if ( strlen($data['prenume']) < 2 )      $errors[] = 'Campul Prenume este obligatoriu.';
        if ( ! preg_match('/^\d{13}$/', $data['cnp']) ) $errors[] = 'CNP invalid – 13 cifre necesare.';
        if ( empty($data['judet']) )             $errors[] = 'Te rugam sa selectezi judetul.';
        if ( strlen($data['localitate']) < 2 )   $errors[] = 'Campul Localitate este obligatoriu.';
        if ( strlen($data['strada']) < 2 )       $errors[] = 'Campul Strada este obligatoriu.';
        if ( strlen($data['nr']) < 1 )           $errors[] = 'Campul Numar este obligatoriu.';
        if ( ! $data['gdpr'] )                   $errors[] = 'Este necesar acordul GDPR.';
        if ( empty($data['signature']) )         $errors[] = 'Semnatura este obligatorie.';
        if ( $data['email'] && ! is_email($data['email']) ) $errors[] = 'Adresa email invalida.';
        return $errors;
    }
}
} // end class_exists
