<?php
if (!defined('ABSPATH')) exit;
// ---------------------------
// Helpers
// ---------------------------

/**
 * Get stores array
 * Each store: ['id'=>'galway', 'name'=>'Galway', 'url_key'=>'galway']
 */
function cutqueue_booking_system_get_stores() {
    $stores = get_option('cutqueue_booking_system_stores', []);
    if (!is_array($stores)) $stores = [];
    return $stores;
}

/**
 * Build option name for a store
 *
 * Normalise store id so the saved option keys always use the form:
 *   {base}_{store_xxx}
 *
 * This makes admin (which uses store IDs like "galway") and frontend
 * (which may detect "store_galway") consistent.
 */
function cutqueue_booking_system_opt($key_base, $store_id) {
    // Normalise store id to always start with "store_"
    if (strpos($store_id, 'store_') !== 0) {
        $store_id = 'store_' . $store_id;
    }
    return $key_base . '_' . $store_id;
}

function cutqueue_booking_system_sanitize_payment_mode( $value ) {

    $allowed = array(
        'disabled',
        'online',
        'in_person',
    );

    return in_array( $value, $allowed, true )
        ? $value
        : 'disabled'; // safe default
}

function cutqueue_booking_system_sanitize_stripe_key( $value ) {
    return sanitize_text_field( $value );
}

/**
 * Output store switcher UI (used on admin pages)
 */
function cutqueue_booking_system_store_switcher_html($current_store) {
    $stores = cutqueue_booking_system_get_stores();

    // ALWAYS keep page (required for admin routing)
    $page = isset($_GET['page'])
        ? sanitize_key( wp_unslash($_GET['page']) )
        : '';

    // Handle store switching securely

    // Generate fresh nonce for form
    $nonce = wp_create_nonce('cutqueue_booking_system_store_switch');

    echo '
    <div class="cutqueue_booking_system-store-switcher bg-dark border border-secondary rounded-3 p-3 mb-3 shadow-sm">
        <form method="get" class="d-flex flex-wrap justify-content-end align-items-center gap-2 m-0">
    ';

    echo '<input type="hidden" name="page" value="' . esc_attr($page) . '">';
    echo '<input type="hidden" name="cutqueue_booking_system_store_nonce" value="' . esc_attr($nonce) . '">';

    echo '
        <label class="text-light fw-semibold mb-0">Editing Store:</label>

        <select id="cutqueue-store-select"
                name="cutqueue_booking_system_store"
                class="form-select form-select-sm bg-secondary text-light border-0 shadow-sm"
                style="max-width:200px;">
    ';

    if (!empty($stores)) {
        foreach ($stores as $s) {
            echo '<option value="' . esc_attr($s['id']) . '" ' .
                selected($s['id'], $current_store, false) . '>' .
                esc_html($s['name']) .
                '</option>';
        }
    } else {
        echo '<option value="store_default">Default</option>';
    }

    echo '
        </select>

        <button type="submit" class="btn btn-warning btn-sm shadow-sm px-2">
            <i class="bi bi-arrow-repeat"></i> Switch
        </button>

        <a href="' . esc_url(admin_url('admin.php?page=cutqueue_booking_system-stores')) . '" 
           class="btn btn-info btn-sm shadow-sm px-2">
            <i class="bi bi-gear"></i> Manage Stores
        </a>
        </form>
    </div>';
}

function cutqueue_booking_system_handle_store_switch() {

    if ( ! is_admin() ) {
        return;
    }

    if ( ! isset( $_GET['cutqueue_booking_system_store'] ) ) {
        return;
    }

    // Capability check
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'You do not have permission to do this.', 'cutqueue' ) );
    }

    // Nonce check
    if (
        ! isset( $_GET['cutqueue_booking_system_store_nonce'] ) ||
        ! wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_GET['cutqueue_booking_system_store_nonce'] ) ),
            'cutqueue_booking_system_store_switch'
        )
    ) {
        wp_die( esc_html__( 'Security check failed.', 'cutqueue' ) );
    }

    $new_store = sanitize_text_field( wp_unslash( $_GET['cutqueue_booking_system_store'] ) );

    update_user_meta(
        get_current_user_id(),
        'cutqueue_current_store',
        $new_store
    );

    return $new_store;
}
add_action( 'admin_init', 'cutqueue_booking_system_handle_store_switch' );


// ---------------------------
// Admin Menu
// ---------------------------
function cutqueue_booking_system_admin_menu() {
    add_menu_page('Barber Bookings','CutQueue','manage_cutqueue','cutqueues','cutqueue_booking_system_booking_admin_page','dashicons-calendar-alt');
    
    add_submenu_page(
        'cutqueues',
        'Bookings',
        'Bookings',
        'manage_cutqueue',
        'cutqueues',
        'cutqueue_booking_system_booking_admin_page'
    );

    add_submenu_page(
        'cutqueues',
        'Stores',
        'Stores',
        'manage_cutqueue',
        'cutqueue_booking_system-stores',
        'cutqueue_booking_system_stores_page'
    );

    add_submenu_page(
        'cutqueues',
        'Services',
        'Services',
        'manage_cutqueue',
        'cutqueue_booking_system-services',
        'cutqueue_booking_system_services_page'
    );

    add_submenu_page(
        'cutqueues',
        'Opening Hours',
        'Opening Hours',
        'manage_cutqueue',
        'cutqueue_booking_system-opening-hours',
        'cutqueue_booking_system_opening_hours_page'
    );

    add_submenu_page(
        'cutqueues',
        'Employees',
        'Employees',
        'manage_cutqueue',
        'cutqueue_booking_system-workers-schedule',
        'cutqueue_booking_system_workers_page'
    );

    add_submenu_page(
        'cutqueues',
        'Payment Settings',
        'Payment Settings',
        'manage_cutqueue',
        'cutqueue_booking_system_payment_settings',
        'cutqueue_booking_system_payment_settings_page'
    );

    add_submenu_page(
        'cutqueues',
        'Notification Settings',
        'Notification Settings',
        'manage_cutqueue',
        'cutqueue_booking_system_notification_settings',
        'cutqueue_booking_system_notification_settings_page'
    );
}

function cutqueue_booking_system_add_caps_to_admin() {
    $role = get_role('administrator');
    if ($role && !$role->has_cap('manage_cutqueue')) {
        $role->add_cap('manage_cutqueue');
    }
}
add_action('admin_init', 'cutqueue_booking_system_add_caps_to_admin');

add_action('admin_init', function() {
    $store_id = cutqueue_detect_store_id();

    register_setting("cutqueue_booking_system_payment_settings_group_{$store_id}", "cutqueue_booking_system_payment_mode_{$store_id}",
    [
        'type'              => 'string',
        'sanitize_callback' => 'cutqueue_booking_system_sanitize_payment_mode',
    ]);
    
    register_setting("cutqueue_booking_system_payment_settings_group_{$store_id}", "cutqueue_booking_system_stripe_public_key_{$store_id}",
    [
        'type'              => 'string',
        'sanitize_callback' => 'cutqueue_booking_system_sanitize_stripe_key',
    ]);

    register_setting("cutqueue_booking_system_payment_settings_group_{$store_id}", "cutqueue_booking_system_stripe_secret_key_{$store_id}",
    [
        'type'              => 'string',
        'sanitize_callback' => 'cutqueue_booking_system_sanitize_stripe_key',
    ]);
});

add_action('admin_menu','cutqueue_booking_system_admin_menu');

