<?php
/**
 * Plugin Name: AIzone Investor Landing
 * Description: Investor landing styles and deck request flow for AIzone MENA.
 */

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

function aizone_investor_target_page_ids() {
    $ids = [];
    foreach ( [ 'home', 'request-deck', 'book-session' ] as $slug ) {
        $page = get_page_by_path( $slug, OBJECT, 'page' );
        if ( $page ) {
            $ids[] = (int) $page->ID;
        }
    }

    return array_values( array_unique( array_filter( $ids ) ) );
}

function aizone_is_investor_context() {
    if ( is_admin() ) {
        return false;
    }

    if ( is_front_page() ) {
        return true;
    }

    return is_page( aizone_investor_target_page_ids() );
}

add_filter( 'body_class', function( $classes ) {
    if ( aizone_is_investor_context() ) {
        $classes[] = 'aizone-investor-active';
    }

    return $classes;
} );

add_action( 'wp_enqueue_scripts', function() {
    if ( ! aizone_is_investor_context() ) {
        return;
    }

    wp_enqueue_style(
        'aizone-investor',
        content_url( 'mu-plugins/aizone-investor.css' ),
        [],
        filemtime( WPMU_PLUGIN_DIR . '/aizone-investor.css' )
    );
}, 40 );

function aizone_investor_current_url() {
    $scheme = is_ssl() ? 'https://' : 'http://';
    $host   = $_SERVER['HTTP_HOST'] ?? parse_url( home_url(), PHP_URL_HOST );
    $uri    = $_SERVER['REQUEST_URI'] ?? '/';

    return $scheme . $host . $uri;
}

function aizone_investor_deck_success_url() {
    $target = wp_get_referer();

    if ( ! $target ) {
        $request_page = get_page_by_path( 'request-deck', OBJECT, 'page' );
        $target       = $request_page ? get_permalink( $request_page ) : home_url( '/request-deck/' );
    }

    return add_query_arg( 'deck', 'requested', $target );
}

function aizone_handle_deck_request_submission() {
    if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ?? '' ) ) {
        return;
    }

    if ( empty( $_POST['aizone_deck_form_submitted'] ) ) {
        return;
    }

    if ( empty( $_POST['aizone_deck_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aizone_deck_nonce'] ) ), 'aizone_deck_request' ) ) {
        wp_die( esc_html__( 'Security check failed. Please refresh the page and try again.', 'twentytwentyfive' ) );
    }

    $name       = sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) );
    $email      = sanitize_email( wp_unslash( $_POST['email'] ?? '' ) );
    $firm       = sanitize_text_field( wp_unslash( $_POST['firm'] ?? '' ) );
    $role       = sanitize_text_field( wp_unslash( $_POST['role'] ?? '' ) );
    $check_size = sanitize_text_field( wp_unslash( $_POST['check_size'] ?? '' ) );
    $focus      = sanitize_text_field( wp_unslash( $_POST['focus'] ?? '' ) );
    $message    = sanitize_textarea_field( wp_unslash( $_POST['message'] ?? '' ) );

    if ( '' === $name || '' === $firm || ! is_email( $email ) ) {
        wp_safe_redirect( add_query_arg( 'deck', 'invalid', aizone_investor_current_url() ) );
        exit;
    }

    $post_id = wp_insert_post(
        [
            'post_type'   => 'lead_capture',
            'post_status' => 'private',
            'post_title'  => trim( $firm . ' — ' . $name, ' —' ),
        ],
        true
    );

    if ( is_wp_error( $post_id ) ) {
        wp_die( esc_html__( 'We could not save your request. Please try again.', 'twentytwentyfive' ) );
    }

    update_post_meta( $post_id, '_lead_name', $name );
    update_post_meta( $post_id, '_lead_email', $email );
    update_post_meta( $post_id, '_lead_phone', '' );
    update_post_meta( $post_id, '_lead_company', $firm );
    update_post_meta( $post_id, '_lead_role', $role );
    update_post_meta( $post_id, '_lead_check_size', $check_size );
    update_post_meta( $post_id, '_lead_focus', $focus );
    update_post_meta( $post_id, '_lead_message', $message );
    update_post_meta( $post_id, '_lead_source', 'Investor deck request' );

    wp_safe_redirect( aizone_investor_deck_success_url() );
    exit;
}
add_action( 'init', 'aizone_handle_deck_request_submission', 60 );

function aizone_investor_deck_form_shortcode() {
    $status = sanitize_key( $_GET['deck'] ?? '' );
    ob_start();
    ?>
    <div class="aizone-form-shell">
        <?php if ( 'requested' === $status ) : ?>
            <div class="aizone-alert success">Thanks — your request is in. We can now review fit and share the investor deck in the next step.</div>
        <?php elseif ( 'invalid' === $status ) : ?>
            <div class="aizone-alert error">Please complete your name, firm, and a valid work email before submitting.</div>
        <?php endif; ?>

        <form class="aizone-form" method="post" action="">
            <input type="hidden" name="aizone_deck_form_submitted" value="1" />
            <?php wp_nonce_field( 'aizone_deck_request', 'aizone_deck_nonce' ); ?>

            <div class="aizone-form-grid two-up">
                <label>
                    <span>Full name</span>
                    <input type="text" name="name" autocomplete="name" required />
                </label>
                <label>
                    <span>Work email</span>
                    <input type="email" name="email" autocomplete="email" required />
                </label>
            </div>

            <div class="aizone-form-grid two-up">
                <label>
                    <span>Firm</span>
                    <input type="text" name="firm" autocomplete="organization" required />
                </label>
                <label>
                    <span>Title / role</span>
                    <input type="text" name="role" autocomplete="organization-title" />
                </label>
            </div>

            <div class="aizone-form-grid two-up">
                <label>
                    <span>Typical check size</span>
                    <input type="text" name="check_size" placeholder="e.g. $250k–$2M" />
                </label>
                <label>
                    <span>Investment focus</span>
                    <input type="text" name="focus" placeholder="Enterprise AI, MENA SaaS, frontier tech" />
                </label>
            </div>

            <label>
                <span>What would you like to diligence first?</span>
                <textarea name="message" rows="5" placeholder="Team, go-to-market, services-to-software strategy, security posture, pipeline, regional expansion, or fund use."></textarea>
            </label>

            <div class="aizone-form-actions">
                <button type="submit">Request the investor deck</button>
                <p>Customer references, pipeline detail, and operating materials can be shared in qualified follow-up discussions.</p>
            </div>
        </form>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode( 'aizone_investor_deck_form', 'aizone_investor_deck_form_shortcode' );
