<?php
namespace ComptaFlowPro\Admin\Tables;

if (!class_exists('WP_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

defined('ABSPATH') || exit;

class TransactionsTable extends \WP_List_Table {
    private $transaction_type;
    private $page_slug;
    
    public function __construct($transaction_type = 'EXPENSE', $page_slug = '') {
        $this->transaction_type = $transaction_type;
        $this->page_slug = $page_slug;
        
        parent::__construct([
            'singular' => 'transaction',
            'plural' => 'transactions',
            'ajax' => false
        ]);
    }
    
    public function get_columns() {
        $columns = [
            'date_txn' => __('Date', 'comptaflow-by-meetempo'),
            'label' => __('Label', 'comptaflow-by-meetempo'),
            'partner_name' => __('Third Party', 'comptaflow-by-meetempo'),
            'amount_ht' => __('Net', 'comptaflow-by-meetempo'),
            'amount_tva' => __('VAT', 'comptaflow-by-meetempo'), 
            'amount_ttc' => __('Gross', 'comptaflow-by-meetempo'),
            'payment_status' => __('Status', 'comptaflow-by-meetempo')
        ];
        
        // Add 'Account' column if it exists
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        $columns_exist = $wpdb->get_results("SHOW COLUMNS FROM {$p}transactions LIKE 'account_code'");
        if (!empty($columns_exist)) {
            $new_columns = [];
            foreach ($columns as $key => $value) {
                $new_columns[$key] = $value;
                if ($key === 'label') {
                    $new_columns['account_code'] = __('Account', 'comptaflow-by-meetempo');
                }
            }
            $columns = $new_columns;
        }
        
        return $columns;
    }
    
    public function get_sortable_columns() {
        return [
            'date_txn' => ['date_txn', true],
            'label' => ['label', false],
            'partner_name' => ['partner_name', false],
            'amount_ttc' => ['amount_ttc', false],
            'payment_status' => ['payment_status', false]
        ];
    }
    
    public function prepare_items() {
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        
        $per_page = 20;
        $current_page = $this->get_pagenum();
        $offset = ($current_page - 1) * $per_page;
        
        // Sanitization with allowlist (WordPress.org requirement)
        $allowed_orderby = ['date_txn', 'label', 'partner_name', 'amount_ttc', 'payment_status'];
        $allowed_order = ['ASC', 'DESC'];
        
        $orderby = 'date_txn'; // Default
        if (!empty($_GET['orderby'])) {
            $requested_orderby = sanitize_text_field(wp_unslash($_GET['orderby']));
            if (in_array($requested_orderby, $allowed_orderby, true)) {
                $orderby = $requested_orderby;
            }
        }
        
        $order = 'DESC'; // Default
        if (!empty($_GET['order'])) {
            $requested_order = strtoupper(sanitize_text_field(wp_unslash($_GET['order'])));
            if (in_array($requested_order, $allowed_order, true)) {
                $order = $requested_order;
            }
        }

        $where_clauses = [];
        $params = [];

        $where_clauses[] = "created_by = %d";
        $params[] = get_current_user_id();

        if (is_array($this->transaction_type) && !empty($this->transaction_type)) {
            $placeholders = implode(', ', array_fill(0, count($this->transaction_type), '%s'));
            $where_clauses[] = "type IN ($placeholders)";
            $params = array_merge($params, $this->transaction_type);
        } elseif (is_string($this->transaction_type) && !empty($this->transaction_type)) {
            $where_clauses[] = "type = %s";
            $params[] = $this->transaction_type;
        } else {
            $where_clauses[] = "1=0";
        }
        
        $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);
        
        // Query for total items count
        $total_items_query = $wpdb->prepare("SELECT COUNT(*) FROM {$p}transactions {$where_sql}", ...$params);
        $total_items = $wpdb->get_var($total_items_query);
        
        // Query for current page items
        $query_params_paged = array_merge($params, [$per_page, $offset]);
        $query = $wpdb->prepare("
            SELECT * FROM {$p}transactions 
            {$where_sql}
            ORDER BY {$orderby} {$order}
            LIMIT %d OFFSET %d
        ", ...$query_params_paged);
        
        $this->items = $wpdb->get_results($query);
        
        $this->set_pagination_args([
            'total_items' => $total_items,
            'per_page'    => $per_page,
        ]);

        $this->_column_headers = [$this->get_columns(), [], $this->get_sortable_columns()];
    }
    
    public function column_default($item, $column_name) {
        switch ($column_name) {
            case 'date_txn':
                return esc_html(date_i18n('d/m/Y', strtotime($item->date_txn)));
            case 'label':
                $page = $this->page_slug ?: 'comptaflow-' . strtolower($item->type) . 's';
                $nonce_action = 'comptaflow_delete_' . strtolower($item->type);

                $edit_link = admin_url("admin.php?page={$page}&action=edit&id={$item->id}");
                $delete_link = wp_nonce_url(admin_url("admin.php?page={$page}&action=delete&id={$item->id}"), $nonce_action);
                
                $actions = apply_filters('comptaflow_transaction_row_actions', [
                    'edit' => '<a href="' . esc_url($edit_link) . '">' . esc_html__('Edit', 'comptaflow-by-meetempo') . '</a>',
                    'delete' => '<a href="' . esc_url($delete_link) . '" onclick="return confirm(\'' . esc_js(__('Delete this transaction?', 'comptaflow-by-meetempo')) . '\')">' . esc_html__('Delete', 'comptaflow-by-meetempo') . '</a>'
                ], $item);
                
                return sprintf('<strong><a href="%s">%s</a></strong>%s', esc_url($edit_link), esc_html($item->label), $this->row_actions($actions));
            case 'payment_status':
                if ($item->payment_status === 'PAID') {
                    return '<strong style="color:green;">✅ ' . esc_html__('Paid', 'comptaflow-by-meetempo') . '</strong>';
                }
                return '<strong style="color:#c86c00;">⏳ ' . esc_html__('Pending', 'comptaflow-by-meetempo') . '</strong>';
            default:
                return property_exists($item, $column_name) ? esc_html($item->$column_name) : '';
        }
    }
}