add_action('admin_enqueue_scripts', function ($hook) {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

    $allowed_pages = [
        'cutqueues',
        'cutqueue_booking_system-stores',
        'cutqueue_booking_system-services',
        'cutqueue_booking_system-opening-hours',
        'cutqueue_booking_system-workers-schedule',
        'cutqueue_booking_system_payment_settings',
        'cutqueue_booking_system_notification_settings',
    ];

    if (in_array($page, $allowed_pages, true)) {

        wp_enqueue_style(
            'cutqueue_booking_system-bootstrap',
            plugin_dir_url(dirname(__FILE__)) . 'assets/css/bootstrap.min.css',
            [],
            '5.3.8'
        );

        wp_enqueue_style(
            'cutqueue_booking_system-admin-css',
            plugin_dir_url(dirname(__FILE__)) . 'assets/css/admin.css',
            [],
            '1.0.0'
        );

        wp_enqueue_script(
            'cutqueue_booking_system-bootstrap-js',
            plugin_dir_url(dirname(__FILE__)) . 'assets/js/bootstrap.bundle.min.js',
            [],
            '5.3.8',
            true
        );

        wp_enqueue_script(
            'cutqueue_booking_system-admin-js',
            plugin_dir_url(dirname(__FILE__)) . 'assets/js/admin.js',
            [],
            '1.0.0',
            true
        );
    }
});

function cutqueue_booking_system_sanitize_array($input) {
    if (is_array($input)) {
        return array_map('sanitize_text_field', $input);
    }
    return sanitize_text_field($input);
}

