<?php

/**
 * REST API endpoints for the Noon Audit plugin.
 *
 * Public:
 *   GET  /noon_audit/v1/audits/<slug>  — fetch audit config for the React app
 *   POST /noon_audit/v1/leads          — submit a lead
 *
 * Admin-only:
 *   GET  /noon_audit/v1/leads          — paginated lead list
 *   GET  /noon_audit/v1/audits         — all audits
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class Noon_Audit_REST_API {
    const NAMESPACE = 'noon_audit/v1';

    public static function register() {
        add_action( 'rest_api_init', [__CLASS__, 'register_routes'] );
    }

    public static function register_routes() {
        // ── Public: Fetch audit by slug ──────────────────────────────────────
        register_rest_route( self::NAMESPACE, '/audits/(?P<slug>[a-z0-9\\-]+)', [
            'methods'             => 'GET',
            'callback'            => [__CLASS__, 'get_audit'],
            'permission_callback' => '__return_true',
            'args'                => [
                'slug' => [
                    'required'          => true,
                    'sanitize_callback' => 'sanitize_title',
                ],
            ],
        ] );
        // ── Public: Submit a lead ────────────────────────────────────────────
        register_rest_route( self::NAMESPACE, '/leads', [
            'methods'             => 'POST',
            'callback'            => [__CLASS__, 'submit_lead'],
            'permission_callback' => '__return_true',
            'args'                => [
                'audit_id'        => [
                    'required' => true,
                    'type'     => 'integer',
                ],
                'email'           => [
                    'required' => true,
                    'type'     => 'string',
                ],
                'name'            => [
                    'required' => false,
                    'type'     => 'string',
                ],
                'company'         => [
                    'required' => false,
                    'type'     => 'string',
                ],
                'score'           => [
                    'required' => true,
                    'type'     => 'integer',
                ],
                'risk_band'       => [
                    'required' => true,
                    'type'     => 'string',
                ],
                'category_scores' => [
                    'required' => false,
                    'type'     => 'array',
                ],
                'answers'         => [
                    'required' => false,
                    'type'     => 'array',
                ],
                'website_url'     => [
                    'required' => false,
                    'type'     => 'string',
                ],
                'turnstile_token' => [
                    'required' => false,
                    'type'     => 'string',
                ],
                'consented_at'    => [
                    'required' => false,
                    'type'     => 'string',
                ],
                'marketing_optin' => [
                    'required' => false,
                    'type'     => 'boolean',
                ],
            ],
        ] );
        // ── Admin: List all leads ────────────────────────────────────────────
        register_rest_route( self::NAMESPACE, '/leads', [
            'methods'             => 'GET',
            'callback'            => [__CLASS__, 'list_leads'],
            'permission_callback' => [__CLASS__, 'is_admin'],
            'args'                => [
                'page'     => [
                    'default' => 1,
                    'type'    => 'integer',
                ],
                'per_page' => [
                    'default' => 20,
                    'type'    => 'integer',
                ],
                'audit_id' => [
                    'type' => 'integer',
                ],
            ],
        ] );
        // ── Admin: List all audits ───────────────────────────────────────────
        register_rest_route( self::NAMESPACE, '/audits', [
            'methods'             => 'GET',
            'callback'            => [__CLASS__, 'list_audits'],
            'permission_callback' => [__CLASS__, 'is_admin'],
        ] );
    }

    // ─── Handlers ────────────────────────────────────────────────────────────
    public static function get_audit( \WP_REST_Request $request ) {
        $slug = $request->get_param( 'slug' );
        $audit = Noon_Audit_Database::get_audit_by_slug( $slug );
        if ( !$audit ) {
            return new \WP_Error('not_found', 'Audit not found.', [
                'status' => 404,
            ]);
        }
        return rest_ensure_response( self::format_audit( $audit ) );
    }

    public static function submit_lead( \WP_REST_Request $request ) {
        $params = $request->get_json_params();
        // Validate email.
        if ( !is_email( $params['email'] ?? '' ) ) {
            return new \WP_Error('invalid_email', 'A valid email is required.', [
                'status' => 400,
            ]);
        }
        // Anti-spam Honeypot: If the hidden 'website_url' field was filled, silently reject the bot.
        if ( !empty( $params['website_url'] ) ) {
            return rest_ensure_response( [
                'success' => true,
                'lead_id' => 0,
            ] );
        }
        // Validate audit exists.
        $audit = Noon_Audit_Database::get_audit_by_id( (int) $params['audit_id'] );
        if ( !$audit ) {
            return new \WP_Error('invalid_audit', 'Audit not found.', [
                'status' => 400,
            ]);
        }
        $lead_id = Noon_Audit_Database::insert_lead( $params );
        if ( !$lead_id ) {
            return new \WP_Error('db_error', 'Failed to save lead.', [
                'status' => 500,
            ]);
        }
        return rest_ensure_response( [
            'success' => true,
            'lead_id' => $lead_id,
        ] );
    }

    public static function list_leads( \WP_REST_Request $request ) {
        $args = [
            'page'     => $request->get_param( 'page' ),
            'per_page' => $request->get_param( 'per_page' ),
            'audit_id' => $request->get_param( 'audit_id' ),
        ];
        return rest_ensure_response( Noon_Audit_Database::get_leads( $args ) );
    }

    public static function list_audits() {
        $audits = Noon_Audit_Database::get_all_audits();
        return rest_ensure_response( array_map( [__CLASS__, 'format_audit'], $audits ) );
    }

    // ─── Helpers ─────────────────────────────────────────────────────────────
    public static function is_admin() {
        return current_user_can( 'manage_options' );
    }

    private static function format_audit( $audit ) {
        return [
            'id'             => (int) $audit->id,
            'title'          => $audit->title,
            'slug'           => $audit->slug,
            'hook_text'      => $audit->hook_text,
            'categories'     => json_decode( $audit->categories, true ),
            'questions'      => json_decode( $audit->questions, true ),
            'band_headlines' => json_decode( $audit->band_headlines, true ),
            'settings'       => json_decode( $audit->settings, true ),
            'status'         => $audit->status,
        ];
    }

}
