<?php
/**
 * ZUTALW Admin History Settings
 * Manages the Prize History and Customer Leads (Claimed Prizes).
 * UPDATE: Uses the new Anti-fraud `zutalw_prize_logs` table.
 */

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

class ZUTALW_Admin_History {

    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_history_menu' ) );
        add_action( 'admin_init', array( $this, 'handle_actions' ) );
    }

    /**
     * Add submenu under the main Zuta Lucky Wheel menu
     */
    public function add_history_menu() {
        add_submenu_page(
            'lucky-wheel-settings', // Parent slug
            esc_html__( 'Prize History', 'zuta-lucky-wheel' ),
            esc_html__( 'Prize History', 'zuta-lucky-wheel' ),
            'manage_options',
            'zutalw-history',
            array( $this, 'render_history_page' )
        );
    }

    /**
     * Handle delete actions before page renders
     */
    public function handle_actions() {
        if ( isset( $_GET['page'] ) && $_GET['page'] === 'zutalw-history' && isset( $_GET['action'] ) && $_GET['action'] === 'delete' && isset( $_GET['id'] ) ) {
            check_admin_referer( 'zutalw_delete_record_' . intval( $_GET['id'] ) );
            
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_die( esc_html__( 'Permission denied.', 'zuta-lucky-wheel' ) );
            }

            global $wpdb;
            $table_logs = $wpdb->prefix . 'zutalw_prize_logs';
            
            // Delete record from the new prize_logs table
            $wpdb->delete( $table_logs, array( 'id' => intval( $_GET['id'] ) ), array( '%d' ) );

            wp_safe_redirect( admin_url( 'admin.php?page=zutalw-history&deleted=1' ) );
            exit;
        }
    }

    /**
     * Render the UI
     */
    public function render_history_page() {
        if ( isset( $_GET['deleted'] ) && $_GET['deleted'] == '1' ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Record deleted successfully.', 'zuta-lucky-wheel' ) . '</p></div>';
        }

        global $wpdb;
        $table_logs      = $wpdb->prefix . 'zutalw_prize_logs';
        $table_campaigns = $wpdb->prefix . 'zutalw_campaigns';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $records = $wpdb->get_results( "
            SELECT 
                l.id, l.device_id, l.fullname, l.phone, l.email, l.prize_name, l.is_trade_in, l.created_at,
                camp.name AS campaign_name
            FROM {$table_logs} l
            LEFT JOIN {$table_campaigns} camp ON l.campaign_id = camp.id
            ORDER BY l.id DESC
            LIMIT 100
        " );
        ?>
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php echo esc_html__( 'Prize & Lead History', 'zuta-lucky-wheel' ); ?></h1>
            <p><?php echo esc_html__( 'Manage all successful customer leads and claimed gifts across campaigns.', 'zuta-lucky-wheel' ); ?></p>
            
            <table class="wp-list-table widefat fixed striped table-view-list">
                <thead>
                    <tr>
                        <th style="width: 50px;">ID</th>
                        <th><?php echo esc_html__( 'Customer Info', 'zuta-lucky-wheel' ); ?></th>
                        <th><?php echo esc_html__( 'Campaign', 'zuta-lucky-wheel' ); ?></th>
                        <th><?php echo esc_html__( 'Prize / Gift', 'zuta-lucky-wheel' ); ?></th>
                        <th><?php echo esc_html__( 'Status', 'zuta-lucky-wheel' ); ?></th>
                        <th style="width: 80px;"><?php echo esc_html__( 'Action', 'zuta-lucky-wheel' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ( ! empty( $records ) ) : ?>
                        <?php foreach ( $records as $row ) : 
                            $status_text  = esc_html__( 'Claimed (Lead)', 'zuta-lucky-wheel' );
                            $status_color = 'color: #155724; background-color: #d4edda; border-color: #c3e6cb;';
                            
                            if ( $row->is_trade_in == 1 ) {
                                $status_text  = esc_html__( 'Trade-in', 'zuta-lucky-wheel' );
                                $status_color = 'color: #856404; background-color: #fff3cd; border-color: #ffeeba;';
                            }
                        ?>
                            <tr>
                                <td><?php echo esc_html( $row->id ); ?></td>
                                <td>
                                    <strong><?php echo esc_html( $row->fullname ? $row->fullname : 'Guest ('.$row->device_id.')' ); ?></strong><br>
                                    <span class="dashicons dashicons-phone" style="font-size: 14px; margin-top: 3px;"></span> <?php echo esc_html( $row->phone ); ?><br>
                                    <?php if ( !empty($row->email) ) : ?>
                                        <span class="dashicons dashicons-email" style="font-size: 14px; margin-top: 3px;"></span> <?php echo esc_html( $row->email ); ?>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php echo !empty($row->campaign_name) ? esc_html( $row->campaign_name ) : '-'; ?>
                                </td>
                                <td>
                                    <span class="dashicons dashicons-awards" style="color: #f56e28;"></span> 
                                    <strong><?php echo esc_html( $row->prize_name ); ?></strong>
                                </td>
                                <td>
                                    <span style="display: inline-block; padding: 3px 8px; border-radius: 4px; border: 1px solid transparent; font-weight: 500; font-size: 12px; <?php echo $status_color; ?>">
                                        <?php echo $status_text; ?>
                                    </span>
                                </td>
                                <td>
                                    <?php
                                    $delete_url = wp_nonce_url( 
                                        admin_url( 'admin.php?page=zutalw-history&action=delete&id=' . $row->id ), 
                                        'zutalw_delete_record_' . $row->id 
                                    );
                                    ?>
                                    <a href="<?php echo esc_url( $delete_url ); ?>" class="button button-small" onclick="return confirm('<?php echo esc_js( __( 'Are you sure you want to delete this lead?', 'zuta-lucky-wheel' ) ); ?>');" style="color: #d63638; border-color: #d63638;">
                                        <?php echo esc_html__( 'Delete', 'zuta-lucky-wheel' ); ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else : ?>
                        <tr>
                            <td colspan="6"><?php echo esc_html__( 'No records found.', 'zuta-lucky-wheel' ); ?></td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
    }
}