// ---------------------------
// Admin: All Bookings
// ---------------------------
function cutqueue_booking_system_booking_admin_page() {
    $current_store = '';
    $current_store = get_user_meta(get_current_user_id(), 'cutqueue_current_store', true);

    /* ========= GET STORE TIMEZONE ========= */
    $stores = get_option('cutqueue_booking_system_stores', []); // literal option name
    if (!is_array($stores)) $stores = [];

    $store_timezone = 'UTC'; // default
    foreach ($stores as $store) {
        if (($store['id'] ?? '') === $current_store) {
            $store_timezone = $store['timezone'] ?? 'UTC';
            break;
        }
    }

    // Load store-scoped data
    $bookings = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_bookings', $current_store), []);
    if (!is_array($bookings)) $bookings = [];
    $workers  = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_workers', $current_store), []);

    $notice = ''; // message to show after deletes

    /* ========= AUTO-CLEAN OLD BOOKINGS ========= */
    $dt_now = new DateTime('now', new DateTimeZone($store_timezone));
    $now_timestamp = $dt_now->getTimestamp();

    $changed = false;
    foreach ($bookings as $key => $b) {
        if (!empty($b['date'])) {
            // Default time to 00:00 if not set
            $time_part = !empty($b['time']) ? $b['time'] : '00:00';

            // Combine date and time
            $booking_dt = DateTime::createFromFormat(
                'Y-m-d H:i',
                $b['date'] . ' ' . $time_part,
                new DateTimeZone($store_timezone)
            );

            // If date is invalid, skip this booking
            if (!$booking_dt) continue;
            $booking_timestamp = $booking_dt->getTimestamp();
            $diff = $booking_timestamp - $now_timestamp;

            // Remove bookings older than 3 days
            if ($booking_timestamp < ($now_timestamp - 3 * 86400)) {
                unset($bookings[$key]);
                $changed = true;
            }

            if($diff > 0 && $diff <= 30*60){
                if (empty($b['status']) || strtolower($b['status']) !== 'cancelled') {
                    $notice = "🔔 Reminder: " . $b['name'] . " has an appointment scheduled ⏰ in the next 30 minutes. 🔔";
                }
            }
        }
    }

    // Save updated bookings if any were removed
    if ($changed) {
        update_option(cutqueue_booking_system_opt('cutqueue_booking_system_bookings', $current_store), $bookings);
    }

    /* ========= HANDLE CANCEL BOOKING ========= */
    $nonce = isset($_GET['_wpnonce'])
        ? sanitize_text_field( wp_unslash($_GET['_wpnonce']) )
        : '';

    $cancel_index = isset($_GET['cutqueue_booking_system_cancel_booking'])
        ? absint($_GET['cutqueue_booking_system_cancel_booking'])
        : 0;

    if ($cancel_index && wp_verify_nonce($nonce, 'cutqueue_booking_system_cancel_booking_nonce')) {
        if (isset($bookings[$cancel_index])) {
            $bookings[$cancel_index]['status'] = 'Cancelled';
            update_option(cutqueue_booking_system_opt('cutqueue_booking_system_bookings', $current_store), $bookings);

            // Send cancellation email
            $email = $bookings[$cancel_index]['email'] ?? '';
            $name  = $bookings[$cancel_index]['name'] ?? '';
            $date  = $bookings[$cancel_index]['date'] ?? '';
            $time  = $bookings[$cancel_index]['time'] ?? '';
            $service = $bookings[$cancel_index]['service'] ?? '';

            if (!empty($email)) {
                $subject = "Your Appointment Has Been Cancelled";
                $message = "Hello $name,\n\nWe regret to inform you that your appointment on $date at $time for '$service' has been cancelled.\n\nIf you have any questions, please contact us.\n\nThank you.";
                wp_mail($email, $subject, $message);
            }
            $notice = 'Appointment cancelled and customer notified.';
        } else {
            $notice = 'Booking not found.';
        }

        // clear GET vars
        unset($_GET['cutqueue_booking_system_cancel_booking'], $_GET['_wpnonce']);
        $bookings = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_bookings', $current_store), []);
        if (!is_array($bookings)) $bookings = [];
    }

    /* ========= HANDLE SINGLE DELETE (no redirect) ========= */
    $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
    $delete_index = isset($_GET['cutqueue_booking_system_delete_booking']) ? intval(wp_unslash($_GET['cutqueue_booking_system_delete_booking'])) : 0;

    if ($delete_index && wp_verify_nonce($nonce, 'cutqueue_booking_system_delete_booking_nonce')) {
        $delete_index = intval($_GET['cutqueue_booking_system_delete_booking']);
        if (isset($bookings[$delete_index])) {
            unset($bookings[$delete_index]);
            update_option(cutqueue_booking_system_opt('cutqueue_booking_system_bookings', $current_store), $bookings);
            $notice = 'Booking deleted.';
        } else {
            $notice = 'Booking not found.';
        }
        // clear GET so we don't attempt to delete again if user refreshes
        unset($_GET['cutqueue_booking_system_delete_booking'], $_GET['_wpnonce']);
        // reload bookings after deletion
        $bookings = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_bookings', $current_store), []);
        if (!is_array($bookings)) $bookings = [];
    }

    /* ========= FILTER (initial values or from GET) ========= */
    $selected_day = isset($_GET['filter_day']) ? sanitize_text_field(wp_unslash($_GET['filter_day'])) : 'upcoming';

    $selected_worker = isset($_GET['filter_worker']) ? sanitize_text_field(wp_unslash($_GET['filter_worker'])) : '';

    /* ========= HANDLE MULTI DELETE (no redirect) ========= */
    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cutqueue_booking_system_delete_selected'])) {
        if (check_admin_referer('cutqueue_booking_system_delete_selected_nonce')) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $selected_bookings = isset($_POST['cutqueue_booking_system_selected_bookings']) ? wp_unslash($_POST['cutqueue_booking_system_selected_bookings']) : [];
            $to_delete_rows = array_map('intval', (array) $selected_bookings); // ensure numeric keys

            $deleted_count = 0;
            if ($to_delete_rows && is_array($to_delete_rows)) {
                foreach ($to_delete_rows as $row) {
                    // We expect checkbox value to be the original booking key
                    $key = intval($row);
                    if (isset($bookings[$key])) {
                        unset($bookings[$key]);
                        $deleted_count++;
                    }
                }
                if ($deleted_count > 0) {
                    update_option(cutqueue_booking_system_opt('cutqueue_booking_system_bookings', $current_store), $bookings);
                    $notice = $deleted_count . ' booking' . ($deleted_count > 1 ? 's' : '') . ' deleted.';
                } else {
                    $notice = 'No bookings deleted.';
                }
            } else {
                $notice = 'No bookings selected.';
            }
            // reload bookings after deletion
            $bookings = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_bookings', $current_store), []);
            if (!is_array($bookings)) $bookings = [];
            // preserve selected filters from POST/GET (we'll continue rendering with them)
            $selected_day = isset($_GET['filter_day']) ? sanitize_text_field(wp_unslash($_GET['filter_day'])) : $selected_day;
            $selected_worker = isset($_GET['filter_worker']) ? sanitize_text_field(wp_unslash($_GET['filter_worker'])) : $selected_worker;
        } else {
            $notice = 'Security check failed.';
        }
    }

    /* ========= FILTER BOOKINGS (preserve keys) ========= */
    $filtered_bookings = [];
    $dt_now = new DateTime('now', new DateTimeZone($store_timezone));
    $now_timestamp = $dt_now->getTimestamp();

    foreach ($bookings as $key => $b) {
        $date = $b['date'] ?? '';
        $time = $b['time'] ?? '00:00';
        
        // Make sure date exists
        if (!$date) continue;

        $booking_dt = DateTime::createFromFormat('Y-m-d H:i', $date . ' ' . $time, new DateTimeZone($store_timezone));
        if (!$booking_dt) continue; // skip invalid dates

        $booking_timestamp = $booking_dt->getTimestamp();

        // Filter by day range
        if ($selected_day === 'upcoming' && $booking_timestamp < $now_timestamp) continue;
        if ($selected_day === 'past' && $booking_timestamp >= $now_timestamp) continue;

        // Filter by worker
        if ($selected_worker && ($b['worker'] ?? '') !== $selected_worker) continue;

        // Keep booking
        $filtered_bookings[$key] = $b;
    }

    /* ========= PAGINATION ========= */
    $per_page = 10;
    $total_items = count($filtered_bookings);
    $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
    $total_pages = max(1, ceil($total_items / $per_page));

    // ensure current page isn't out of range after deletions
    if ($current_page > $total_pages) $current_page = $total_pages;

    $paged_bookings = array_slice($filtered_bookings, ($current_page - 1) * $per_page, $per_page, true);

    /* ========= OUTPUT ========= */
    echo '<div style="max-width: 100%; padding: 20px;">';
    echo '<div class="bg-dark text-light shadow-lg rounded-4 p-4 w-100">';
    echo '<h1 class="mb-4 text-warning"><i class="bi bi-calendar2-check"></i> All Bookings</h1>';

    cutqueue_booking_system_store_switcher_html($current_store);

    // show notice if any
    if ($notice) {
        echo '<div class="updated notice text-danger" style="margin-bottom:12px;"><p>' . esc_html($notice) . '</p></div>';
    }

    // ===== Filters =====
    echo '<div class="d-flex flex-wrap justify-content-start align-items-center mb-4 gap-3">';
    echo '<form method="get" class="d-flex flex-wrap gap-3 align-items-end m-0 w-100">';
    echo '<input type="hidden" name="page" value="cutqueues">';
    echo '<input type="hidden" name="cutqueue_booking_system_store" value="' . esc_attr($current_store) . '">';

    $selectStyle = 'min-width:220px; width:100%; max-width:250px;';

    // Appointment Range
    echo '<div class="d-flex flex-column flex-sm-row align-items-start align-items-sm-end gap-2 flex-grow-1 flex-md-grow-0" style="min-width:250px;">';
    echo '<label for="filter_day" class="mb-0 text-nowrap">Appointment Range:</label>';
    echo '<select id="filter_day" name="filter_day" class="form-select form-select-sm bg-dark text-light border-secondary" style="' . esc_attr($selectStyle) . '">';
    echo '<option value="' . esc_attr('upcoming') . '" ' . selected($selected_day, 'upcoming', false) . '>Upcoming Appointments</option>';
    echo '<option value="' . esc_attr('past') . '" ' . selected($selected_day, 'past', false) . '>Past Appointments</option>';
    echo '</select>';
    echo '</div>';

    // Worker
    echo '<div class="d-flex flex-column flex-sm-row align-items-start align-items-sm-end gap-2 flex-grow-1 flex-md-grow-0" style="min-width:250px;">';
    echo '<label for="filter_worker" class="mb-0 text-nowrap">Worker:</label>';
    echo '<select id="filter_worker" name="filter_worker" class="form-select form-select-sm bg-dark text-light border-secondary" style="' . esc_attr($selectStyle) . '">';
    echo '<option value="">All</option>';
    foreach ($workers as $w) {
        $wname = $w['name'] ?? '';
        echo '<option value="' . esc_attr($wname) . '" ' . selected($selected_worker, $wname, false) . '>' . esc_html($wname) . '</option>';
    }
    echo '</select>';
    echo '</div>';

    // Filter Button
    echo '<button type="submit" style="margin-left: 5px;" class="btn btn-warning btn-sm shadow-sm px-3"><i class="bi bi-funnel me-1"></i> Filter</button>';
    echo '</form></div>';

    /* ========= TABLE / MOBILE ========= */
    if ($paged_bookings) {
        echo '<form method="post" id="cutqueue_booking_system-delete-form">';
        wp_nonce_field('cutqueue_booking_system_delete_selected_nonce');

        // Desktop table
        echo '<div class="table-responsive d-none d-md-block">';
        echo '<table class="table table-dark table-hover align-middle mb-0 rounded-3 overflow-hidden" style="width:100%;">';
        echo '<thead class="table-warning text-dark"><tr>
                <th><input type="checkbox" id="cutqueue_booking_system_select_all"></th>
                <th>Date & Time</th>
                <th>Name</th>
                <th>Email</th>
                <th>Mobile</th>
                <th>Service</th>
                <th>Duration</th>
                <th>Worker</th>
                <th>Status</th>
                <th>Action</th>
              </tr></thead><tbody>';

        // IMPORTANT: checkbox value is original booking key
        foreach ($paged_bookings as $orig_key => $b) {
            $status = $b['status'] ?? 'Active';
            $status_class = $status === 'Cancelled' ? 'bg-danger text-dark' : 'bg-success text-dark';
            $cancel_url = wp_nonce_url(add_query_arg(['cutqueue_booking_system_cancel_booking' => $orig_key]), 'cutqueue_booking_system_cancel_booking_nonce');

            echo '<tr class="border-secondary">';
            echo '<td><input type="checkbox" name="cutqueue_booking_system_selected_bookings[]" value="' . intval($orig_key) . '"></td>';
            echo '<td><i class="bi bi-calendar3"></i> ' . esc_html(($b['date'] ?? '') . ' ' . ($b['time'] ?? '')) . '</td>';
            echo '<td>' . esc_html($b['name'] ?? '') . '</td>';
            echo '<td>' . esc_html($b['email'] ?? '') . '</td>';
            echo '<td>' . esc_html($b['mobile'] ?? '') . '</td>';
            echo '<td><span class="badge bg-info text-dark">' . esc_html($b['service'] ?? '') . '</span></td>';
            echo '<td><span class="badge bg-warning text-dark">' . intval($b['duration'] ?? 0) . ' min</span></td>';
            echo '<td><span class="badge bg-light text-dark">' . esc_html($b['worker'] ?? '') . '</span></td>';
            echo '<td><span class="badge ' . esc_attr($status_class) . '">' . esc_html($status) . '</span></td>';
            
            // Cancel button only if not already cancelled
            echo '<td>';
            if ($status !== 'Cancelled') {
                echo '<a href="' . esc_url($cancel_url) . '" class="badge bg-danger text-dark" onclick="return confirm(\'Cancel this booking?\');">
                        Cancel
                    </a>';
            } else {
                echo '<i class="text-muted">—</i>';
            }
            echo '</td>';                 
            echo '</tr>';
        }

        echo '</tbody></table></div>';
        echo '</form>';

        // Mobile cards
        echo '<div class="d-md-none">';
        foreach ($paged_bookings as $orig_key => $b) {
            $status = $b['status'] ?? 'Active';
            $status_class = $status === 'Cancelled' ? 'bg-danger text-dark me-1' : 'bg-success text-dark me-1';
            $cancel_url = wp_nonce_url(add_query_arg(['cutqueue_booking_system_cancel_booking' => $orig_key]), 'cutqueue_booking_system_cancel_booking_nonce');

            echo '<div class="p-3 mb-3 rounded-4 shadow-sm" style="background: linear-gradient(145deg, #1e1e1e, #2a2a2a); border: 1px solid #333;">';
            echo '<div class="d-flex justify-content-between align-items-center mb-2">';
            echo '<h5 class="mb-0 text-warning">' . esc_html($b['name'] ?? '') . '</h5>';
            echo '<input type="checkbox" name="cutqueue_booking_system_selected_bookings[]" value="' . intval($orig_key) . '">';
            echo '</div>';
            echo '<p class="mb-1"><i class="bi bi-calendar3 text-warning"></i> ' . esc_html(($b['date'] ?? '') . ' ' . ($b['time'] ?? '')) . '</p>';
            echo '<p class="mb-1"><i class="bi bi-envelope text-info"></i> ' . esc_html($b['email'] ?? '') . '</p>';
            echo '<p class="mb-1"><i class="bi bi-telephone text-success"></i> ' . esc_html($b['mobile'] ?? '') . '</p>';
            echo '<div class="mt-2">';
            echo '<span class="badge bg-info text-dark me-1">' . esc_html($b['service'] ?? '') . '</span>';
            echo '<span class="badge bg-warning text-dark me-1">' . intval($b['duration'] ?? 0) . ' min</span>';
            echo '<span class="badge bg-light text-black me-1">' . esc_html($b['worker'] ?? '') . '</span>';
            echo '<span class="badge ' . esc_attr($status_class) . '">' . esc_html($status) . '</span>';
            echo '</div>';

            if ($status !== 'Cancelled') {
                echo '<div class="mt-3">';
                echo '<a href="' . esc_url($cancel_url) . '" class="btn btn-sm btn-danger w-100 text-dark" onclick="return confirm(\'Cancel this booking?\');">
                        <i class="bi bi-x-circle"></i> Cancel
                    </a>';
                echo '</div>';
            }

            echo '</div>';
        }
        echo '</div>';
    } else {
        echo '<p class="text-danger fs-5">No bookings yet.</p>';
    }

    // Pagination
    if ($total_pages > 1) {
        echo '<nav><ul class="pagination pagination-sm justify-content-center mt-3">';
        for ($p = 1; $p <= $total_pages; $p++) {
            $active = ($p == $current_page) ? 'active' : '';
            $filters = [
                'cutqueue_booking_system_search' => isset($_GET['cutqueue_booking_system_search']) ? sanitize_text_field( wp_unslash($_GET['cutqueue_booking_system_search']) ) : '',
                'paged'     => $p,
            ];

            $url = add_query_arg($filters);
            echo '<li class="page-item ' . esc_attr($active) . '"><a class="page-link bg-dark text-warning border-secondary" href="' . esc_url($url) . '">' . esc_attr($p) . '</a></li>';
        }
        echo '</ul></nav>';
    }

    echo '
        <button id="cutqueue_booking_system-float-delete" type="submit" form="cutqueue_booking_system-delete-form" name="cutqueue_booking_system_delete_selected" onclick="return confirm(\'Delete selected bookings?\');">
        <i class="bi bi-trash3"></i> Delete Selected
        </button>
    ';

    echo '</div></div>'; ?>

