<?php
/**
 * Template: Admin Page
 * Display list of signed agreements
 */

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

// Handle delete action
$action = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : '';
$delete_id = isset( $_GET['id'] ) ? absint( wp_unslash( $_GET['id'] ) ) : 0;
if ( $action === 'delete' && $delete_id && check_admin_referer( 'delete_agreement_' . $delete_id ) ) {
    global $wpdb;
    $id = $delete_id;
    $table_name = $wpdb->prefix . 'swpdf_signed_docs';
    
    // Get file path
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Safe: $table_name uses $wpdb->prefix
    $agreement = $wpdb->get_row( $wpdb->prepare( "SELECT file_path FROM $table_name WHERE id = %d", $id ) );
    if ( $agreement ) {
        // Delete file
        $upload_dir = wp_upload_dir();
        $file_path = $upload_dir['basedir'] . '/swpdf-signed-docs/' . $agreement->file_path;
        if ( file_exists( $file_path ) ) {
            wp_delete_file( $file_path );
        }
        
        // Delete database record
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe deletion by ID
        $wpdb->delete( $table_name, array( 'id' => $id ), array( '%d' ) );
        
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Agreement deleted successfully.', 'signwpdf-pdf-sign-fill' ) . '</p></div>';
    }
}

// Get agreements
global $wpdb;
$table_name = $wpdb->prefix . 'swpdf_signed_docs';
$per_page = 20;
$page = isset( $_GET['paged'] ) ? max( 1, intval( wp_unslash( $_GET['paged'] ) ) ) : 1;
$offset = ( $page - 1 ) * $per_page;

// Get filter values
$filter_date_from = isset( $_GET['date_from'] ) ? sanitize_text_field( wp_unslash( $_GET['date_from'] ) ) : '';
$filter_date_to = isset( $_GET['date_to'] ) ? sanitize_text_field( wp_unslash( $_GET['date_to'] ) ) : '';
$filter_type = isset( $_GET['agreement_type'] ) ? sanitize_text_field( wp_unslash( $_GET['agreement_type'] ) ) : '';

// Build WHERE clause
$where = array( '1=1' );
$params = array();

if ( $filter_date_from ) {
    $where[] = 'signed_at >= %s';
    $params[] = $filter_date_from . ' 00:00:00';
}
if ( $filter_date_to ) {
    $where[] = 'signed_at <= %s';
    $params[] = $filter_date_to . ' 23:59:59';
}
if ( $filter_type ) {
    $where[] = 'agreement_type = %s';
    $params[] = $filter_type;
}

$where_clause = implode( ' AND ', $where );

// Get total count
if ( ! empty( $params ) ) {
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Safe: $table_name uses $wpdb->prefix
    $total = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $table_name WHERE $where_clause", $params ) );
    $params_with_limit = array_merge( $params, array( $per_page, $offset ) );
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $agreements = $wpdb->get_results( $wpdb->prepare( 
        "SELECT * FROM $table_name WHERE $where_clause ORDER BY signed_at DESC LIMIT %d OFFSET %d",
        $params_with_limit
    ) );
} else {
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Safe: $table_name uses $wpdb->prefix
    $total = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" );
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $agreements = $wpdb->get_results( $wpdb->prepare( 
        "SELECT * FROM $table_name ORDER BY signed_at DESC LIMIT %d OFFSET %d",
        $per_page,
        $offset
    ) );
}

$total_pages = ceil( $total / $per_page );

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Safe: $table_name uses $wpdb->prefix
$agreement_types = $wpdb->get_col( "SELECT DISTINCT agreement_type FROM $table_name ORDER BY agreement_type" );

// Export nonce
$export_nonce = wp_create_nonce( 'swpdf_export_nonce' );
?>

