<?php
/**
 * SR_Talent_Controller — جذب کارشناس از فضای مجازی
 */
if ( ! defined( 'ABSPATH' ) ) exit;

require_once ACC_PATH . 'includes/helpers/svc-talent.php';

class SR_Talent_Controller {

    public static function register_routes(): void {
        $ns  = 'acc/v1';
        $pub = '__return_true';
        $jwt = 'acc_jwt_check_permission';

        register_rest_route( $ns, '/service/talent/meta', [
            'methods'             => 'GET',
            'callback'            => [ __CLASS__, 'meta' ],
            'permission_callback' => $pub,
        ] );

        register_rest_route( $ns, '/service/talent/apply', [
            'methods'             => 'POST',
            'callback'            => [ __CLASS__, 'start_apply' ],
            'permission_callback' => $pub,
        ] );

        register_rest_route( $ns, '/service/talent/apply/(?P<token>[a-f0-9]{48})', [
            'methods'             => 'GET',
            'callback'            => [ __CLASS__, 'get_apply' ],
            'permission_callback' => $pub,
        ] );

        register_rest_route( $ns, '/service/talent/apply/(?P<token>[a-f0-9]{48})/profile', [
            'methods'             => 'PUT',
            'callback'            => [ __CLASS__, 'update_profile' ],
            'permission_callback' => $pub,
        ] );

        register_rest_route( $ns, '/service/talent/apply/(?P<token>[a-f0-9]{48})/identity', [
            'methods'             => 'PUT',
            'callback'            => [ __CLASS__, 'save_identity' ],
            'permission_callback' => $pub,
        ] );

        register_rest_route( $ns, '/service/talent/apply/(?P<token>[a-f0-9]{48})/assessment/start', [
            'methods'             => 'POST',
            'callback'            => [ __CLASS__, 'start_assessment' ],
            'permission_callback' => $pub,
        ] );

        register_rest_route( $ns, '/service/talent/apply/(?P<token>[a-f0-9]{48})/assessment', [
            'methods'             => 'GET',
            'callback'            => [ __CLASS__, 'get_assessment' ],
            'permission_callback' => $pub,
        ] );

        register_rest_route( $ns, '/service/talent/apply/(?P<token>[a-f0-9]{48})/assessment/submit', [
            'methods'             => 'POST',
            'callback'            => [ __CLASS__, 'submit_assessment' ],
            'permission_callback' => $pub,
        ] );

        register_rest_route( $ns, '/service/talent/apply/(?P<token>[a-f0-9]{48})/result', [
            'methods'             => 'GET',
            'callback'            => [ __CLASS__, 'get_result' ],
            'permission_callback' => $pub,
        ] );

        register_rest_route( $ns, '/service/talent/applications', [
            'methods'             => 'GET',
            'callback'            => [ __CLASS__, 'list_applications' ],
            'permission_callback' => [ __CLASS__, 'reviewer_perm' ],
        ] );

        register_rest_route( $ns, '/service/talent/applications/(?P<id>\d+)', [
            'methods'             => 'GET',
            'callback'            => [ __CLASS__, 'get_application' ],
            'permission_callback' => [ __CLASS__, 'reviewer_perm' ],
        ] );

        register_rest_route( $ns, '/service/talent/applications/(?P<id>\d+)/review', [
            'methods'             => 'POST',
            'callback'            => [ __CLASS__, 'review_application' ],
            'permission_callback' => [ __CLASS__, 'reviewer_perm' ],
        ] );

        register_rest_route( $ns, '/service/talent/stats', [
            'methods'             => 'GET',
            'callback'            => [ __CLASS__, 'stats' ],
            'permission_callback' => [ __CLASS__, 'reviewer_perm' ],
        ] );
    }

    public static function reviewer_perm(): bool {
        $uid = (int) get_current_user_id();
        if ( $uid <= 0 ) return false;
        if ( function_exists( 'acl_user_is_super_admin' ) && acl_user_is_super_admin( $uid ) ) {
            return true;
        }
        if ( function_exists( 'acl_user_can' ) ) {
            if ( acl_user_can( $uid, 'service.manage' ) || acl_user_can( $uid, 'service.senior.manage' ) || acl_user_can( $uid, 'service.dispatch' ) ) {
                return true;
            }
        }
        require_once ACC_PATH . 'includes/helpers/svc-teams.php';
        return Svc_Teams::is_senior( $uid ) || Svc_Teams::is_dispatcher( $uid );
    }