<?php
}

// ---------------------------
// Admin: Services (store-scoped)
// ---------------------------
function cutqueue_booking_system_services_page(){
    $current_store = get_user_meta(get_current_user_id(), 'cutqueue_current_store', true);

    $services = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_services', $current_store), []);
    if (!is_array($services)) $services = [];

    $nonce = isset($_GET['_wpnonce'])
        ? sanitize_text_field( wp_unslash($_GET['_wpnonce']) )
        : '';

    $del_service = isset($_GET['cutqueue_booking_system_delete_service'])
        ? sanitize_text_field( wp_unslash($_GET['cutqueue_booking_system_delete_service']) )
        : '';

    if ( $nonce && wp_verify_nonce($nonce, 'cutqueue_booking_system_delete_service_nonce') && $del_service ) {

        foreach ($services as $k => $s) {
            if (($s['name'] ?? '') === $del_service) {
                unset($services[$k]);
                update_option(cutqueue_booking_system_opt('cutqueue_booking_system_services', $current_store), array_values($services));
                echo '<div class="updated notice"><p>Service deleted.</p></div>';
                break;
            }
        }
    }

    // save
    if (isset($_POST['cutqueue_booking_system_save_service'])) {
        check_admin_referer('cutqueue_booking_system_services_nonce','cutqueue_booking_system_services_nonce_field');
        $name = isset($_POST['service_name']) ? sanitize_text_field(wp_unslash($_POST['service_name'])) : '';
        $duration = isset($_POST['service_duration']) ? intval(wp_unslash($_POST['service_duration'])) : 0;
        $price = isset($_POST['service_price']) ? intval(wp_unslash($_POST['service_price'])) : 0;

        $exists = false;
        foreach ($services as $s) {
            if (strtolower($s['name']) === strtolower($name)) $exists = true;
        }

        if (!$exists) {
            $services[] = ['name' => $name, 'duration' => $duration, 'price' => $price];
            update_option(cutqueue_booking_system_opt('cutqueue_booking_system_services', $current_store), $services);
            echo '<div class="updated notice"><p>Service added.</p></div>';
        } else {
            echo '<div class="error notice"><p>Service exists.</p></div>';
        }
    }

    echo '<div class="container"><div class="pt-4"><h1>Services</h1></div>';
    cutqueue_booking_system_store_switcher_html($current_store);
    ?>
    <form method="post"><?php wp_nonce_field('cutqueue_booking_system_services_nonce','cutqueue_booking_system_services_nonce_field'); ?>
    <div class="form-row">
        <div class="form-group col-md-3">
            <label for="servicename"><b>Name</b></label>
            <input type="text" id="servicename" name="service_name" class="form-control" placeholder="Enter service name" required>
        </div>
        <div class="form-group col-md-3">
            <label for="serviceduration"><b>Duration (min)</b></label>
            <input class="form-control" type="number" id="serviceduration" name="service_duration" min="5" max="180" value="30" required>            
        </div>
        <div class="form-group col-md-3">
            <label for="serviceprice"><b>Price</b></label>
            <input class="form-control" type="number" id="serviceprice" name="service_price" step="0.01" max="180" value="10" required>            
        </div>
    </div>
    <div class="py-2">
        <button type="submit" name="cutqueue_booking_system_save_service" class="btn btn-success btn-sm">
        Add Service
        </button>
    </div>
    </form>

    <h3>Existing Services</h3>
    <?php if($services): ?>
    <table class="table table-dark table-hover align-middle mb-0 rounded-3 overflow-hidden" style="width:100%;">
    <thead class="table-warning text-dark">
        <tr>
        <th scope="col">Name</th>
        <th scope="col">Duration</th>
        <th scope="col">Price</th>
        <th scope="col" class="text-end">Actions</th>
        </tr>
    </thead>
    <tbody id="services-table-body">
        <?php foreach ($services as $index => $s): ?>
        <tr data-index="<?php echo esc_attr($index); ?>">
            <td class="service-name"><?php echo esc_html($s['name'] ?? ''); ?></td>
            <td class="service-duration"><?php echo intval($s['duration'] ?? 0); ?></td>
            <td class="service-price"><?php echo intval($s['price'] ?? 0); ?></td>
            <td class="text-end">
                <button class="btn btn-sm btn-warning me-2 edit-service px-3">Edit</button>
                <a href="<?php echo esc_url(
                    wp_nonce_url(
                        add_query_arg([
                            'cutqueue_booking_system_delete_service' => $s['name'] ?? '',
                            'cutqueue_booking_system_store' => $current_store ?? ''
                        ]),
                        'cutqueue_booking_system_delete_service_nonce'
                    )
                ); ?>"
                class="btn btn-sm btn-danger me-2 edit-service px-2"
                onclick="return confirm('Delete this service?');">
                    Delete
                </a>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
    </table>
    <?php else: ?><p>No services yet for this store.</p><?php endif; ?>

    </div>
    <?php

    wp_localize_script('cutqueue_booking_system-admin-js', 'cutqueue_booking_system_formData', array(
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('cutqueue_booking_system_admin_nonce'),
        'store' => $current_store,
    ));
}

