<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
if (!defined('ABSPATH')) {
    exit;
}

$nonce = wp_create_nonce('yatoon_admin_nonce');
$date_ts = strtotime($date . ' 12:00:00');
$prev_date = gmdate('Y-m-d', strtotime('-1 day', $date_ts));
$next_date = gmdate('Y-m-d', strtotime('+1 day', $date_ts));
$today_date = current_time('Y-m-d');

// ── Timezone fix ─────────────────────────────────────────────────────────────
// The DB stores times in the site's local timezone (no UTC offset stored).
// strtotime() silently interprets them as UTC on servers set to UTC, causing
// a 4-hour offset. We parse with explicit local timezone instead.
$_yc_tz_string = yatoon_timezone_string();
$_yc_local_tz  = new DateTimeZone( $_yc_tz_string );
function yatoon_cal_fmt_time( $db_time, $tz ) {
    if ( empty( $db_time ) ) { return '';
    }
    $dt = new DateTime( $db_time, $tz );
    return $dt->format( 'g:i A' );
}

// ── All active staff for filter UI ───────────────────────────────────────────
global $wpdb;
$_yc_all_staff       = $wpdb->get_results( "SELECT id, name FROM {$wpdb->prefix}yatoon_staff WHERE is_active = 1 AND is_bookable = 1 ORDER BY sort_order ASC, name ASC" ); // phpcs:ignore
$_yc_hidden_raw      = get_option( 'yatoon_calendar_hidden_staff', '' );
$_yc_hidden_ids      = array_filter( array_map( 'intval', explode( ',', $_yc_hidden_raw ) ) );

$status_options = array(
    'pending'   => 'Pending',
    'confirmed' => 'Confirmed',
    'completed' => 'Completed',
    'no_show'   => 'No Show',
    'cancelled' => 'Cancelled',
);
$payment_options = array(
    'unpaid'          => 'Unpaid',
    'paid_square_pos' => 'Paid in Square POS',
    'deposit_paid'    => 'Deposit Paid',
    'no_show_fee_charged' => 'No-show Fee Charged',
    'no_show_fee_waived'  => 'No-show Fee Waived',
    'partially_refunded' => 'Partially refunded',
    'refunded'        => 'Refunded',
    'waived'          => 'Waived',
);
$is_square_mode = get_option('yatoon_active_platform', 'local') === 'square';
$square_no_show_enabled = get_option('yatoon_square_no_show_fee_enabled', '') === '1';
$square_app_url = get_option('yatoon_square_app_url', '');
$square_checkout_url = get_option('yatoon_square_checkout_url', '');
$square_no_show_amount = (float) get_option('yatoon_square_no_show_fee_amount', 25);

$by_staff = array();
foreach ((array) $staff as $person) {
    $by_staff[ (int) $person->id ] = array(
        'staff'    => $person,
        'bookings' => array(),
    );
}
$by_staff[0] = array(
    'staff'    => (object) array('id' => 0, 'name' => 'Any / Unassigned'),
    'bookings' => array(),
);
foreach ((array) $bookings as $booking) {
    $staff_id = (int) ( $booking->staff_id ?? 0 );
    if (!isset($by_staff[ $staff_id ])) {
        $by_staff[ $staff_id ] = array(
            'staff'    => (object) array('id' => $staff_id, 'name' => $booking->staff_name ?: 'Inactive Staff'),
            'bookings' => array(),
        );
    }
    $by_staff[ $staff_id ]['bookings'][] = $booking;
}

$total_revenue = 0;
$unpaid_count = 0;
foreach ((array) $bookings as $booking) {
    $total_revenue += (float) $booking->total_price;
    if (empty($booking->payment_status) || $booking->payment_status === 'unpaid') {
        ++$unpaid_count;
    }
}
?>

