<?php
/**
 * Projects_Controller.php
 * مدیریت پروژه‌های مشتری (فروشگاه / املاک)
 *
 * GET    /acc/v1/projects          → لیست
 * POST   /acc/v1/projects          → ایجاد
 * GET    /acc/v1/projects/{id}     → جزئیات
 * PUT    /acc/v1/projects/{id}     → ویرایش
 * DELETE /acc/v1/projects/{id}     → حذف
 * POST   /acc/v1/projects/{id}/activate → فعال‌سازی
 * GET    /acc/v1/projects/active   → پروژه فعال جاری
 */

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

class Projects_Controller {

    const TABLE = 'acc_projects';

    /* ── ثبت مسیرها ──────────────────────────────────── */
    public static function register_routes(): void {
        $ns = 'acc/v1';
        $p  = 'acc_jwt_check_permission';

        register_rest_route( $ns, '/projects', [
            [ 'methods' => 'GET',  'callback' => [ __CLASS__, 'list_projects' ],  'permission_callback' => $p ],
            [ 'methods' => 'POST', 'callback' => [ __CLASS__, 'create_project' ], 'permission_callback' => $p ],
        ] );

        register_rest_route( $ns, '/projects/active', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'get_active' ], 'permission_callback' => $p,
        ] );

        register_rest_route( $ns, '/projects/(?P<id>\d+)', [
            [ 'methods' => 'GET',    'callback' => [ __CLASS__, 'get_project' ],    'permission_callback' => $p ],
            [ 'methods' => 'PUT',    'callback' => [ __CLASS__, 'update_project' ], 'permission_callback' => $p ],
            [ 'methods' => 'DELETE', 'callback' => [ __CLASS__, 'delete_project' ], 'permission_callback' => $p ],
        ] );

        register_rest_route( $ns, '/projects/(?P<id>\d+)/activate', [
            'methods' => 'POST', 'callback' => [ __CLASS__, 'activate_project' ], 'permission_callback' => $p,
        ] );

        register_rest_route( $ns, '/projects/pages', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'get_wp_pages' ], 'permission_callback' => $p,
        ] );
    }

    /* ── نصب جدول ────────────────────────────────────── */
    public static function install(): void {
        global $wpdb;
        $table   = $wpdb->prefix . self::TABLE;
        $charset = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
            id              int(11)          NOT NULL AUTO_INCREMENT,
            title           varchar(200)     NOT NULL,
            type            enum('shop','realestate','portal','custom') NOT NULL DEFAULT 'shop',
            status          enum('active','draft','archived') NOT NULL DEFAULT 'draft',
            is_running      tinyint(1)       NOT NULL DEFAULT 0,
            company_name    varchar(200)     NULL,
            company_tagline varchar(300)     NULL,
            company_logo    varchar(500)     NULL,
            company_phone   varchar(50)      NULL,
            company_email   varchar(200)     NULL,
            company_address text             NULL,
            domain          varchar(300)     NULL,
            front_page_id   int(11)          NULL,
            description     text             NULL,
            settings        longtext         NULL,
            created_at      datetime         NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at      datetime         NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_running (is_running),
            KEY idx_type    (type),
            KEY idx_status  (status)
        ) {$charset};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );
    }

    /* ════════════════════════════════════════════════════
       لیست پروژه‌ها
    ════════════════════════════════════════════════════ */
    public static function list_projects( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $table  = $wpdb->prefix . self::TABLE;
        $type   = sanitize_text_field( $req->get_param('type')   ?? '' );
        $status = sanitize_text_field( $req->get_param('status') ?? '' );

        $wheres = [];
        $args   = [];
        if ( $type )   { $wheres[] = 'type = %s';   $args[] = $type;   }
        if ( $status ) { $wheres[] = 'status = %s'; $args[] = $status; }

        $uid = acl_current_user_id();
        if ( ! acl_append_scope_where( $uid, 'project', 'id', $wheres, $args ) ) {
            return new WP_REST_Response( [ 'success' => true, 'data' => [] ] );
        }
        $where = $wheres ? 'WHERE ' . implode( ' AND ', $wheres ) : '';

        $sql  = "SELECT * FROM {$table} {$where} ORDER BY is_running DESC, created_at DESC";
        $rows = $args
            ? $wpdb->get_results( $wpdb->prepare( $sql, ...$args ), ARRAY_A )
            : $wpdb->get_results( $sql, ARRAY_A );

        foreach ( $rows as &$r ) {
            $r['settings'] = $r['settings'] ? json_decode( $r['settings'], true ) : null;
            $r['front_page_title'] = $r['front_page_id']
                ? get_the_title( (int)$r['front_page_id'] ) : '';
        }

        return new WP_REST_Response( [ 'success' => true, 'data' => $rows ?? [] ] );
    }

    /* ════════════════════════════════════════════════════
       پروژه فعال جاری
    ════════════════════════════════════════════════════ */
    public static function get_active( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $table = $wpdb->prefix . self::TABLE;
        $row   = $wpdb->get_row( "SELECT * FROM {$table} WHERE is_running = 1 LIMIT 1", ARRAY_A );
        if ( ! $row ) return new WP_REST_Response( [ 'success' => true, 'data' => null ] );
        $deny = acl_deny_scope( acl_current_user_id(), 'project', (int) $row['id'], '' );
        if ( $deny ) return new WP_REST_Response( [ 'success' => true, 'data' => null ] );
        $row['settings'] = $row['settings'] ? json_decode( $row['settings'], true ) : null;
        return new WP_REST_Response( [ 'success' => true, 'data' => $row ] );
    }

    /* ════════════════════════════════════════════════════
       جزئیات یک پروژه
    ════════════════════════════════════════════════════ */
    public static function get_project( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $table = $wpdb->prefix . self::TABLE;
        $id    = (int) $req->get_param('id');
        $deny  = acl_deny_scope( acl_current_user_id(), 'project', $id, '' );
        if ( $deny ) return $deny;
        $row   = $wpdb->get_row(
            $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ),
            ARRAY_A
        );
        if ( ! $row ) return new WP_REST_Response( [ 'message' => 'یافت نشد' ], 404 );
        $row['settings'] = $row['settings'] ? json_decode( $row['settings'], true ) : null;
        return new WP_REST_Response( [ 'success' => true, 'data' => $row ] );
    }

    /* ════════════════════════════════════════════════════
       ایجاد پروژه
    ════════════════════════════════════════════════════ */
    public static function create_project( WP_REST_Request $req ): WP_REST_Response {
        $deny = acl_deny_if_scope_restricted( acl_current_user_id(), 'project' );
        if ( $deny ) return $deny;
        global $wpdb;
        $data = self::_extract_data( $req );
        if ( empty( $data['title'] ) )
            return new WP_REST_Response( [ 'success' => false, 'message' => 'عنوان الزامی است' ], 400 );

        $wpdb->insert( $wpdb->prefix . self::TABLE, $data );
        $id = $wpdb->insert_id;
        return new WP_REST_Response( [ 'success' => true, 'id' => $id ], 201 );
    }

    /* ════════════════════════════════════════════════════
       ویرایش پروژه
    ════════════════════════════════════════════════════ */
    public static function update_project( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $id   = (int) $req->get_param('id');
        $deny = acl_deny_scope( acl_current_user_id(), 'project', $id, '' );
        if ( $deny ) return $deny;
        $data = self::_extract_data( $req );
        unset( $data['is_running'] ); // فعال‌سازی جداگانه است
        $wpdb->update( $wpdb->prefix . self::TABLE, $data, [ 'id' => $id ] );
        return new WP_REST_Response( [ 'success' => true ] );
    }

    /* ════════════════════════════════════════════════════
       حذف پروژه
    ════════════════════════════════════════════════════ */
    public static function delete_project( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $id  = (int) $req->get_param('id');
        $deny = acl_deny_scope( acl_current_user_id(), 'project', $id, '' );
        if ( $deny ) return $deny;
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT is_running FROM {$wpdb->prefix}" . self::TABLE . " WHERE id = %d", $id
        ) );
        if ( $row && $row->is_running )
            return new WP_REST_Response( [ 'success' => false, 'message' => 'پروژه فعال را نمی‌توان حذف کرد' ], 400 );

        $wpdb->delete( $wpdb->prefix . self::TABLE, [ 'id' => $id ] );
        return new WP_REST_Response( [ 'success' => true ] );
    }

    /* ════════════════════════════════════════════════════
       فعال‌سازی پروژه — قلب سیستم
    ════════════════════════════════════════════════════ */
    public static function activate_project( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $id    = (int) $req->get_param('id');
        $deny  = acl_deny_scope( acl_current_user_id(), 'project', $id, '' );
        if ( $deny ) return $deny;
        $table = $wpdb->prefix . self::TABLE;

        $project = $wpdb->get_row(
            $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ), ARRAY_A
        );
        if ( ! $project )
            return new WP_REST_Response( [ 'success' => false, 'message' => 'پروژه یافت نشد' ], 404 );

        /* ── غیرفعال کردن همه ── */
        $wpdb->query( "UPDATE {$table} SET is_running = 0" );

        /* ── فعال کردن این پروژه ── */
        $wpdb->update( $table, [ 'is_running' => 1, 'status' => 'active' ], [ 'id' => $id ] );

        /* ── اعمال تنظیمات روی WordPress ── */
        self::_apply_to_wordpress( $project );

        return new WP_REST_Response( [
            'success' => true,
            'message' => "پروژه «{$project['title']}» فعال شد",
        ] );
    }

    /* ── اعمال تنظیمات پروژه روی WordPress ──────────── */
    private static function _apply_to_wordpress( array $project ): void {
        /* نام سایت و توضیح */
        if ( ! empty( $project['company_name'] ) ) {
            update_option( 'blogname',        $project['company_name'] );
            update_option( 'blogdescription', $project['company_tagline'] ?? '' );
        }

        /* صفحه اول */
        if ( ! empty( $project['front_page_id'] ) ) {
            update_option( 'show_on_front', 'page' );
            update_option( 'page_on_front', (int) $project['front_page_id'] );
        }

        /* لوگو — ذخیره در custom_logo اگر attachment باشد */
        if ( ! empty( $project['company_logo'] ) ) {
            update_option( 'acc_active_project_logo', $project['company_logo'] );
        }

        /* اطلاعات تماس برای استفاده در قالب */
        update_option( 'acc_active_project_id',      $project['id'] );
        update_option( 'acc_active_project_type',    $project['type'] );
        update_option( 'acc_active_project_phone',   $project['company_phone']   ?? '' );
        update_option( 'acc_active_project_email',   $project['company_email']   ?? '' );
        update_option( 'acc_active_project_address', $project['company_address'] ?? '' );
    }

    /* ── لیست صفحات وردپرس برای انتخاب صفحه اول ──── */
    public static function get_wp_pages( WP_REST_Request $req ): WP_REST_Response {
        $pages = get_posts( [
            'post_type'      => 'page',
            'post_status'    => 'publish',
            'numberposts'    => 100,
            'orderby'        => 'title',
            'order'          => 'ASC',
        ] );
        $data = array_map( fn($p) => [
            'id'    => $p->ID,
            'title' => $p->post_title,
            'slug'  => $p->post_name,
            'url'   => get_permalink( $p->ID ),
        ], $pages );
        return new WP_REST_Response( [ 'success' => true, 'data' => $data ] );
    }

    /* ── استخراج فیلدها از request ───────────────────── */
    private static function _extract_data( WP_REST_Request $req ): array {
        $settings = $req->get_param('settings');
        return array_filter( [
            'title'           => sanitize_text_field( $req->get_param('title')           ?? '' ),
            'type'            => in_array( $req->get_param('type'), ['shop','realestate','portal','custom'] )
                                    ? $req->get_param('type') : 'shop',
            'status'          => in_array( $req->get_param('status'), ['active','draft','archived'] )
                                    ? $req->get_param('status') : 'draft',
            'company_name'    => sanitize_text_field( $req->get_param('company_name')    ?? '' ),
            'company_tagline' => sanitize_text_field( $req->get_param('company_tagline') ?? '' ),
            'company_logo'    => esc_url_raw(          $req->get_param('company_logo')   ?? '' ),
            'company_phone'   => sanitize_text_field( $req->get_param('company_phone')   ?? '' ),
            'company_email'   => sanitize_email(       $req->get_param('company_email')  ?? '' ),
            'company_address' => sanitize_textarea_field( $req->get_param('company_address') ?? '' ),
            'domain'          => sanitize_text_field( $req->get_param('domain')          ?? '' ),
            'front_page_id'   => $req->get_param('front_page_id') ? (int)$req->get_param('front_page_id') : null,
            'description'     => sanitize_textarea_field( $req->get_param('description') ?? '' ),
            'settings'        => $settings ? wp_json_encode( $settings ) : null,
        ], fn($v) => $v !== null && $v !== '' );
    }
}