add_action('wp_ajax_cutqueue_booking_system_update_service', function() {
    check_ajax_referer('cutqueue_booking_system_admin_nonce', 'cutqueue_booking_system_nonce');

    // Ensure the POST indexes exist and unslash them before sanitization
    $index   = isset($_POST['index']) ? intval(wp_unslash($_POST['index'])) : 0;
    $name    = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
    $duration = isset($_POST['duration']) ? intval(wp_unslash($_POST['duration'])) : 0;
    $price   = isset($_POST['price']) ? intval(wp_unslash($_POST['price'])) : 0;
  
    $current_store = get_user_meta(get_current_user_id(), 'cutqueue_current_store', true);

    $services = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_services', $current_store), []);
    if (!is_array($services)) $services = [];

    if (!isset($services[$index])) {
        wp_send_json_error("Service not found.");
    }

    $services[$index]['name'] = $name;
    $services[$index]['duration'] = $duration;
    $services[$index]['price'] = $price;

    update_option(cutqueue_booking_system_opt('cutqueue_booking_system_services', $current_store), $services);

    wp_send_json_success("Service updated successfully.");
});

// ---------------------------
// Admin: Workers (store-scoped)
// ---------------------------
function cutqueue_booking_system_workers_page(){
    $current_store = get_user_meta(get_current_user_id(), 'cutqueue_current_store', true);
    
    $workers = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_workers', $current_store), []);
    
    $disable_worker_select = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_disable_worker_select', $current_store), false);
    $slots_per_booking = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_slots_per_booking', $current_store), 1);

    // Save admin settings
    if (isset($_POST['cutqueue_booking_system_save_settings']) && check_admin_referer('cutqueue_booking_system_disable_worker_select_nonce')) {
        $disable_worker_select = !empty($_POST['cutqueue_booking_system_disable_worker_select']);
        $slots_per_booking = isset($_POST['cutqueue_booking_system_slots_per_booking']) ? intval($_POST['cutqueue_booking_system_slots_per_booking']) : 1;

        update_option(cutqueue_booking_system_opt('cutqueue_booking_system_disable_worker_select', $current_store), $disable_worker_select);
        update_option(cutqueue_booking_system_opt('cutqueue_booking_system_slots_per_booking', $current_store), $slots_per_booking);

        echo '<div class="updated notice"><p>Settings updated successfully.</p></div>';
    }
    
    if (!is_array($workers)) $workers = [];

    // days array used for initializing schedules
    $days_of_week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

    // delete
    if ( isset($_GET['cutqueue_booking_system_delete_worker'], $_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_GET['_wpnonce']) ), 'cutqueue_booking_system_delete_worker_nonce')) {
       $requested_store = isset($_GET['cutqueue_booking_system_store']) ? sanitize_text_field(wp_unslash($_GET['cutqueue_booking_system_store'])) : '';
        if ($requested_store !== $current_store) {
            wp_die('Invalid store context.');
        }
        
        $del = sanitize_text_field(wp_unslash($_GET['cutqueue_booking_system_delete_worker']));
        foreach($workers as $k=>$w){ 
            if($w['name']===$del){ 
                unset($workers[$k]); 
                update_option(cutqueue_booking_system_opt('cutqueue_booking_system_workers', $current_store), array_values($workers)); 
                echo '<div class="updated notice"><p>Worker deleted.</p></div>'; 
                break; 
            } 
        }
        // Refresh local variable after deletion
        $workers = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_workers', $current_store), []);
        if (!is_array($workers)) $workers = [];
    }

    // save (add employee)
    if (isset($_POST['cutqueue_booking_system_save_worker'])) {
        check_admin_referer('cutqueue_booking_system_workers_nonce','cutqueue_booking_system_workers_nonce_field');

        $name = isset($_POST['worker_name']) ? sanitize_text_field(wp_unslash($_POST['worker_name'])) : '';
        if ($name === '') {
            echo '<div class="error notice"><p>Please provide a name.</p></div>';
        } else {
            $exists = false;
            foreach ($workers as $w) {
                if (isset($w['name']) && strtolower($w['name']) === strtolower($name)) {
                    $exists = true;
                    break;
                }
            }

            if (!$exists) {
                // initialize default empty schedule for the worker
                $default_schedule = [];
                foreach ($days_of_week as $d) {
                    $default_schedule[$d] = ['enabled' => false, 'start' => '', 'end' => ''];
                }

                $workers[] = ['name' => $name, 'schedule' => $default_schedule];
                update_option(cutqueue_booking_system_opt('cutqueue_booking_system_workers', $current_store), $workers);

                // Refresh local variable so the rest of the page renders with the new worker
                $workers = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_workers', $current_store), []);
                if (!is_array($workers)) $workers = [];

                echo '<div class="updated notice"><p>Employee added successfully.</p></div>';
            } else {
                echo '<div class="error notice"><p>Worker exists.</p></div>';
            }
        }
    }

    echo '<div class="container"><div class="pt-4"><h1>Employees</h1></div>';
    cutqueue_booking_system_store_switcher_html($current_store);

    ?>
    <form method="post" class="mb-4">
    <?php wp_nonce_field('cutqueue_booking_system_disable_worker_select_nonce'); ?>
    <div style="background:#222;padding:15px;border-radius:8px;margin-bottom:10px;">
        <label style="display:flex;align-items:center;gap:10px;color:#fff;font-weight:600;">
            <input type="checkbox" name="cutqueue_booking_system_disable_worker_select" value="1" <?php checked($disable_worker_select); ?>>
            Disable worker selection in frontend
        </label>
        <div style="margin-top:10px;">
            <label style="color:#fff;">Number of slots per booking:</label>
            <input type="number" name="cutqueue_booking_system_slots_per_booking" value="<?php echo esc_attr($slots_per_booking); ?>" min="1" class="regular-text" style="width:80px;">
        </div>
        <p style="color:#bbb;margin-top:8px;">When enabled, all employees below are disabled and clients can only book "Any Available Worker".</p>
        <button type="submit" name="cutqueue_booking_system_save_settings" class="button button-primary">Save Settings</button>
    </div>
    </form>
    <?php  

    // show success notice if redirected after add (kept for compatibility if used)
    if (isset($_GET['added']) && $_GET['added'] === 'true') {
        echo '<div class="updated notice"><p>Employee added successfully.</p></div>';
        // small anchor for UX: scroll target if you want to jump down with JS
        echo '<a></a>';
    }

    if ($disable_worker_select) {
        echo '<div style="opacity:0.5;pointer-events:none;">';
    }

    ?>  
    <form method="post"><?php wp_nonce_field(
    'cutqueue_booking_system_workers_nonce',
    'cutqueue_booking_system_workers_nonce_field'
    ); ?>
    <div class="form-row">
        <div class="form-group col-md-3">
            <label for="workername"><b>Name</b></label>
            <input type="text" id="workername" name="worker_name" class="form-control" placeholder="Enter employee name" required>
        </div>
    </div>
    <div class="py-2">
        <button type="submit" name="cutqueue_booking_system_save_worker" class="btn btn-success btn-sm">
        Add Employee
        </button>
    </div>
    </form>
    <div class="pt-3">
        <h3>Existing Employees</h3>
    </div>
    <?php if($workers): ?>
    <table class="table table-dark table-hover align-middle mb-0 rounded-3 overflow-hidden" style="width:100%;">
        <thead class="table-warning text-dark">
            <tr>
                <th scope="col">Name</th>
                <th scope="col" class="text-end">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($workers as $w): ?>
                <tr>
                    <td><?php echo esc_html($w['name']); ?></td>
                    <td class="text-end">
                        <a href="<?php echo esc_url(
                            wp_nonce_url(
                                add_query_arg([
                                    'cutqueue_booking_system_delete_worker' => $w['name'] ?? '',
                                    'cutqueue_booking_system_store' => $current_store ?? ''
                                ]),
                                'cutqueue_booking_system_delete_worker_nonce'
                            )
                        ); ?>" 
                        class="btn btn-sm btn-danger"
                        onclick="return confirm('Delete this worker?');">
                            Delete
                        </a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php else: ?><p>No employees yet for this store.</p><?php endif; ?>
    <?php

    // Reload workers (ensure latest after operations)
    $workers = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_workers', $current_store), []);
    if (!is_array($workers)) $workers = [];

    if (isset($_POST['cutqueue_booking_system_save_schedule'])) {

        check_admin_referer('cutqueue_booking_system_worker_days_nonce');

        $worker_schedule = [];

        if (isset($_POST['worker_schedule']) && is_array($_POST['worker_schedule'])) {
            foreach ($worker_schedule as $name => $schedule_data) {
                $name = sanitize_text_field($name);

                $index = array_search($name, array_column($workers, 'name'), true);
                if ($index !== false) {
                    $schedule = [];
                    foreach ($days_of_week as $day) {
                        $start = sanitize_text_field($schedule_data[$day]['start'] ?? '');
                        $end   = sanitize_text_field($schedule_data[$day]['end'] ?? '');

                        $enabled = !empty($schedule_data[$day]['enabled']);

                        $schedule[$day] = [
                            'enabled' => $enabled,
                            'start'   => $start,
                            'end'     => $end,
                        ];
                    }
                    $workers[$index]['schedule'] = $schedule;
                }
            }
            update_option(
                cutqueue_booking_system_opt('cutqueue_booking_system_workers', $current_store),
                $workers
            );

            echo '<div class="updated notice"><p>Worker schedules updated for ' . esc_html($current_store) . '!</p></div>';
        }
    }

    echo '<div class="pt-4"><h3>Employee Schedule</h3></div>';
    ?>
    <form method="post"><?php wp_nonce_field('cutqueue_booking_system_worker_days_nonce'); ?>

    <div style="overflow-x:auto; width:100%; -webkit-overflow-scrolling:touch;">
        <table class="table table-dark table-hover align-middle mb-0 rounded-3 overflow-hidden" 
            style="min-width:900px; width:100%;">

        <thead class="table-warning text-dark">
            <tr>
                <th scope="col">Employee</th>
                <?php foreach ($days_of_week as $day): ?>
                    <th scope="col" class="text-center"><?php echo esc_html($day); ?></th>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($workers as $worker):
                // ensure schedule exists for each worker so the table always renders
                $schedule = $worker['schedule'] ?? [];
                if (!is_array($schedule)) $schedule = [];
            ?>
            <tr>
                <td><strong><?php echo esc_html($worker['name']); ?></strong></td>
                <?php foreach ($days_of_week as $day):
                    $day_data = $schedule[$day] ?? ['enabled' => false, 'start' => '', 'end' => ''];
                ?>
                <td class="text-center">
                    <div class="form-check mb-2 d-flex justify-content-center align-items-center gap-2">
                        <input 
                            type="checkbox" 
                            name="worker_schedule[<?php echo esc_attr($worker['name']); ?>][<?php echo esc_attr($day); ?>][enabled]" 
                            value="1" 
                            <?php checked(!empty($day_data['enabled'])); ?> >
                        <label class="form-check-label fw-semibold">
                            Day off
                        </label>
                    </div>
                    <div class="mb-2">
                        <input 
                            type="time" 
                            class="form-control form-control-sm text-center" 
                            name="worker_schedule[<?php echo esc_attr($worker['name']); ?>][<?php echo esc_attr($day); ?>][start]" 
                            value="<?php echo esc_attr($day_data['start']); ?>" 
                            style="max-width:100px; margin:auto;">
                    </div>
                    <div>
                        <input 
                            type="time" 
                            class="form-control form-control-sm text-center" 
                            name="worker_schedule[<?php echo esc_attr($worker['name']); ?>][<?php echo esc_attr($day); ?>][end]" 
                            value="<?php echo esc_attr($day_data['end']); ?>" 
                            style="max-width:100px; margin:auto;">
                    </div>
                </td>
                <?php endforeach; ?>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <div class="py-1">
        <button type="submit" name="cutqueue_booking_system_save_schedule" class="btn btn-success btn-sm">
        Save Schedule
        </button>
    </div>
    </form>
    <?php

        if ($disable_worker_select) {
        echo '</div>';
    }
}

