<?php
if (!defined('ABSPATH'))
exit; // Exit if accessed directly
class DevsAccounting_Category{
    public function __construct()
    {
        add_action('rest_api_init', [$this, 'category_api_endpoint']);
    }

    // Define your custom endpoint
    public function category_api_endpoint() {
        register_rest_route('devs-accounting/v1', '/add-category', array(
            'methods' => 'POST', // Change to POST method to handle data insertion
            'callback' => [$this, 'save_category_data'],
            'permission_callback' => [$this, 'verify_category_nonce']
        ));

        register_rest_route('devs-accounting/v1', '/categories', array(
            'methods' => 'get', 
            'callback' => [$this, 'get_categories'],
            'permission_callback' => function () {
                return true;
            },
        ));
        
        register_rest_route('devs-accounting/v1', '/get-category/(?P<id>\d+)', array(
            'methods' => 'get', 
            'callback' => [$this, 'get_single_category'],
            'permission_callback' => function () {
                return true;
            },
        ));
        
        register_rest_route('devs-accounting/v1', '/delete-category/(?P<id>\d+)', array(
            'methods' => 'get', 
            'callback' => [$this, 'delete_single_category'],
            'permission_callback' => [$this, 'verify_category_nonce']
        ));

        register_rest_route('devs-accounting/v1', '/export-categories', [
            'methods' => 'GET',
            'callback' => [$this, 'export_categories'],
            'permission_callback' => [$this, 'verify_category_nonce'],
        ]);

        register_rest_route('devs-accounting/v1', '/import-categories', [
            'methods' => 'POST',
            'callback' => [$this, 'import_categories'],
            'permission_callback' => [$this, 'verify_category_nonce'],
        ]);
        register_rest_route('devs-accounting/v1', '/sample-category', [
            'methods' => 'GET',
            'callback' => [$this, 'download_sample_category'],
            'permission_callback' => [$this, 'verify_category_nonce'],
        ]);
        
        
    }

    function verify_category_nonce($request) {
        $nonce = $request->get_header('X-WP-Nonce');
        if (!wp_verify_nonce($nonce, 'wp_rest')) {
            return new WP_Error('rest_forbidden', esc_html__('Invalid nonce.', 'devs-accounting'), array('status' => 403));
        }
        return true;
    }

