<?php
// File: src/Admin/Tables/TransactionsTable.php
// Version 1.0 - UK Transactions List Table

namespace ComptaFlowUK\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' => esc_html__('Date', 'comptaflow-uk-by-meetempo'),
            'label' => esc_html__('Description', 'comptaflow-uk-by-meetempo'),
            'partner_name' => esc_html__('Counterparty', 'comptaflow-uk-by-meetempo'),
            'amount_ht' => esc_html__('Net', 'comptaflow-uk-by-meetempo'),
            'amount_tva' => esc_html__('VAT', 'comptaflow-uk-by-meetempo'), 
            'amount_ttc' => esc_html__('Gross', 'comptaflow-uk-by-meetempo'),
            'payment_status' => esc_html__('Status', 'comptaflow-uk-by-meetempo')
        ];
        
        // Add 'Account' column if it exists
        global $wpdb;
        $columns_exist = $wpdb->get_results("SHOW COLUMNS FROM {$wpdb->prefix}cfuk_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'] = esc_html__('Account', 'comptaflow-uk-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;
        $table = $wpdb->prefix . 'cfuk_transactions';

        $per_page = 20;
        $current_page = $this->get_pagenum();
        $offset = ($current_page - 1) * $per_page;

        // Order by — hardcoded mapping so the value never comes from user input
        $allowed_orderby = [
            'date_txn'       => 'date_txn',
            'label'          => 'label',
            'partner_name'   => 'partner_name',
            'amount_ttc'     => 'amount_ttc',
            'payment_status' => 'payment_status',
        ];
        $orderby_key = isset($_GET['orderby']) ? sanitize_key($_GET['orderby']) : '';
        $orderby = isset($allowed_orderby[$orderby_key]) ? $allowed_orderby[$orderby_key] : 'date_txn';

        // Order direction — ternary ensures only literal 'ASC' or 'DESC'
        $order = (!empty($_GET['order']) && 'ASC' === strtoupper(sanitize_text_field(wp_unslash($_GET['order'])))) ? 'ASC' : 'DESC';

        $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 count
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name from $wpdb->prefix, where_sql uses prepare placeholders
        $total_items = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} {$where_sql}", ...$params));

        // Query for current page items
        $query_params_paged = array_merge($params, [$per_page, $offset]);
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $orderby/$order from hardcoded allowlist, $table from $wpdb->prefix
        $this->items = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$table} {$where_sql} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d",
            ...$query_params_paged
        ));

        $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-uk-' . strtolower($item->type) . 's';
                $nonce_action = 'comptaflow_uk_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_uk_transaction_row_actions', [
                    'edit' => '<a href="' . esc_url($edit_link) . '">' . esc_html__('Edit', 'comptaflow-uk-by-meetempo') . '</a>',
                    'delete' => '<a href="' . esc_url($delete_link) . '" onclick="return confirm(\'' . esc_js(__('Delete this transaction?', 'comptaflow-uk-by-meetempo')) . '\')">' . esc_html__('Delete', 'comptaflow-uk-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-uk-by-meetempo') . '</strong>';
                }
                return '<strong style="color:#c86c00;">⏳ ' . esc_html__('Pending', 'comptaflow-uk-by-meetempo') . '</strong>';
            default:
                return property_exists($item, $column_name) ? esc_html($item->$column_name) : '';
        }
    }
}