// ---------------------------
// Admin: Opening Hours (store-scoped)
// ---------------------------
function cutqueue_booking_system_opening_hours_page(){
    $current_store = get_user_meta(get_current_user_id(), 'cutqueue_current_store', true);

    $days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
    $hours = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_opening_hours', $current_store), []);
    
    if (!is_array($hours)) $hours = [];

    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && check_admin_referer('cutqueue_booking_system_save_opening_hours')) {
        $new_hours = [];
        foreach($days as $d) {
            $new_hours[$d] = [
                'open'  => isset($_POST['open_' . $d])  ? sanitize_text_field(wp_unslash($_POST['open_' . $d]))  : '',
                'close' => isset($_POST['close_' . $d]) ? sanitize_text_field(wp_unslash($_POST['close_' . $d])) : '',
                'closed' => isset($_POST['closed_'.$d]) ? 1 : 0
            ];
        }
        update_option(cutqueue_booking_system_opt('cutqueue_booking_system_opening_hours', $current_store), $new_hours);
        $hours = $new_hours;
        echo '<div class="updated notice"><p>Opening hours saved' . '!</p></div>';
    }

    function cutqueue_hour_options_local($selected = '') {
        for ($h = 0; $h <= 23; $h++) {
            for ($m = 0; $m <= 45; $m += 15) {
                $val = sprintf('%02d:%02d', $h, $m);
                $sel = selected($selected, $val, false);
                echo '<option value="' . esc_attr($val) . '" ' . esc_attr($sel) . '>' . esc_html($val) . '</option>';
            }
        }
    }

    echo '<div class="container"><div class="pt-4"><h1>Opening Hours</h1></div>';
    cutqueue_booking_system_store_switcher_html($current_store);
    ?>
    <form method="post"><?php wp_nonce_field('cutqueue_booking_system_save_opening_hours'); ?>
    <table class="table table-dark table-hover align-middle mb-0 rounded-3 overflow-hidden" style="width:100%;">
        <thead class="table-warning text-dark">
            <tr>
                <th scope="col">Day</th>
                <th scope="col">Open</th>
                <th scope="col">Close</th>
                <th class="text-center" scope="col">Closed</th>
                <th class="text-center" scope="col">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($days as $day):
                $open = $hours[$day]['open'] ?? '';
                $close = $hours[$day]['close'] ?? '';
                $closed = !empty($hours[$day]['closed']);
            ?>
            <tr>
                <td><strong><?php echo esc_html($day); ?></strong></td>
                <td>
                    <select 
                        name="open_<?php echo esc_attr($day); ?>" 
                        class="form-select form-select-sm" 
                        <?php echo $closed ? 'disabled' : ''; ?>>
                        <?php cutqueue_hour_options_local($open); ?>
                    </select>
                </td>
                <td>
                    <select 
                        name="close_<?php echo esc_attr($day); ?>" 
                        class="form-select form-select-sm" 
                        <?php echo $closed ? 'disabled' : ''; ?>>
                        <?php cutqueue_hour_options_local($close); ?>
                    </select>
                </td>
                <td class="text-center">
                    <input 
                        type="checkbox" 
                        name="closed_<?php echo esc_attr($day); ?>" 
                        <?php checked($closed); ?> 
                        onchange="toggleRow(this)">
                </td>
                <td class="text-center">
                    <button 
                        type="button" 
                        class="btn btn-sm btn-primary"
                        onclick="copyHours('<?php echo esc_attr($day); ?>')">
                        Copy to Rest
                    </button>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <div class="py-1">
        <button type="submit" class="btn btn-success btn-sm">
        Save Hours
        </button>
    </div>
    </form>
    </div>
    <?php
}