<div class="wrap" id="yatoon-calendar-wrap">
    <h1><?php esc_html_e( 'Staff Calendar', 'yatoon-booking-system' ); ?></h1>


    <!-- Calendar settings bar: timezone + staff filter -->
    <div class="yc-settings-bar">
        <div>
            <h3><?php esc_html_e( 'Timezone', 'yatoon-booking-system' ); ?></h3>
            <div class="yc-tz-row">
                <span><?php echo esc_html( $_yc_tz_string ); ?></span>
                <span class="description"><?php esc_html_e( 'Uses the WordPress site timezone.', 'yatoon-booking-system' ); ?></span>
            </div>
        </div>
        <div>
            <h3><?php esc_html_e( 'Show Staff Columns', 'yatoon-booking-system' ); ?></h3>
            <div class="yc-staff-filters">
                <?php foreach ( $_yc_all_staff as $sf ) : ?>
                    <label>
                        <input type="checkbox" class="yc-staff-toggle"
                            data-staff-id="<?php echo intval( $sf->id ); ?>"
                            <?php checked( ! in_array( intval( $sf->id ), $_yc_hidden_ids, true ) ); ?>>
                        <?php echo esc_html( $sf->name ); ?>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <div class="yc-toolbar">
        <div class="yc-date-nav">
            <a class="button" href="<?php echo esc_url(admin_url('admin.php?page=yatoon-calendar&date=' . $prev_date)); ?>"><?php esc_html_e( '&larr; Prev', 'yatoon-booking-system' ); ?></a>
            <a class="button" href="<?php echo esc_url(admin_url('admin.php?page=yatoon-calendar&date=' . $today_date)); ?>"><?php esc_html_e( 'Today', 'yatoon-booking-system' ); ?></a>
            <a class="button" href="<?php echo esc_url(admin_url('admin.php?page=yatoon-calendar&date=' . $next_date)); ?>"><?php esc_html_e( 'Next &rarr;', 'yatoon-booking-system' ); ?></a>
            <form method="get" style="display:flex;gap:6px;align-items:center;">
                <input type="hidden" name="page" value="yatoon-calendar">
                <input type="date" name="date" value="<?php echo esc_attr($date); ?>">
                <button type="submit" class="button">Go</button>
            </form>
        </div>
        <div class="yc-date-title"><?php echo esc_html(date_i18n('D, M j, Y', $date_ts)); ?></div>
        <div class="yc-stats">
            <div class="yc-stat"><strong><?php echo count((array) $bookings); ?></strong><span><?php esc_html_e( 'Bookings', 'yatoon-booking-system' ); ?></span></div>
            <div class="yc-stat"><strong>$<?php echo esc_html(number_format($total_revenue, 0)); ?></strong><span><?php esc_html_e( 'Scheduled', 'yatoon-booking-system' ); ?></span></div>
            <div class="yc-stat"><strong><?php echo intval($unpaid_count); ?></strong><span><?php esc_html_e( 'Unpaid', 'yatoon-booking-system' ); ?></span></div>
        </div>
    </div>

    <div class="yc-mobile-staff-tabs" aria-label="<?php echo esc_attr__( 'Choose employee', 'yatoon-booking-system' ); ?>">
        <?php foreach ($by_staff as $group) : ?>
            <?php if ((int) $group['staff']->id === 0 && empty($group['bookings'])) { continue; } ?>
            <button type="button" data-calendar-staff-target="<?php echo intval($group['staff']->id); ?>">
                <span><?php echo esc_html($group['staff']->name); ?></span>
                <b><?php echo count($group['bookings']); ?></b>
            </button>
        <?php endforeach; ?>
    </div>

    <div class="yc-grid">
        <?php foreach ($by_staff as $group) : ?>
            <?php if ((int) $group['staff']->id === 0 && empty($group['bookings'])) { continue; } ?>
            <section class="yc-col" data-staff-id="<?php echo intval($group['staff']->id); ?>" data-staff-name="<?php echo esc_attr($group['staff']->name); ?>">
                <div class="yc-col-head">
                    <h2><?php echo esc_html($group['staff']->name); ?></h2>
                    <span class="yc-count"><?php echo count($group['bookings']); ?> appt</span>
                </div>
                <?php if (empty($group['bookings'])) : ?>
                    <div class="yc-empty"><?php esc_html_e( 'No bookings', 'yatoon-booking-system' ); ?></div>
                <?php else : ?>
                    <?php foreach ($group['bookings'] as $booking) : ?>
                        <div class="yc-card yc-status-<?php echo esc_attr($booking->status ?: 'pending'); ?><?php echo !empty($booking->design_image_url) ? ' yc-has-design' : ''; ?>"
                            draggable="true"
                            data-booking-id="<?php echo intval($booking->id); ?>"
                            data-service-id="<?php echo intval($booking->service_id); ?>"
                            data-staff-id="<?php echo intval($booking->staff_id); ?>"
                            data-design-upload="<?php echo esc_attr(!empty($booking->design_image_url) ? '1' : '0'); ?>"
                            data-start-time="<?php echo esc_attr($booking->start_time); ?>">
                            <div class="yc-time">
                                <?php echo esc_html( yatoon_cal_fmt_time( $booking->start_time, $_yc_local_tz ) ); ?>
                                - <?php echo esc_html( yatoon_cal_fmt_time( $booking->end_time, $_yc_local_tz ) ); ?>
                            </div>
                            <div class="yc-service"><?php echo esc_html($booking->service_name ?: 'Service'); ?> - $<?php echo esc_html(number_format((float) $booking->total_price, 2)); ?></div>
                            <div class="yc-client">
                                <strong><?php echo esc_html($booking->customer_name); ?></strong><br>
                                <?php echo esc_html($booking->customer_phone ?: $booking->customer_email); ?>
                            </div>
                            <div class="yc-controls">
                                <button type="button" class="button yc-view-details" data-booking-id="<?php echo intval($booking->id); ?>"><?php esc_html_e( 'View details', 'yatoon-booking-system' ); ?></button>
                                <select class="yc-status-select" data-booking-id="<?php echo intval($booking->id); ?>">
                                    <?php foreach ($status_options as $value => $label) : ?>
                                        <option value="<?php echo esc_attr($value); ?>" <?php selected($booking->status ?: 'pending', $value); ?>><?php echo esc_html($label); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <select class="yc-payment-select" data-booking-id="<?php echo intval($booking->id); ?>">
                                    <?php foreach ($payment_options as $value => $label) : ?>
                                        <option value="<?php echo esc_attr($value); ?>" <?php selected($booking->payment_status ?: 'unpaid', $value); ?>><?php echo esc_html($label); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="button" class="button yc-reschedule-toggle"><?php esc_html_e( 'Move / Reschedule', 'yatoon-booking-system' ); ?></button>
                                <div class="yc-reschedule-panel" aria-live="polite">
                                    <div class="yc-reschedule-row">
                                        <label>
                                            <?php esc_html_e( 'New date', 'yatoon-booking-system' ); ?>
                                            <input type="date" class="yc-reschedule-date" value="<?php echo esc_attr($date); ?>">
                                        </label>
                                    </div>
                                    <div class="yc-slot-list">
                                        <span class="description"><?php esc_html_e( 'Choose a date to load available times.', 'yatoon-booking-system' ); ?></span>
                                    </div>
                                    <div class="yc-reschedule-actions">
                                        <span class="description"><?php esc_html_e( 'You\'ll be asked how to notify the customer when you save.', 'yatoon-booking-system' ); ?></span>
                                        <button type="button" class="button button-primary yc-reschedule-save" disabled><?php esc_html_e( 'Save move', 'yatoon-booking-system' ); ?></button>
                                    </div>
                                    <div class="yc-reschedule-msg"></div>
                                </div>
                                <?php if ($is_square_mode && $square_no_show_enabled) : ?>
                                    <div class="yc-no-show-tools">
                                        <div class="yc-no-show-note">Square no-show fee: $<?php echo esc_html(number_format($square_no_show_amount, 2)); ?>. Open Square, charge if appropriate, then record the result.</div>
                                        <?php if ($square_app_url) : ?>
                                            <a class="button" href="<?php echo esc_url($square_app_url); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Open Square App', 'yatoon-booking-system' ); ?></a>
                                        <?php endif; ?>
                                        <?php if ($square_checkout_url) : ?>
                                            <a class="button" href="<?php echo esc_url($square_checkout_url); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Open Square Checkout', 'yatoon-booking-system' ); ?></a>
                                        <?php endif; ?>
                                        <button type="button" class="button yc-no-show-fee" data-booking-id="<?php echo intval($booking->id); ?>" data-status="no_show_fee_charged"><?php esc_html_e( 'Mark fee charged', 'yatoon-booking-system' ); ?></button>
                                        <button type="button" class="button yc-no-show-fee" data-booking-id="<?php echo intval($booking->id); ?>" data-status="no_show_fee_waived"><?php esc_html_e( 'Waive fee', 'yatoon-booking-system' ); ?></button>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </section>
        <?php endforeach; ?>
    </div>