<div class="wrap">
    <h1 class="wp-heading-inline">📄 Signed Agreements</h1>
    <span class="title-count"><?php echo esc_html( $total ); ?> total</span>
    <hr class="wp-header-end">
    
    <!-- Filter & Export Bar -->
    <div class="psf-filter-bar" style="background: #fff; padding: 15px; margin: 20px 0; border: 1px solid #ccd0d4; border-radius: 4px; display: flex; gap: 15px; align-items: flex-end; flex-wrap: wrap;">
        <div>
            <label style="display: block; margin-bottom: 4px; font-weight: 600; font-size: 12px;">From Date</label>
            <input type="date" name="date_from" id="filter_date_from" value="<?php echo esc_attr( $filter_date_from ); ?>" class="regular-text" style="padding: 5px;">
        </div>
        <div>
            <label style="display: block; margin-bottom: 4px; font-weight: 600; font-size: 12px;">To Date</label>
            <input type="date" name="date_to" id="filter_date_to" value="<?php echo esc_attr( $filter_date_to ); ?>" class="regular-text" style="padding: 5px;">
        </div>
        <div>
            <label style="display: block; margin-bottom: 4px; font-weight: 600; font-size: 12px;">Agreement Type</label>
            <select name="agreement_type" id="filter_agreement_type" style="padding: 5px; min-width: 150px;">
                <option value="">All Types</option>
                <?php foreach ( $agreement_types as $type ) : ?>
                    <option value="<?php echo esc_attr( $type ); ?>" <?php selected( $filter_type, $type ); ?>><?php echo esc_html( ucwords( str_replace( '-', ' ', $type ) ) ); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <button type="button" id="btn_filter" class="button button-primary">🔍 Filter</button>
            <button type="button" id="btn_clear_filter" class="button">Clear</button>
        </div>
        <div style="margin-left: auto;">
            <button type="button" id="btn_export_csv" class="button button-secondary" style="background: #00a32a; color: #fff; border-color: #00a32a;">📥 Export CSV</button>
        </div>
    </div>
    
    <?php if ( empty( $agreements ) ) : ?>
        <div class="notice notice-info">
            <p>No signed agreements found yet.</p>
        </div>
    <?php else : ?>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th style="width: 50px;">ID</th>
                    <th>Customer Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th style="width: 80px;">Stock #</th>
                    <th>Agreement Type</th>
                    <th>Signed Date</th>
                    <th style="width: 80px;">IP Address</th>
                    <th style="width: 220px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $agreements as $agreement ) : ?>
                    <tr>
                        <td><?php echo esc_html( $agreement->id ); ?></td>
                        <td>
                            <strong><?php echo esc_html( $agreement->customer_name ); ?></strong>
                        </td>
                        <td><?php echo esc_html( $agreement->customer_email ); ?></td>
                        <td><?php echo esc_html( $agreement->customer_phone ); ?></td>
                        <td><?php echo esc_html( isset( $agreement->stock_number ) ? $agreement->stock_number : '' ); ?></td>
                        <td><?php echo esc_html( ucwords( str_replace( '-', ' ', $agreement->agreement_type ) ) ); ?></td>
                        <td><?php echo esc_html( wp_date( 'M j, Y g:i A', strtotime( $agreement->signed_at ) ) ); ?></td>
                        <td><code style="font-size: 11px;"><?php echo esc_html( $agreement->ip_address ?? 'N/A' ); ?></code></td>
                        <td>
                            <?php
                            $upload_dir = wp_upload_dir();
                            $file_url = $upload_dir['baseurl'] . '/swpdf-signed-docs/' . $agreement->file_path;
                            $file_path = $upload_dir['basedir'] . '/swpdf-signed-docs/' . $agreement->file_path;
                            ?>
                            <?php if ( file_exists( $file_path ) ) : ?>
                                <a href="<?php echo esc_url( $file_url ); ?>" class="button button-small" target="_blank">View PDF</a>
                                <a href="<?php echo esc_url( $file_url ); ?>" class="button button-small" download>Download</a>
                            <?php else : ?>
                                <em>File not found</em>
                            <?php endif; ?>
                            <?php 
                            // Get all form_data for this agreement
                            $form_data_json = isset( $agreement->form_data ) ? $agreement->form_data : '{}';
                            ?>
                            <a href="#" class="button button-small view-details" data-id="<?php echo esc_attr( $agreement->id ); ?>" data-details="<?php echo esc_attr( $form_data_json ); ?>" title="View Captured Fields">📋</a>
                            <a href="#" class="button button-small view-audit" data-id="<?php echo esc_attr( $agreement->id ); ?>" data-audit="<?php echo esc_attr( wp_json_encode( array(
                                'id' => $agreement->id,
                                'customer_name' => $agreement->customer_name,
                                'customer_email' => $agreement->customer_email,
                                'signed_at' => wp_date( 'F j, Y \a\t g:i:s A', strtotime( $agreement->signed_at ) ),
                                'ip_address' => $agreement->ip_address ?? 'Not recorded',
                                'user_agent' => $agreement->user_agent ?? 'Not recorded',
                            ) ) ); ?>" title="View Audit Trail">🔒</a>
                            <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=signwpdf-pdf-sign-fill&action=delete&id=' . intval( $agreement->id ) ), 'delete_agreement_' . intval( $agreement->id ) ) ); ?>" class="button button-small button-link-delete" onclick="return confirm('Are you sure you want to delete this agreement?');">Delete</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <?php if ( $total_pages > 1 ) : ?>
            <div class="tablenav">
                <div class="tablenav-pages">
                    <?php
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- paginate_links() returns safe HTML
                    echo paginate_links( array(
                        'base' => add_query_arg( 'paged', '%#%' ),
                        'format' => '',
                        'prev_text' => '&laquo;',
                        'next_text' => '&raquo;',
                        'total' => $total_pages,
                        'current' => $page
                    ) );
                    ?>
                </div>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<!-- Details Modal -->
<div id="agreement-details-modal" style="display: none;">
    <div class="agreement-details-overlay"></div>
    <div class="agreement-details-content">
        <span class="close-modal">&times;</span>
        <h2 id="modal-title">Agreement Details</h2>
        <div id="agreement-details-body"></div>
    </div>
</div>