// ---------------------------
// Admin: Stores management
// ---------------------------
function cutqueue_booking_system_stores_page() {
    $stores = cutqueue_booking_system_get_stores();
    $active_store = get_option('cutqueue_booking_system_active_store', '');

    // Handle delete
   if (isset($_GET['cutqueue_booking_system_delete_store'], $_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field( wp_unslash($_GET['_wpnonce']) ),'cutqueue_booking_system_delete_store_nonce')) {
        $delete_id = sanitize_text_field(wp_unslash($_GET['cutqueue_booking_system_delete_store']));
        foreach ($stores as $key => $s) {
            if ($s['id'] === $delete_id) {
                unset($stores[$key]);
                update_option('cutqueue_booking_system_stores', array_values($stores));
                // If active store removed, clear active option
                if ($active_store === $delete_id) update_option('cutqueue_booking_system_active_store', '');
                echo '<div class="updated notice"><p>Store deleted.</p></div>';
                break;
            }
        }
        $stores = cutqueue_booking_system_get_stores(); // refresh
    }

    // Handle save
    if (isset($_POST['cutqueue_booking_system_save_store'])) {
        check_admin_referer('cutqueue_booking_system_store_nonce', 'cutqueue_booking_system_store_nonce_field');
        $id = isset($_POST['store_id'])
            ? sanitize_title( wp_unslash($_POST['store_id']) )
            : '';

        $name = isset($_POST['store_name'])
            ? sanitize_text_field( wp_unslash($_POST['store_name']) )
            : '';

        $url_key = isset($_POST['store_url_key'])
            ? sanitize_text_field( wp_unslash($_POST['store_url_key']) )
            : '';

        // Prevent duplicate URL keys
        foreach ($stores as $s) {
            if (!empty($url_key) && $s['url_key'] === $url_key) {
                echo '<div class="error notice"><p>URL Key already in use.</p></div>';
                return;
            }
        }

        $currency = isset($_POST['store_currency'])
            ? sanitize_text_field( wp_unslash($_POST['store_currency']) )
            : 'eur';

        $timezone = isset($_POST['store_timezone'])
            ? sanitize_text_field(wp_unslash($_POST['store_timezone']))
            : 'Europe/Dublin';

        // ensure id present
        if (empty($id)) {
            echo '<div class="error notice"><p>Store ID required.</p></div>';
        } else {
            $exists = false;
            foreach ($stores as $s) if ($s['id'] === $id) $exists = true;
            if (!$exists) {
                $stores[] = [
                    'id' => $id,
                    'name' => $name,
                    'url_key' => $url_key,
                    'currency' => $currency,
                    'timezone' => $timezone
                ];
                update_option('cutqueue_booking_system_stores', $stores);
                echo '<div class="updated notice"><p>Store added.</p></div>';
            } else {
                echo '<div class="error notice"><p>Store ID already exists.</p></div>';
            }
        }
        $stores = cutqueue_booking_system_get_stores(); // refresh
    }

    // Handle active store selection
    if (isset($_POST['cutqueue_booking_system_set_active_store'])) {
        check_admin_referer('cutqueue_booking_system_set_active_store_nonce', 'cutqueue_booking_system_set_active_store_nonce_field');
        $active_store = isset($_POST['active_store'])
        ? sanitize_text_field( wp_unslash($_POST['active_store']) )
        : '';

        update_option('cutqueue_booking_system_active_store', $active_store);
        echo '<div class="updated notice"><p>Active store set to: '.esc_html($active_store).'</p></div>';
    }

    echo '<div class="container"><div class="pt-4"><h1>Stores</h1></div>';
    ?>
    <h3>Add New Store</h3>
    <form method="post"><?php wp_nonce_field('cutqueue_booking_system_store_nonce', 'cutqueue_booking_system_store_nonce_field'); ?>
    <div class="form-row">
        <div class="form-group col-md-4">
            <label for="store_id"><b>Store ID (slug)</b></label>
            <input 
                type="text" 
                id="store_id" 
                name="store_id" 
                class="form-control" 
                placeholder="e.g. newyork" 
                required>
        </div>
        <div class="form-group col-md-4">
            <label for="store_name"><b>Store Name</b></label>
            <input 
                type="text" 
                id="store_name" 
                name="store_name" 
                class="form-control" 
                placeholder="e.g. New York" 
                required>
        </div>
        <div class="form-group col-md-4">
            <label for="store_url_key"><b>URL Keyword (optional)</b></label>
            <input 
                type="text" 
                id="store_url_key" 
                name="store_url_key" 
                class="form-control" 
                placeholder="e.g. newyork">
        </div>
        <div class="form-group col-md-4">
            <label for="store_currency"><b>Currency</b></label>
            <select id="store_currency" name="store_currency" class="form-control">
                <?php 
                $currencies = ['eur' => 'EUR (€)', 'usd' => 'USD ($)', 'gbp' => 'GBP (£)'];
                foreach ($currencies as $code => $label): ?>
                    <option value="<?php echo esc_attr($code); ?>" <?php selected('eur', $code); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group col-md-4">
            <label for="store_timezone"><b>Timezone</b></label>
            <select id="store_timezone" name="store_timezone" class="form-control">
                <?php foreach (timezone_identifiers_list() as $tz): ?>
                    <option value="<?php echo esc_attr($tz); ?>">
                        <?php echo esc_html($tz); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>
    <div class="py-2">
        <button type="submit" name="cutqueue_booking_system_save_store" class="btn btn-success btn-sm">
            Add Store
        </button>
    </div>
    </form>
    <hr>
    <h3>Existing Stores</h3>
    <?php if ($stores): ?>
        <form method="post"><?php wp_nonce_field('cutqueue_booking_system_set_active_store_nonce', 'cutqueue_booking_system_set_active_store_nonce_field'); ?>
        <table class="table table-dark table-hover align-middle mb-0 rounded-3 overflow-hidden cutqueue_booking_system-stores-table" style="width:100%;">
            <thead class="table-warning text-dark">
                <tr>
                    <th scope="col">ID</th>
                    <th scope="col">Name</th>
                    <th scope="col">URL Key</th>
                    <th scope="col">Currency</th>
                    <th scope="col">Timezone</th>
                    <th scope="col" class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($stores as $s): ?>
                    <tr>
                        <td data-label="ID"><?php echo esc_html($s['id']); ?></td>
                        <td data-label="Name"><?php echo esc_html($s['name']); ?></td>
                        <td data-label="URL Key"><?php echo esc_html($s['url_key']); ?></td>
                        <td data-label="Currency"><?php echo esc_html(strtoupper($s['currency'] ?? 'EUR')); ?></td>
                        <td data-label="Timezone"><?php echo esc_html($s['timezone'] ?? 'Europe/Dublin'); ?></td>
                        <td class="text-end">
                            <a href="<?php echo esc_url(
                                wp_nonce_url(
                                    add_query_arg(['cutqueue_booking_system_delete_store' => $s['id']], admin_url('admin.php?page=cutqueue_booking_system-stores')),
                                    'cutqueue_booking_system_delete_store_nonce'
                                )
                            ); ?>" 
                            class="btn btn-danger btn-sm"
                            onclick="return confirm('Delete this store?');">
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </form>
    <?php else: ?>
        <p>No stores added yet.</p>
    <?php endif; ?>
    </div>
    <?php
}

