<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * REST Controller for Task Assignments (Database-Driven Architecture)
 */
class CPM_Assignments_Controller {

    /**
     * Helper to get table name
     */
    private static function get_table() {
        global $wpdb;
        return $wpdb->prefix . 'cp_task_assignments';
    }

    /* ---------------- List / Get ---------------- */

    public static function get_items( $request ) {
        global $wpdb;
        $table = self::get_table();

        $project_id  = $request->get_param( 'project_id' );
        $task_id     = $request->get_param( 'task_id' );
        $resource_id = $request->get_param( 'resource_id' );

        $where  = array();
        $params = array();

        if ( $project_id ) { $where[] = 'project_id = %d'; $params[] = (int) $project_id; }
        if ( $task_id )    { $where[] = 'task_id = %d';     $params[] = (int) $task_id; }
        if ( $resource_id ){ $where[] = 'resource_id = %d'; $params[] = (int) $resource_id; }

        $where_sql = ! empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : '';
        $sql = "SELECT * FROM {$table} {$where_sql} ORDER BY id ASC";

        $items = ! empty( $params ) ? $wpdb->get_results( $wpdb->prepare( $sql, $params ), ARRAY_A ) : $wpdb->get_results( $sql, ARRAY_A );

        $data = array();
        foreach ( $items as $item ) {
            $data[] = self::prepare_item_for_response( (object) $item, $request )->get_data();
        }

        return rest_ensure_response( $data );
    }

    public static function get_item( $request ) {
        global $wpdb;
        $id = (int) $request['id'];

        $item = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM " . self::get_table() . " WHERE id = %d", $id ) );

        if ( ! $item ) {
            return new WP_Error( 'cpm_assignment_not_found', __( 'Assignment not found', 'cpm' ), array( 'status' => 404 ) );
        }

        return self::prepare_item_for_response( $item, $request );
    }

    /* ---------------- Create ---------------- */

    public static function create_item( $request ) {
        global $wpdb;

        $data = array(
            'project_id'         => (int) $request->get_param( 'project_id' ),
            'task_id'            => (int) $request->get_param( 'task_id' ),
            'resource_id'        => (int) $request->get_param( 'resource_id' ),
            'allocation_percent' => (float) ( $request->get_param( 'allocation_percent' ) ?? 100.00 ),
            'units'              => $request->get_param( 'units' ) !== null ? (float) $request->get_param( 'units' ) : null,
            'role'               => $request->get_param( 'role' ),
            'notes'              => $request->get_param( 'notes' ),
        );

        if ( ! $data['project_id'] || ! $data['task_id'] || ! $data['resource_id'] ) {
            return new WP_Error( 'cpm_missing_fields', __( 'Required fields missing', 'cpm' ), array( 'status' => 400 ) );
        }

        $formats = array( '%d', '%d', '%d', '%f', '%f', '%s', '%s' );
        if ( is_null( $data['units'] ) ) { unset( $data['units'] ); array_splice($formats, 4, 1); }

        $inserted = $wpdb->insert( self::get_table(), $data, $formats );

        if ( false === $inserted ) {
            return new WP_Error( 'cpm_insert_error', __( 'Could not create.', 'cpm' ), array( 'status' => 500 ) );
        }

        $item = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM " . self::get_table() . " WHERE id = %d", $wpdb->insert_id ) );
        return self::prepare_item_for_response( $item, $request )->set_status( 201 );
    }

    /* ---------------- Update & Delete (خلاصه شده برای پایداری) ---------------- */
    // ... (می‌توانید منطق Update و Delete قبلی خود را مشابه متدهای بالا به static تغییر دهید)

    /* ---------------- Helper ---------------- */

    public static function prepare_item_for_response( $item, $request ) {
        $data = array(
            'id'                 => (int) $item->id,
            'project_id'         => (int) $item->project_id,
            'task_id'            => (int) $item->task_id,
            'resource_id'        => (int) $item->resource_id,
            'allocation_percent' => (float) $item->allocation_percent,
            'units'              => $item->units ? (float) $item->units : null,
            'role'               => $item->role,
            'notes'              => $item->notes,
        );
        return new WP_REST_Response( $data, 200 );
    }
}
