<?php

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

class CPM_Resources_Controller {

    private static $table = 'cp_resources';

    public static function get_resources( WP_REST_Request $request ) {
        global $wpdb;
        $project_id = $request->get_param( 'project_id' );
        $type       = $request->get_param( 'type' );

        $where = []; $params = [];
        if ( $project_id ) { $where[] = 'project_id = %d'; $params[] = (int)$project_id; }
        if ( $type ) { $where[] = 'type = %s'; $params[] = sanitize_text_field($type); }

        $where_sql = !empty($where) ? ' WHERE ' . implode(' AND ', $where) : '';
        $items = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}" . self::$table . " {$where_sql} ORDER BY project_id ASC, id ASC", $params ), ARRAY_A );

        return rest_ensure_response( array_map( ['self', 'map_resource'], $items ) );
    }

    public static function get_resource( WP_REST_Request $request ) {
        global $wpdb;
        $item = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}" . self::$table . " WHERE id = %d", (int)$request['id'] ), ARRAY_A );
        if ( ! $item ) return new WP_Error( 'not_found', 'Resource not found', ['status' => 404] );
        return rest_ensure_response( self::map_resource( $item ) );
    }

    public static function create_resource( WP_REST_Request $request ) {
        global $wpdb;
        $params = $request->get_json_params();
        if ( empty($params['project_id']) || empty($params['type']) || empty($params['name']) ) {
            return new WP_Error( 'invalid_data', 'Missing fields', ['status' => 400] );
        }

        $data = [
            'project_id' => (int)$params['project_id'],
            'type'       => sanitize_text_field($params['type']),
            'name'       => sanitize_text_field($params['name']),
            'code'       => isset($params['code']) ? sanitize_text_field($params['code']) : null,
            'unit'       => isset($params['unit']) ? sanitize_text_field($params['unit']) : null,
            'cost_per_unit' => isset($params['cost_per_unit']) ? (float)$params['cost_per_unit'] : null,
            'currency'   => isset($params['currency']) ? sanitize_text_field($params['currency']) : 'IRR',
            'calendar_id'=> isset($params['calendar_id']) ? (int)$params['calendar_id'] : null,
            'attributes_json' => isset($params['attributes']) ? wp_json_encode($params['attributes']) : null,
            'is_active'  => isset($params['is_active']) ? (int)!!$params['is_active'] : 1
        ];

        $wpdb->insert( $wpdb->prefix . self::$table, $data );
        $item = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}" . self::$table . " WHERE id = %d", $wpdb->insert_id ), ARRAY_A );
        return new WP_REST_Response( self::map_resource($item), 201 );
    }

    public static function update_resource( WP_REST_Request $request ) {
        global $wpdb;
        $id = (int)$request['id'];
        $existing = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}" . self::$table . " WHERE id = %d", $id ), ARRAY_A );
        if ( ! $existing ) return new WP_Error( 'not_found', 'Resource not found', ['status' => 404] );

        $params = $request->get_json_params();
        $data = [];
        $fields = ['project_id', 'type', 'name', 'code', 'unit', 'cost_per_unit', 'currency', 'calendar_id', 'is_active'];
        
        foreach($fields as $f) if(isset($params[$f])) $data[$f] = $params[$f];
        if(isset($params['attributes'])) $data['attributes_json'] = wp_json_encode($params['attributes']);

        if(empty($data)) return new WP_Error( 'no_data', 'No fields', ['status' => 400] );
        
        $wpdb->update( $wpdb->prefix . self::$table, $data, ['id' => $id] );
        $item = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}" . self::$table . " WHERE id = %d", $id ), ARRAY_A );
        return rest_ensure_response( self::map_resource($item) );
    }

    public static function delete_resource( WP_REST_Request $request ) {
        global $wpdb;
        $id = (int)$request['id'];
        if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}" . self::$table . " WHERE id = %d", $id ) ) ) 
            return new WP_Error( 'not_found', 'Not found', ['status' => 404] );
        
        $wpdb->delete( $wpdb->prefix . self::$table, ['id' => $id] );
        return rest_ensure_response( ['deleted' => true, 'id' => $id] );
    }

    public static function map_resource( $r ) {
        return [
            'id' => (int)$r['id'],
            'project_id' => (int)$r['project_id'],
            'type' => $r['type'],
            'name' => $r['name'],
            'code' => $r['code'],
            'unit' => $r['unit'],
            'cost_per_unit' => (float)$r['cost_per_unit'],
            'currency' => $r['currency'],
            'calendar_id' => $r['calendar_id'] ? (int)$r['calendar_id'] : null,
            'attributes' => isset($r['attributes_json']) ? json_decode($r['attributes_json'], true) : null,
            'is_active' => (bool)$r['is_active']
        ];
    }
}
