<?php
/**
 * Admin Bookings Page Template
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

global $wpdb;
$db = WAHRB_Database::instance();

// ─── Read filter parameters ───
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational filter parameters, no data modification
$current_status = isset($_GET['status']) ? sanitize_text_field(wp_unslash($_GET['status'])) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational filter parameters, no data modification
$filter_vendor = isset($_GET['vendor_id']) ? absint($_GET['vendor_id']) : 0;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational filter parameters, no data modification
$filter_date_from = isset($_GET['date_from']) ? sanitize_text_field(wp_unslash($_GET['date_from'])) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational filter parameters, no data modification
$filter_date_to = isset($_GET['date_to']) ? sanitize_text_field(wp_unslash($_GET['date_to'])) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational filter parameters, no data modification
$filter_amount_min = isset($_GET['amount_min']) ? sanitize_text_field(wp_unslash($_GET['amount_min'])) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational filter parameters, no data modification
$filter_amount_max = isset($_GET['amount_max']) ? sanitize_text_field(wp_unslash($_GET['amount_max'])) : '';

$page_url = wahrb_get_admin_dashboard_url('bookings');

// ─── Get vendors who have bookings (for dropdown) ───
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom tables
$vendors_with_bookings = $wpdb->get_results("SELECT DISTINCT b.vendor_id, u.display_name FROM {$db->table('bookings')} b LEFT JOIN {$wpdb->users} u ON b.vendor_id = u.ID ORDER BY u.display_name ASC", ARRAY_A);

// ─── Get stats ───
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name from WAHRB_Database helper
$total_bookings = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$db->table('bookings')} WHERE deleted_at IS NULL");
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name from WAHRB_Database helper
$pending_bookings = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$db->table('bookings')} WHERE status = 'pending' AND deleted_at IS NULL");
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name from WAHRB_Database helper
$confirmed_bookings = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$db->table('bookings')} WHERE status = 'confirmed' AND deleted_at IS NULL");
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name from WAHRB_Database helper
$cancelled_bookings = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$db->table('bookings')} WHERE status = 'cancelled' AND deleted_at IS NULL");
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name from WAHRB_Database helper
$completed_bookings = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$db->table('bookings')} WHERE status = 'completed' AND deleted_at IS NULL");

// Status filters config
$status_filters = [
    '' => ['label' => __('All', 'wahra-rentals-bookings'), 'count' => $total_bookings, 'color' => '#1976d2'],
    'pending' => ['label' => __('Pending', 'wahra-rentals-bookings'), 'count' => $pending_bookings, 'color' => '#ed6c02'],
    'confirmed' => ['label' => __('Confirmed', 'wahra-rentals-bookings'), 'count' => $confirmed_bookings, 'color' => '#2e7d32'],
    'completed' => ['label' => __('Completed', 'wahra-rentals-bookings'), 'count' => $completed_bookings, 'color' => '#388e3c'],
    'cancelled' => ['label' => __('Cancelled', 'wahra-rentals-bookings'), 'count' => $cancelled_bookings, 'color' => '#d32f2f'],
];

// ─── Build query with all filters ───
$where_clauses = ['b.deleted_at IS NULL'];

if ($current_status) {
    $where_clauses[] = $wpdb->prepare('b.status = %s', $current_status);
}
if ($filter_vendor > 0) {
    $where_clauses[] = $wpdb->prepare('b.vendor_id = %d', $filter_vendor);
}
if ($filter_date_from && strtotime($filter_date_from)) {
    $where_clauses[] = $wpdb->prepare('b.start_dt >= %s', sanitize_text_field($filter_date_from) . ' 00:00:00');
}
if ($filter_date_to && strtotime($filter_date_to)) {
    $where_clauses[] = $wpdb->prepare('b.end_dt <= %s', sanitize_text_field($filter_date_to) . ' 23:59:59');
}
if ($filter_amount_min !== '' && is_numeric($filter_amount_min)) {
    $where_clauses[] = $wpdb->prepare('ps.total_amount >= %f', floatval($filter_amount_min));
}
if ($filter_amount_max !== '' && is_numeric($filter_amount_max)) {
    $where_clauses[] = $wpdb->prepare('ps.total_amount <= %f', floatval($filter_amount_max));
}

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

// Get bookings with payment_schedule JOIN for amount data
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $where clauses prepared above, table names from WAHRB_Database helper
$recent_bookings = $wpdb->get_results("SELECT b.*, u.display_name as vendor_name, p.post_title as product_name, ps.total_amount, ps.deposit_amount_final, ps.balance_amount_final, ps.deposit_status, ps.balance_status, ps.security_deposit_amount_final, ps.security_status FROM {$db->table('bookings')} b LEFT JOIN {$wpdb->users} u ON b.vendor_id = u.ID LEFT JOIN {$wpdb->posts} p ON b.product_id = p.ID LEFT JOIN {$db->table('payment_schedule')} ps ON b.booking_id = ps.booking_id WHERE {$where} ORDER BY b.created_at DESC LIMIT 100", ARRAY_A);

$has_active_filters = $filter_vendor || $filter_date_from || $filter_date_to || ($filter_amount_min !== '') || ($filter_amount_max !== '');

$status_labels = [
    'pending' => __('Pending', 'wahra-rentals-bookings'),
    'confirmed' => __('Confirmed', 'wahra-rentals-bookings'),
    'active' => __('Active', 'wahra-rentals-bookings'),
    'checked_in' => __('Checked In', 'wahra-rentals-bookings'),
    'checked_out' => __('Checked Out', 'wahra-rentals-bookings'),
    'completed' => __('Completed', 'wahra-rentals-bookings'),
    'cancelled' => __('Cancelled', 'wahra-rentals-bookings'),
    'refunded' => __('Refunded', 'wahra-rentals-bookings'),
];
?>

<div class="wrap wahrb-admin-wrap">
    <h1><?php esc_html_e('Bookings', 'wahra-rentals-bookings'); ?></h1>

    <!-- Status Filter Tabs -->
    <ul class="subsubsub" style="margin: 20px 0;">
        <?php $i = 0; foreach ($status_filters as $key => $filter): ?>
            <li>
                <a href="<?php echo esc_url($key ? add_query_arg('status', $key, $page_url) : $page_url); ?>" 
                   class="<?php echo esc_attr( $current_status === $key ? 'current' : '' ); ?>"
                   style="<?php echo esc_attr( $current_status === $key ? 'color: ' . $filter['color'] . '; font-weight: bold;' : '' ); ?>">
                    <?php echo esc_html($filter['label']); ?>
                    <span class="count">(<?php echo esc_html($filter['count']); ?>)</span>
                </a>
                <?php if (++$i < count($status_filters)): ?> | <?php endif; ?>
            </li>
        <?php endforeach; ?>
    </ul>

    <div style="clear: both;"></div>

    <!-- Filter Bar -->
    <form method="get" action="<?php echo esc_url($page_url); ?>" style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px 20px; margin-top: 12px; display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end;">
        <input type="hidden" name="page" value="<?php echo esc_attr(isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : 'wahrb-bookings'); ?>">
        <?php if ($current_status): ?>
            <input type="hidden" name="status" value="<?php echo esc_attr($current_status); ?>">
        <?php endif; ?>

        <?php if (count($vendors_with_bookings) > 1): ?>
        <div style="display: flex; flex-direction: column; gap: 4px;">
            <label for="wahrb-filter-vendor" style="font-size: 12px; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">
                <?php esc_html_e('Vendor', 'wahra-rentals-bookings'); ?>
            </label>
            <select name="vendor_id" id="wahrb-filter-vendor" style="min-width: 180px; height: 36px; border: 1px solid #cbd5e1; border-radius: 6px; padding: 0 8px;">
                <option value=""><?php esc_html_e('All vendors', 'wahra-rentals-bookings'); ?></option>
                <?php foreach ($vendors_with_bookings as $v): ?>
                    <option value="<?php echo esc_attr($v['vendor_id']); ?>" <?php selected($filter_vendor, (int) $v['vendor_id']); ?>>
                        <?php echo esc_html($v['display_name'] ?: 'Vendor #' . $v['vendor_id']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>

        <div style="display: flex; flex-direction: column; gap: 4px;">
            <label for="wahrb-filter-date-from" style="font-size: 12px; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">
                <?php esc_html_e('Date from', 'wahra-rentals-bookings'); ?>
            </label>
            <input type="date" name="date_from" id="wahrb-filter-date-from" value="<?php echo esc_attr($filter_date_from); ?>" style="height: 36px; border: 1px solid #cbd5e1; border-radius: 6px; padding: 0 8px;">
        </div>

        <div style="display: flex; flex-direction: column; gap: 4px;">
            <label for="wahrb-filter-date-to" style="font-size: 12px; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">
                <?php esc_html_e('Date to', 'wahra-rentals-bookings'); ?>
            </label>
            <input type="date" name="date_to" id="wahrb-filter-date-to" value="<?php echo esc_attr($filter_date_to); ?>" style="height: 36px; border: 1px solid #cbd5e1; border-radius: 6px; padding: 0 8px;">
        </div>

        <div style="display: flex; flex-direction: column; gap: 4px;">
            <label for="wahrb-filter-amount-min" style="font-size: 12px; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">
                <?php esc_html_e('Amount min', 'wahra-rentals-bookings'); ?>
            </label>
            <input type="number" name="amount_min" id="wahrb-filter-amount-min" value="<?php echo esc_attr($filter_amount_min); ?>" placeholder="0" min="0" step="0.01" style="width: 100px; height: 36px; border: 1px solid #cbd5e1; border-radius: 6px; padding: 0 8px;">
        </div>

        <div style="display: flex; flex-direction: column; gap: 4px;">
            <label for="wahrb-filter-amount-max" style="font-size: 12px; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">
                <?php esc_html_e('Amount max', 'wahra-rentals-bookings'); ?>
            </label>
            <input type="number" name="amount_max" id="wahrb-filter-amount-max" value="<?php echo esc_attr($filter_amount_max); ?>" placeholder="∞" min="0" step="0.01" style="width: 100px; height: 36px; border: 1px solid #cbd5e1; border-radius: 6px; padding: 0 8px;">
        </div>

        <div style="display: flex; gap: 8px; align-items: flex-end;">
            <button type="submit" class="button button-primary" style="height: 36px; line-height: 34px;">
                <?php esc_html_e('Filter', 'wahra-rentals-bookings'); ?>
            </button>
            <?php if ($has_active_filters): ?>
                <a href="<?php echo esc_url($current_status ? add_query_arg('status', $current_status, $page_url) : $page_url); ?>" class="button" style="height: 36px; line-height: 34px;">
                    <?php esc_html_e('Reset', 'wahra-rentals-bookings'); ?>
                </a>
            <?php endif; ?>
        </div>
    </form>

    <?php if ($has_active_filters): ?>
    <div style="margin-top: 8px; font-size: 13px; color: #64748b;">
        <?php
        /* translators: %d: number of filtered results */
        printf(esc_html__('%d results with active filters.', 'wahra-rentals-bookings'), count($recent_bookings));
        ?>
    </div>
    <?php endif; ?>

    <!-- Export Button -->
    <div style="margin-top: 12px; display: flex; justify-content: flex-end;">
        <?php
        $csv_args = [];
        if ($current_status) {
            $csv_args['status'] = $current_status;
        }
        if ($filter_date_from) {
            $csv_args['date_from'] = $filter_date_from;
        }
        if ($filter_date_to) {
            $csv_args['date_to'] = $filter_date_to;
        }
        ?>
        <a href="<?php echo esc_url(WAHRB_CSV_Exporter::get_export_url($csv_args)); ?>" class="button" style="display: inline-flex; align-items: center; gap: 6px;">
            📥 <?php esc_html_e('Export CSV', 'wahra-rentals-bookings'); ?>
        </a>
    </div>

    <!-- Bookings table -->
    <div class="wahrb-bookings-table" style="background: #fff; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); overflow: hidden; margin-top: 10px;">
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th style="width: 100px;"><?php esc_html_e('No.', 'wahra-rentals-bookings'); ?></th>
                    <th><?php esc_html_e('Product', 'wahra-rentals-bookings'); ?></th>
                    <th><?php esc_html_e('Customer', 'wahra-rentals-bookings'); ?></th>
                    <th><?php esc_html_e('Vendor', 'wahra-rentals-bookings'); ?></th>
                    <th><?php esc_html_e('Dates', 'wahra-rentals-bookings'); ?></th>
                    <th><?php esc_html_e('Amount', 'wahra-rentals-bookings'); ?></th>
                    <th style="width: 100px;"><?php esc_html_e('Status', 'wahra-rentals-bookings'); ?></th>
                    <th style="width: 80px;"><?php esc_html_e('Actions', 'wahra-rentals-bookings'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($recent_bookings)): ?>
                    <tr>
                        <td colspan="8" style="text-align: center; padding: 40px;">
                            <?php esc_html_e('No bookings in this category.', 'wahra-rentals-bookings'); ?>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($recent_bookings as $booking): ?>
                        <tr>
                            <td>
                                <strong>#<?php echo esc_html($booking['booking_number']); ?></strong>
                            </td>
                            <td><?php echo esc_html($booking['product_name'] ?: 'Product #' . $booking['product_id']); ?></td>
                            <td>
                                <?php echo esc_html($booking['customer_name']); ?><br>
                                <small style="color: #666;"><?php echo esc_html($booking['customer_email']); ?></small>
                            </td>
                            <td><?php echo esc_html($booking['vendor_name'] ?: 'Vendor #' . $booking['vendor_id']); ?></td>
                            <td>
                                <?php
                                echo esc_html(date_i18n('d/m/Y', strtotime($booking['start_dt'])));
                                echo ' &rarr; '; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe HTML entity
                                echo esc_html(date_i18n('d/m/Y', strtotime($booking['end_dt'])));
                                ?>
                            </td>
                            <td>
                                <?php echo wp_kses_post(wc_price($booking['total_amount'] ?? 0)); ?>
                            </td>
                            <td>
                                <?php
                                $status_colors = [
                                    'pending' => '#ed6c02',
                                    'confirmed' => '#2e7d32',
                                    'checked_in' => '#1976d2',
                                    'checked_out' => '#9c27b0',
                                    'completed' => '#388e3c',
                                    'cancelled' => '#d32f2f',
                                    'refunded' => '#757575',
                                ];
                                $status = $booking['status'];
                                $color = $status_colors[$status] ?? '#666';
                                $label = $status_labels[$status] ?? ucfirst($status);
                                ?>
                                <span style="
                                    display: inline-block;
                                    padding: 3px 8px;
                                    border-radius: 4px;
                                    background: <?php echo esc_attr($color); ?>;
                                    color: #fff;
                                    font-size: 0.85em;
                                ">
                                    <?php echo esc_html($label); ?>
                                </span>
                            </td>
                            <td>
                                <a href="<?php echo esc_url(wahrb_get_admin_dashboard_url('booking-detail', ['booking_id' => $booking['booking_id']])); ?>"
                                   class="button"
                                   title="<?php esc_attr_e('View details', 'wahra-rentals-bookings'); ?>"
                                   style="padding: 2px 8px; text-decoration: none;">
                                    👁
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