    public function get_categories($request) {
        global $wpdb;

        $table_name = $wpdb->prefix . 'dac_categories';
        if (!empty($request['type']) && $request['type'] === 'product') {
            $taxonomy     = 'product_cat';
            $orderby      = 'name';  
            $show_count   = 0;      // 1 for yes, 0 for no
            $pad_counts   = 0;      // 1 for yes, 0 for no
            $hierarchical = 1;      // 1 for yes, 0 for no  
            $title        = '';  
            $empty        = 0;
            $args = array(
                'taxonomy'     => $taxonomy,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
         );
        $all_categories = get_categories( $args );
        $results = [];
        foreach ($all_categories as $cat) {
               $results[] = [
                'id'=>$cat->term_id,
                'name'=>$cat->name,
                'type'=> 'item'

               ];
        }
        }else{
            $results = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM $table_name WHERE deleted_at IS NULL ORDER BY created_at DESC",
            ));
    
        }
        

        return rest_ensure_response($results);
    }    
    
    public function get_single_category($request) {
        global $wpdb;

        $table_name = $wpdb->prefix . 'dac_categories';

        $item_id = $request['id'];

        $category = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM $table_name WHERE ID = %d",
            $item_id
        ) );

        if ( $category ) {
            return rest_ensure_response( $category );
        } else {
            return new WP_Error( 'task_not_found', esc_html__( 'Task not found', 'devs-accounting' ), array( 'status' => 404 ) );
        }
    }

    public function delete_single_category($request) {
        global $wpdb;

        $table_name = $wpdb->prefix . 'dac_categories';

        $cat_id = isset($request['id']) ? intval($request['id']) : 0;

        if ($cat_id <= 0) {
            return new WP_Error( 'invalid_item_id', esc_html__( 'Invalid item ID', 'devs-accounting' ), array( 'status' => 400 ) );
        }
         
        $existing_category = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM $table_name WHERE ID = %d",
                $cat_id
            )
        );

        if (!$existing_category) {
            return new WP_Error( 'item_not_found', esc_html__( 'Item not found', 'devs-accounting' ), array( 'status' => 404 ) );
        }

        $current_time = gmdate('Y-m-d H:i:s'); 

        $result = $wpdb->update(
            $table_name,
            array( 
                'deleted_at' => $current_time,
                ),
            array( 'id' => $cat_id ),
        );

        if ($result === false) {
            return new WP_Error( 'soft_delete_failed', esc_html__( 'Failed to soft delete item', 'devs-accounting' ), array( 'status' => 500 ) );
        }

        return rest_ensure_response( array( 'message' => esc_html__('Item soft deleted successfully', 'devs-accounting') ) );
    }

    public function save_category_data($request) 
    {
       
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_categories';
    
        $name = sanitize_text_field($request['name']);
        $type = sanitize_text_field($request['type']);
    
        $errors = array();
    
        if (empty($name)) {
            $errors['name'] = esc_html__('Category name is required.', 'devs-accounting');
        }
    
        if (empty($type)) {
            $errors['type'] = esc_html__('Category type is required.', 'devs-accounting');
        }
    
        if (!empty($errors)) {
            $response = array(
                'message' => esc_html__('Validation errors occurred.', 'devs-accounting'),
                'errors' => $errors,
            );
            return new WP_REST_Response($response, 400);
        }
    
        $insert_data = array(
            'name' => $name,
            'type' => $type,
        );
    
        if (!empty($request['id'])) {
            $where = array('id' => $request['id']); 
            $table = $wpdb->update($table_name, $insert_data, $where);
    
            if ($table !== false) {
                $response = array(
                    'message' => esc_html__('Category updated successfully!', 'devs-accounting'),
                    'data' => $table,
                );
            } else {
                $response = array(
                    'message' => esc_html__('Update Category failed', 'devs-accounting'),
                );
            }
        } else {
            $table = $wpdb->insert($table_name, $insert_data);
    
            if ($table) {
                $response = array(
                    'message' => esc_html__('Category created successfully!', 'devs-accounting'),
                    'data' => $wpdb->insert_id,
                );
            } else {
                $response = array(
                    'message' => esc_html__('Create category failed', 'devs-accounting'),
                );
            }
        }
    
        return new WP_REST_Response($response, 200);
    }

    public function export_categories($request) 
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_categories';
        
        $categories = $wpdb->get_results("SELECT name, type FROM $table_name WHERE deleted_at IS NULL", ARRAY_A);
        
        if (empty($categories)) {
            return new WP_Error('no_data', __('No categories found to export.', 'devs-accounting'), ['status' => 404]);
        }
        
        $filename = 'categories-export-' . time() . '.csv';
        
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        
 
        fputcsv($output, ['Name', 'Type']);

        foreach ($categories as $cat) {
            $name = trim($cat['name']); 
            $type = trim($cat['type']);
            
            if (empty($name) || empty($type)) {
                continue;
            }
            
            fputcsv($output, [$name, $type]);
        }
        
        fclose($output);
        exit;
    }
    
    public function import_categories($request) 
    {
        if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            return new WP_Error('upload_error', __('CSV upload failed.', 'devs-accounting'), ['status' => 400]);
        }

        $csv_file = $_FILES['file']['tmp_name'];
        $handle = fopen($csv_file, 'r');

        if (!$handle) {
            return new WP_Error('csv_open_error', __('Could not open CSV file.', 'devs-accounting'), ['status' => 400]);
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_categories';

        $imported = 0;

        fgetcsv($handle); 

        while (($row = fgetcsv($handle)) !== false) {
            if (count($row) !== 2) {
                continue;
            }

            [$name, $type] = $row;
            $name = sanitize_text_field($name);
            $type = sanitize_text_field($type);

            if (!empty($name) && !empty($type)) {
                $inserted = $wpdb->insert($table_name, [
                    'name' => $name,
                    'type' => $type,
                ]);
                if ($inserted !== false) {
                    $imported++;
                }
            }
        }

        if (is_resource($handle)) {
            fclose($handle);
        }


        if ($imported > 0) {
            return new WP_REST_Response([
                'success' => true,
                'message' => "$imported categories imported successfully.",
            ]);
        } else {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'No categories were imported.',
            ], 400);  
        }
    }

    
    
    
    public function download_sample_category($request) 
    {
        $filename = 'sample-categories.csv';
    
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
    
        $output = fopen('php://output', 'w');
        fputcsv($output, ['name', 'type']);
        fclose($output);
        
        exit;
    }
    
    
}

$items = new DevsAccounting_Category();