function cutqueue_booking_system_payment_settings_page() {
    $current_store = get_user_meta(get_current_user_id(), 'cutqueue_current_store', true);

    // Load existing values
    $payment_mode = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_payment_mode', $current_store), 'disabled');
    $stripe_public_key = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_stripe_public_key', $current_store), '');
    $stripe_secret_key = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_stripe_secret_key', $current_store), '');

    // Handle POST (save action)
    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && check_admin_referer('cutqueue_booking_system_save_payment_settings')) {
      
        if (isset($_POST['cutqueue_booking_system_store']) && sanitize_text_field(wp_unslash($_POST['cutqueue_booking_system_store'])) !== $current_store) {
            wp_die('Invalid store context.');
        }

        $new_payment_mode = isset($_POST['cutqueue_booking_system_payment_mode'])
            ? sanitize_text_field(wp_unslash($_POST['cutqueue_booking_system_payment_mode']))
            : 'disabled';

        $new_public_key = isset($_POST['cutqueue_booking_system_stripe_public_key'])
            ? sanitize_text_field(wp_unslash($_POST['cutqueue_booking_system_stripe_public_key']))
            : '';

        $new_secret_key = isset($_POST['cutqueue_booking_system_stripe_secret_key'])
            ? sanitize_text_field(wp_unslash($_POST['cutqueue_booking_system_stripe_secret_key']))
            : '';

        // Update stored options
        update_option(cutqueue_booking_system_opt('cutqueue_booking_system_payment_mode', $current_store), $new_payment_mode);
        update_option(cutqueue_booking_system_opt('cutqueue_booking_system_stripe_public_key', $current_store), $new_public_key);
        update_option(cutqueue_booking_system_opt('cutqueue_booking_system_stripe_secret_key', $current_store), $new_secret_key);

        // Update in memory for re-render
        $payment_mode = $new_payment_mode;
        $stripe_public_key = $new_public_key;
        $stripe_secret_key = $new_secret_key;

        echo '<div class="updated notice"><p>Payment settings saved' . '!</p></div>';
    }

    // Render UI
    echo '<div class="container pt-4">';
    echo '<h1>Payment Settings</h1>';
    cutqueue_booking_system_store_switcher_html($current_store);
    ?>
    <form method="post">
        <?php wp_nonce_field('cutqueue_booking_system_save_payment_settings'); ?>
        <input type="hidden" name="cutqueue_booking_system_store" value="<?php echo esc_attr($current_store); ?>">

        <table class="table table-dark table-hover align-middle mb-0 rounded-3 overflow-hidden" style="width:100%;">
            <thead class="table-warning text-dark">
                <tr>
                    <th scope="col">Setting</th>
                    <th scope="col">Value</th>
                </tr>
            </thead>
            <tbody>
                <!-- Payment Mode -->
                <tr>
                    <td><strong>Payment Mode</strong></td>
                    <td>
                        <select id="cutqueue_booking_system_payment_mode_select" name="cutqueue_booking_system_payment_mode" class="form-select form-select-sm">
                            <option value="disabled" <?php selected($payment_mode, 'disabled'); ?>>Disable Payments</option>
                            <option value="online" <?php selected($payment_mode, 'online'); ?>>Online Only</option>
                        </select>
                    </td>
                </tr>

                <!-- Stripe Publishable Key -->
                <tr class="stripe-settings">
                    <td><strong>Stripe Publishable Key</strong></td>
                    <td>
                        <input type="text" name="cutqueue_booking_system_stripe_public_key" 
                               value="<?php echo esc_attr($stripe_public_key); ?>" 
                               class="form-control form-control-sm" />
                    </td>
                </tr>

                <!-- Stripe Secret Key -->
                <tr class="stripe-settings">
                    <td><strong>Stripe Secret Key</strong></td>
                    <td>
                        <input type="text" name="cutqueue_booking_system_stripe_secret_key" 
                               value="<?php echo esc_attr($stripe_secret_key); ?>" 
                               class="form-control form-control-sm" />
                    </td>
                </tr>
            </tbody>
        </table>

        <div class="py-3">
            <button type="submit" class="btn btn-success btn-sm">Save Settings</button>
        </div>
    </form>
    <?php
    echo '</div>';
}

function cutqueue_booking_system_notification_settings_page(){
    if ( isset($_GET['cutqueue_booking_system_store']) ) {

        $new_store = sanitize_text_field( wp_unslash( $_GET['cutqueue_booking_system_store'] ) );

        // Save selected store for this admin user
        update_user_meta(
            get_current_user_id(),
            'cutqueue_current_store',
            $new_store
        );

        $current_store = $new_store;

    } else {
        // Load saved store if no switch requested
        $current_store = get_user_meta(
            get_current_user_id(),
            'cutqueue_current_store',
            true
        );
    }

    // Load existing values
    $adminEmail = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_admin_email', $current_store), '');

    // Handle POST (save action)
    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && check_admin_referer('cutqueue_booking_system_save_notification_settings')) {

        // Validate store context
        if (isset($_POST['cutqueue_booking_system_store']) && sanitize_text_field(wp_unslash($_POST['cutqueue_booking_system_store'])) !== $current_store) {
            wp_die('Invalid store context.');
        }

        $new_admin_email = isset($_POST['cutqueue_booking_system_admin_email'])
            ? sanitize_text_field(wp_unslash($_POST['cutqueue_booking_system_admin_email']))
            : '';

        // Update stored options
        update_option(cutqueue_booking_system_opt('cutqueue_booking_system_admin_email', $current_store), $new_admin_email);

        // Update in memory for re-render
        $adminEmail = $new_admin_email;

        echo '<div class="updated notice"><p>Notification settings saved ' . '!</p></div>';
    }

    // Render UI
    echo '<div class="container pt-4">';
    echo '<h1>Notification Settings</h1>';

    cutqueue_booking_system_store_switcher_html($current_store);
    ?>
    <form method="post">
        <?php wp_nonce_field('cutqueue_booking_system_save_notification_settings'); ?>
        <input type="hidden" name="cutqueue_booking_system_store" value="<?php echo esc_attr($current_store); ?>">

        <table class="table table-dark table-hover align-middle mb-0 rounded-3 overflow-hidden" style="width:100%;">
            <thead class="table-warning text-dark">
                <tr>
                    <th scope="col">Setting</th>
                    <th scope="col">Value</th>
                </tr>
            </thead>
            <tbody>
                <tr class="stripe-settings">
                    <td><strong>Admin Email</strong></td>
                    <td>
                        <input type="text" name="cutqueue_booking_system_admin_email" 
                               value="<?php echo esc_attr($adminEmail); ?>" 
                               class="form-control form-control-sm" 
                               placeholder="abc@gmail.com"/>
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="py-3">
            <button type="submit" class="btn btn-success btn-sm">Save Settings</button>
        </div>
    </form>
    <?php
    echo '</div>';
}


?>