</div>

<div id="yc-detail-overlay" class="yc-detail-overlay" aria-hidden="true">
    <div class="yc-detail-modal" role="dialog" aria-modal="true">
        <button type="button" class="yc-detail-close" id="yc-detail-close" aria-label="<?php echo esc_attr__( 'Close', 'yatoon-booking-system' ); ?>"><?php esc_html_e( '&times;', 'yatoon-booking-system' ); ?></button>
        <div id="yc-detail-body" class="yc-detail-body"></div>
    </div>
</div>

<?php
// The booking detail map is page data, so it is handed to the screen script
// through wp_localize_script rather than printed as a <script> literal. The
// script is enqueued in the footer, so localizing here still lands before it.
$_yc_detail_map = array();
foreach ( (array) $bookings as $_yc_b ) {
    $_yc_detail_map[ intval( $_yc_b->id ) ] = array(
        'id'                  => intval( $_yc_b->id ),
        'customer_name'       => $_yc_b->customer_name,
        'customer_email'      => $_yc_b->customer_email,
        'customer_phone'      => $_yc_b->customer_phone,
        'service_name'        => $_yc_b->service_name ?: 'Service',
        'staff_name'          => $_yc_b->staff_name ?: 'N/A',
        'start_time'          => yatoon_cal_fmt_time( $_yc_b->start_time, $_yc_local_tz ),
        'end_time'            => yatoon_cal_fmt_time( $_yc_b->end_time, $_yc_local_tz ),
        'status'              => $_yc_b->status ?: 'pending',
        'payment_status'      => $_yc_b->payment_status ?: 'unpaid',
        'payment_note'        => $_yc_b->payment_note,
        'total_price'         => number_format( (float) $_yc_b->total_price, 2 ),
        'notes'               => $_yc_b->notes,
        'design_image_url'    => $_yc_b->design_image_url,
        'consent_accepted'    => ! empty( $_yc_b->consent_accepted ),
        'policy_acknowledged' => ! empty( $_yc_b->policy_acknowledged ),
    );
}
wp_localize_script( 'yatoon-admin-calendar', 'yatoonCalendarData', array(
    'bookings'    => (object) $_yc_detail_map,
    'nonce'       => $nonce,
    'dateBaseUrl' => admin_url( 'admin.php?page=yatoon-calendar&date=' ),
    'date'        => $date,
) );
?>

