<?php
/**
 * ED_Accounting_Controller — حسابداری بهای تمام‌شده EduBrain
 */
if ( ! defined( 'ABSPATH' ) ) exit;

require_once ACC_PATH . 'includes/helpers/education-cost-accounting.php';
require_once ACC_PATH . 'includes/helpers/acc-portal-accounting.php';

class ED_Accounting_Controller {

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

        register_rest_route( $ns, '/education/accounting/config', [
            [ 'methods' => 'GET', 'callback' => [ __CLASS__, 'get_config' ],  'permission_callback' => $jwt ],
            [ 'methods' => 'PUT', 'callback' => [ __CLASS__, 'save_config' ], 'permission_callback' => $jwt ],
        ] );
        register_rest_route( $ns, '/education/accounting/portal', [
            [ 'methods' => 'GET', 'callback' => [ __CLASS__, 'get_portal' ],  'permission_callback' => $jwt ],
            [ 'methods' => 'PUT', 'callback' => [ __CLASS__, 'save_portal' ], 'permission_callback' => $jwt ],
        ] );
        register_rest_route( $ns, '/education/accounting/pending', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'pending_queue' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/education/accounting/cost-report', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'cost_report' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/education/accounting/post/(?P<session_id>\d+)', [
            'methods' => 'POST', 'callback' => [ __CLASS__, 'post_session' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/education/accounting/splits/(?P<session_id>\d+)', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'get_splits' ], 'permission_callback' => $jwt,
        ] );

        /* Activity Cost Graph — جلسه ↔ فعالیت ↔ نقش */
        register_rest_route( $ns, '/education/acct/activities', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'abc_activities' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/education/acct/sessions', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'abc_sessions' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/education/acct/cost-graph', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'abc_cost_graph' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/education/acct/activity-cost/(?P<session_id>\d+)', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'abc_activity_cost' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/education/acct/allocate/(?P<session_id>\d+)', [
            'methods' => 'POST', 'callback' => [ __CLASS__, 'abc_allocate' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/education/acct/crew/(?P<session_id>\d+)', [
            [ 'methods' => 'GET', 'callback' => [ __CLASS__, 'abc_get_crew' ], 'permission_callback' => $jwt ],
            [ 'methods' => 'PUT', 'callback' => [ __CLASS__, 'abc_save_crew' ], 'permission_callback' => $jwt ],
        ] );
    }

    private static function _abc(): void {
        require_once ACC_PATH . 'includes/helpers/education-activity-cost.php';
        Edu_Activity_Cost::ensure_tables();
    }

    public static function abc_activities(): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        self::_abc();
        return new WP_REST_Response( [
            'success' => true,
            'data'    => Edu_Activity_Cost::list_activities( true ),
            'roles'   => Edu_Activity_Cost::role_labels(),
        ] );
    }

    public static function abc_sessions(): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        self::_abc();
        return new WP_REST_Response( [
            'success' => true,
            'data'    => Edu_Activity_Cost::list_sessions( 50 ),
        ] );
    }

    public static function abc_cost_graph( WP_REST_Request $req ): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        self::_abc();
        $data = Edu_Activity_Cost::cost_graph( [
            'session_id' => (int) $req->get_param( 'session_id' ),
        ] );
        return new WP_REST_Response( [ 'success' => true, 'data' => $data ] );
    }

    public static function abc_activity_cost( WP_REST_Request $req ): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        self::_abc();
        $id = (int) $req['session_id'];
        $row = Edu_Activity_Cost::get_session( $id );
        if ( ! $row ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'جلسه یافت نشد' ], 404 );
        }
        return new WP_REST_Response( [
            'success' => true,
            'data'    => Edu_Activity_Cost::allocate( $row ),
        ] );
    }

    public static function abc_allocate( WP_REST_Request $req ): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        self::_abc();
        $id = (int) $req['session_id'];
        $row = Edu_Activity_Cost::get_session( $id );
        if ( ! $row ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'جلسه یافت نشد' ], 404 );
        }
        $alloc = Edu_Activity_Cost::allocate( $row );
        Edu_Activity_Cost::persist( $id, $alloc );
        return new WP_REST_Response( [
            'success' => true,
            'message' => 'تخصیص فعالیت ذخیره شد',
            'data'    => $alloc,
        ] );
    }

    public static function abc_get_crew( WP_REST_Request $req ): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        self::_abc();
        $id = (int) $req['session_id'];
        if ( ! Edu_Activity_Cost::get_session( $id ) ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'جلسه یافت نشد' ], 404 );
        }
        return new WP_REST_Response( [
            'success' => true,
            'data'    => Edu_Activity_Cost::get_crew( $id ),
            'roles'   => Edu_Activity_Cost::role_labels(),
        ] );
    }

    public static function abc_save_crew( WP_REST_Request $req ): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        self::_abc();
        $id = (int) $req['session_id'];
        if ( ! Edu_Activity_Cost::get_session( $id ) ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'جلسه یافت نشد' ], 404 );
        }
        $body = $req->get_json_params() ?: [];
        $members = $body['members'] ?? $body['crew'] ?? [];
        return new WP_REST_Response( Edu_Activity_Cost::save_crew( $id, is_array( $members ) ? $members : [] ) );
    }

    private static function can(): 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;
        }
        foreach ( [ 'education.accounting', 'education.accounting.post', 'acc.view', 'acc.post' ] as $pk ) {
            if ( function_exists( 'acl_user_can' ) && acl_user_can( $uid, $pk ) ) {
                return true;
            }
        }
        return false;
    }

    private static function guard(): ?WP_REST_Response {
        if ( ! self::can() ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'دسترسی حسابداری ندارید' ], 403 );
        }
        return null;
    }

    public static function get_config(): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        return new WP_REST_Response( Edu_Cost_Accounting::get_config() );
    }

    public static function save_config( WP_REST_Request $req ): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        $body = $req->get_json_params() ?: [];
        Edu_Cost_Accounting::save_config( $body );
        return new WP_REST_Response( [ 'success' => true, 'config' => Edu_Cost_Accounting::get_config() ] );
    }

    public static function get_portal(): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        return new WP_REST_Response( Acc_Portal_Accounting::meta( 'education' ) );
    }

    public static function save_portal( WP_REST_Request $req ): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        Acc_Portal_Accounting::save_portal_settings( 'education', $req->get_json_params() ?: [] );
        return new WP_REST_Response( [ 'success' => true, 'portal' => Acc_Portal_Accounting::portal_settings( 'education' ) ] );
    }

    public static function pending_queue(): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        return new WP_REST_Response( Edu_Cost_Accounting::pending_queue() );
    }

    public static function cost_report( WP_REST_Request $req ): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        return new WP_REST_Response( Edu_Cost_Accounting::cost_report(
            $req->get_param( 'from' ),
            $req->get_param( 'to' )
        ) );
    }

    public static function post_session( WP_REST_Request $req ): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        $result = Edu_Cost_Accounting::post_session( (int) $req['session_id'], (int) get_current_user_id() );
        $code   = ! empty( $result['success'] ) ? 200 : 400;
        return new WP_REST_Response( $result, $code );
    }

    public static function get_splits( WP_REST_Request $req ): WP_REST_Response {
        if ( $g = self::guard() ) {
            return $g;
        }
        global $wpdb;
        $t = Edu_Cost_Accounting::splits_table();
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$t} WHERE session_id = %d ORDER BY id", (int) $req['session_id']
        ), ARRAY_A ) ?: [];
        return new WP_REST_Response( [ 'splits' => $rows ] );
    }
}
