<?php
/**
 * C3P Capital API — MT5 EA sync (manual broker withdraw/deposit + ledger).
 */
declare(strict_types=1);

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

require_once ACC_PATH . 'includes/helpers/c3p-capital.php';

class C3P_Capital_Controller {

    public static function register_routes(): void {
        $ns   = 'acc/v1';
        $perm = [C3P_Capital::class, 'check_api_key'];

        register_rest_route($ns, '/c3p-capital/state', [
            ['methods' => 'GET',  'callback' => [self::class, 'get_state'],  'permission_callback' => $perm],
            ['methods' => 'PUT',  'callback' => [self::class, 'put_state'],  'permission_callback' => $perm],
        ]);

        register_rest_route($ns, '/c3p-capital/ledger', [
            ['methods' => 'GET',  'callback' => [self::class, 'get_ledger'],  'permission_callback' => $perm],
            ['methods' => 'POST', 'callback' => [self::class, 'post_ledger'], 'permission_callback' => $perm],
        ]);

        register_rest_route($ns, '/c3p-capital/pending', [
            ['methods' => 'GET',  'callback' => [self::class, 'get_pending'],  'permission_callback' => $perm],
            ['methods' => 'POST', 'callback' => [self::class, 'post_pending'], 'permission_callback' => $perm],
        ]);

        register_rest_route($ns, '/c3p-capital/pending/(?P<id>\d+)/confirm', [
            'methods'             => 'POST',
            'callback'            => [self::class, 'confirm_pending'],
            'permission_callback' => $perm,
        ]);
    }

    private static function login_from_request(WP_REST_Request $req): int {
        $json = $req->get_json_params();
        if (is_array($json) && !empty($json['account_login'])) {
            return (int) $json['account_login'];
        }
        return (int) ($req->get_param('account_login') ?? 0);
    }

    public static function get_state(WP_REST_Request $req): WP_REST_Response {
        $login = self::login_from_request($req);
        if ($login <= 0) {
            return new WP_REST_Response(['success' => false, 'message' => 'account_login required'], 400);
        }
        $state = C3P_Capital::get_state($login);
        return new WP_REST_Response(['success' => true, 'state' => $state], 200);
    }

    public static function put_state(WP_REST_Request $req): WP_REST_Response {
        $json = $req->get_json_params();
        if (!is_array($json)) {
            return new WP_REST_Response(['success' => false, 'message' => 'JSON body required'], 400);
        }
        $login = (int) ($json['account_login'] ?? 0);
        if ($login <= 0) {
            return new WP_REST_Response(['success' => false, 'message' => 'account_login required'], 400);
        }
        $result = C3P_Capital::upsert_state($login, $json);
        return new WP_REST_Response($result, 200);
    }

    public static function get_ledger(WP_REST_Request $req): WP_REST_Response {
        $login = self::login_from_request($req);
        if ($login <= 0) {
            return new WP_REST_Response(['success' => false, 'message' => 'account_login required'], 400);
        }
        $limit = (int) ($req->get_param('limit') ?? 200);
        $from  = $req->get_param('from') ? sanitize_text_field((string) $req->get_param('from')) : null;
        $to    = $req->get_param('to') ? sanitize_text_field((string) $req->get_param('to')) : null;
        return new WP_REST_Response([
            'success' => true,
            'data'    => C3P_Capital::ledger($login, $limit, $from, $to),
        ], 200);
    }

    public static function post_ledger(WP_REST_Request $req): WP_REST_Response {
        $json = $req->get_json_params();
        if (!is_array($json)) {
            return new WP_REST_Response(['success' => false, 'message' => 'JSON body required'], 400);
        }
        $login = (int) ($json['account_login'] ?? 0);
        if ($login <= 0) {
            return new WP_REST_Response(['success' => false, 'message' => 'account_login required'], 400);
        }
        $result = C3P_Capital::append_ledger($login, $json);
        $code   = !empty($result['success']) ? 200 : 500;
        return new WP_REST_Response($result, $code);
    }

    public static function get_pending(WP_REST_Request $req): WP_REST_Response {
        $login = self::login_from_request($req);
        if ($login <= 0) {
            return new WP_REST_Response(['success' => false, 'message' => 'account_login required'], 400);
        }
        $status = sanitize_text_field((string) ($req->get_param('status') ?? 'pending'));
        return new WP_REST_Response([
            'success' => true,
            'data'    => C3P_Capital::pending_list($login, $status),
        ], 200);
    }

    public static function post_pending(WP_REST_Request $req): WP_REST_Response {
        $json = $req->get_json_params();
        if (!is_array($json)) {
            return new WP_REST_Response(['success' => false, 'message' => 'JSON body required'], 400);
        }
        $login = (int) ($json['account_login'] ?? 0);
        if ($login <= 0) {
            return new WP_REST_Response(['success' => false, 'message' => 'account_login required'], 400);
        }
        $result = C3P_Capital::create_pending($login, $json);
        $code   = !empty($result['success']) ? 201 : 400;
        return new WP_REST_Response($result, $code);
    }

    public static function confirm_pending(WP_REST_Request $req): WP_REST_Response {
        $id    = (int) $req->get_param('id');
        $json  = $req->get_json_params();
        $login = is_array($json) ? (int) ($json['account_login'] ?? 0) : 0;
        $ticket = is_array($json) ? (int) ($json['deal_ticket'] ?? 0) : 0;
        if ($id <= 0 || $login <= 0) {
            return new WP_REST_Response(['success' => false, 'message' => 'id and account_login required'], 400);
        }
        $result = C3P_Capital::confirm_pending($id, $login, $ticket);
        $code   = (int) ($result['http'] ?? (!empty($result['success']) ? 200 : 500));
        unset($result['http']);
        return new WP_REST_Response($result, $code);
    }
}
