<?php

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

class CPM_Dependencies_Controller {

    private static $table = 'cp_task_dependencies';

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

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

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

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

    public static function get_dependency( 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( 'cpm_dep_not_found', 'Not found', ['status' => 404] );
        return rest_ensure_response( self::map_dependency( $item ) );
    }

    public static function create_dependency( WP_REST_Request $request ) {
        global $wpdb;
        $params = $request->get_json_params();
        
        if ( empty($params['project_id']) || empty($params['predecessor_task_id']) || empty($params['successor_task_id']) ) {
            return new WP_Error( 'cpm_missing_fields', 'Required fields missing', ['status' => 400] );
        }
        if ( $params['predecessor_task_id'] == $params['successor_task_id'] ) {
            return new WP_Error( 'cpm_self_link', 'Task cannot depend on itself', ['status' => 400] );
        }

        $data = [
            'project_id' => (int)$params['project_id'],
            'predecessor_task_id' => (int)$params['predecessor_task_id'],
            'successor_task_id' => (int)$params['successor_task_id'],
            'type' => in_array($params['type'] ?? '', ['FS', 'FF', 'SS', 'SF']) ? $params['type'] : 'FS',
            'lag' => (int)($params['lag'] ?? 0)
        ];

        $wpdb->insert( $wpdb->prefix . self::$table, $data );
        if ( $wpdb->last_error ) return new WP_Error( 'cpm_insert_error', $wpdb->last_error, ['status' => 500] );
        
        $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_dependency($item), 201 );
    }

    public static function update_dependency( 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( 'cpm_not_found', 'Not found', ['status' => 404] );

        $params = $request->get_json_params();
        $fields = [];
        $allowed = ['project_id', 'predecessor_task_id', 'successor_task_id', 'type', 'lag'];
        foreach ( $allowed as $key ) {
            if ( isset( $params[$key] ) ) $fields[$key] = $params[$key];
        }

        if ( empty( $fields ) ) return new WP_Error( 'cpm_no_data', 'No data', ['status' => 400] );
        
        $wpdb->update( $wpdb->prefix . self::$table, $fields, ['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_dependency( $item ) );
    }

    public static function delete_dependency( 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( 'cpm_not_found', 'Not found', ['status' => 404] );
        
        $wpdb->delete( $wpdb->prefix . self::$table, ['id' => $id] );
        return rest_ensure_response( ['deleted' => true, 'previous' => self::map_dependency($existing)] );
    }

    private static function map_dependency( $r ) {
        return [
            'id' => (int)$r['id'],
            'project_id' => (int)$r['project_id'],
            'predecessor_task_id' => (int)$r['predecessor_task_id'],
            'successor_task_id' => (int)$r['successor_task_id'],
            'type' => $r['type'],
            'lag' => (int)$r['lag'],
            'created_at' => $r['created_at'] ?? '',
            'updated_at' => $r['updated_at'] ?? ''
        ];
    }
}