    public static function meta( WP_REST_Request $req ): WP_REST_Response {
        if ( ! Svc_Talent::tables_exist() ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'ماژول جذب نصب نشده است.' ], 503 );
        }
        return new WP_REST_Response( [ 'success' => true, 'data' => Svc_Talent::meta() ], 200 );
    }

    public static function start_apply( WP_REST_Request $req ): WP_REST_Response {
        if ( ! Svc_Talent::tables_exist() ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'ماژول جذب نصب نشده است.' ], 503 );
        }
        $body = $req->get_json_params() ?: [];
        if ( empty( $body['full_name'] ) || empty( $body['phone'] ) ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'نام و موبایل الزامی است.' ], 400 );
        }
        $app = Svc_Talent::start_application( $body );
        return new WP_REST_Response( [ 'success' => true, 'data' => $app ], 201 );
    }

    public static function get_apply( WP_REST_Request $req ): WP_REST_Response {
        $token = (string) $req->get_param( 'token' );
        $app   = Svc_Talent::get_by_token( $token );
        if ( ! $app ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'درخواست یافت نشد.' ], 404 );
        }
        return new WP_REST_Response( [ 'success' => true, 'data' => Svc_Talent::format_application( $app ) ], 200 );
    }

    public static function update_profile( WP_REST_Request $req ): WP_REST_Response {
        $token = (string) $req->get_param( 'token' );
        $body  = $req->get_json_params() ?: [];
        $app   = Svc_Talent::update_profile( $token, $body );
        if ( ! $app ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'درخواست یافت نشد.' ], 404 );
        }
        return new WP_REST_Response( [ 'success' => true, 'data' => $app ], 200 );
    }

    public static function save_identity( WP_REST_Request $req ): WP_REST_Response {
        $token = (string) $req->get_param( 'token' );
        $body  = $req->get_json_params() ?: [];
        $app   = Svc_Talent::save_identities(
            $token,
            $body['identities'] ?? [],
            $body['certificates'] ?? []
        );
        if ( ! $app ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'درخواست یافت نشد.' ], 404 );
        }
        if ( ! empty( $body['video_intro_url'] ) ) {
            global $wpdb;
            $wpdb->update( Svc_Talent::applications_table(), [
                'video_intro_url' => esc_url_raw( $body['video_intro_url'] ),
            ], [ 'access_token' => $token ] );
            $app = Svc_Talent::format_application( Svc_Talent::get_by_token( $token ) );
        }
        return new WP_REST_Response( [ 'success' => true, 'data' => $app ], 200 );
    }

    public static function start_assessment( WP_REST_Request $req ): WP_REST_Response {
        $token   = (string) $req->get_param( 'token' );
        $attempt = Svc_Talent::start_assessment( $token );
        if ( ! $attempt ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'شروع ارزیابی ممکن نیست.' ], 400 );
        }
        return new WP_REST_Response( [ 'success' => true, 'data' => $attempt ], 200 );
    }

    public static function get_assessment( WP_REST_Request $req ): WP_REST_Response {
        $token = (string) $req->get_param( 'token' );
        $app   = Svc_Talent::get_by_token( $token );
        if ( ! $app ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'درخواست یافت نشد.' ], 404 );
        }
        $attempt = Svc_Talent::get_active_attempt( (int) $app['id'] );
        if ( ! $attempt ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'ارزیابی فعالی وجود ندارد.' ], 404 );
        }
        return new WP_REST_Response( [
            'success' => true,
            'data'    => Svc_Talent::format_attempt_for_client( $attempt ),
        ], 200 );
    }

    public static function submit_assessment( WP_REST_Request $req ): WP_REST_Response {
        $token   = (string) $req->get_param( 'token' );
        $body    = $req->get_json_params() ?: [];
        $answers = $body['answers'] ?? [];
        if ( ! is_array( $answers ) || ! $answers ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'پاسخ‌ها الزامی است.' ], 400 );
        }
        $result = Svc_Talent::submit_assessment( $token, $answers );
        if ( ! $result ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'ثبت پاسخ ممکن نیست.' ], 400 );
        }
        return new WP_REST_Response( [ 'success' => true, 'data' => $result ], 200 );
    }

    public static function get_result( WP_REST_Request $req ): WP_REST_Response {
        $token  = (string) $req->get_param( 'token' );
        $result = Svc_Talent::get_result( $token );
        if ( ! $result ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'نتیجه یافت نشد.' ], 404 );
        }
        return new WP_REST_Response( [ 'success' => true, 'data' => $result ], 200 );
    }

    public static function list_applications( WP_REST_Request $req ): WP_REST_Response {
        $filters = [
            'status' => $req->get_param( 'status' ) ?: '',
            'q'      => $req->get_param( 'q' ) ?: '',
            'limit'  => (int) ( $req->get_param( 'limit' ) ?? 50 ),
            'offset' => (int) ( $req->get_param( 'offset' ) ?? 0 ),
        ];
        return new WP_REST_Response( [
            'success' => true,
            'data'    => Svc_Talent::list_applications( $filters ),
            'stats'   => Svc_Talent::stats(),
        ], 200 );
    }

    public static function get_application( WP_REST_Request $req ): WP_REST_Response {
        $id  = (int) $req->get_param( 'id' );
        $app = Svc_Talent::get_by_id( $id );
        if ( ! $app ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'یافت نشد.' ], 404 );
        }
        $formatted = Svc_Talent::format_application( $app );
        unset( $formatted['access_token'] );
        return new WP_REST_Response( [ 'success' => true, 'data' => $formatted ], 200 );
    }

    public static function review_application( WP_REST_Request $req ): WP_REST_Response {
        $id     = (int) $req->get_param( 'id' );
        $body   = $req->get_json_params() ?: [];
        $action = sanitize_text_field( $body['action'] ?? '' );
        if ( ! in_array( $action, [ 'approve', 'reject' ], true ) ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'action نامعتبر' ], 400 );
        }
        $app = Svc_Talent::review_application( $id, $action, (int) get_current_user_id(), [
            'notes'          => $body['notes'] ?? '',
            'senior_user_id' => (int) ( $body['senior_user_id'] ?? 0 ),
            'temp_password'  => $body['temp_password'] ?? '',
        ] );
        if ( ! $app ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'یافت نشد.' ], 404 );
        }
        unset( $app['access_token'] );
        return new WP_REST_Response( [ 'success' => true, 'data' => $app ], 200 );
    }

    public static function stats( WP_REST_Request $req ): WP_REST_Response {
        return new WP_REST_Response( [ 'success' => true, 'data' => Svc_Talent::stats() ], 200 );
    }
}
