<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.WP.GlobalVariablesOverride.Prohibited -- False positives: locally-scoped variables (template view-vars via TemplateLoader::render() extract+include within a method, or closure locals), not plugin globals.

namespace Bookaro\Controller\Admin;


defined( 'ABSPATH' ) || exit;

/**
 * Booking edit screen template.
 *
 * Expected variables:
 * @var int    $id     Booking ID.
 * @var array  $row    Booking details.
 * @var string $notice Optional admin notice.
 */
use function esc_html_e;
use function esc_html__;
use function esc_html;
use function esc_attr;
use function esc_url;
use function admin_url;
use function wp_nonce_field;
use function submit_button;
use function selected;
use function get_option;
use function date_i18n;
use function sanitize_key;
use function absint;
use function get_userdata;

$status_key = sanitize_key( (string) ( $row['status'] ?? '' ) );
$status_labels = [
    'pending'   => esc_html__( 'Pending', 'mybookaro' ),
    'approved'  => esc_html__( 'Approved', 'mybookaro' ),
    'rejected'  => esc_html__( 'Rejected', 'mybookaro' ),
    'cancelled' => esc_html__( 'Cancelled', 'mybookaro' ),
    'completed' => esc_html__( 'Completed', 'mybookaro' ),
    'no_show'   => esc_html__( 'No-show', 'mybookaro' ),
];
$status_class_map = [
    'pending'   => 'pending',
    'approved'  => 'approved',
    'rejected'  => 'rejected',
    'cancelled' => 'cancelled',
    'completed' => 'completed',
    'no_show'   => 'no_show',
];
$status_label = $status_labels[ $status_key ] ?? ( $status_key !== '' ? ucfirst( $status_key ) : esc_html__( 'Unknown', 'mybookaro' ) );
$status_class = $status_class_map[ $status_key ] ?? 'pending';

$listing_id = absint( $row['listing_id'] ?? 0 );
$customer_name = '';
if ( ! empty( $row['customer_id'] ) ) {
    $customer = get_userdata( (int) $row['customer_id'] );
    $customer_name = $customer ? $customer->display_name : '';
}
$provider_name = '';
if ( ! empty( $row['provider_id'] ) ) {
    $provider = get_userdata( (int) $row['provider_id'] );
    $provider_name = $provider ? $provider->display_name : '';
}
$booking_date_raw = (string) ( $row['booking_date'] ?? '' );
// Bug 72: display-only label; format via presenter so the displayed time is
// not shifted by the GMT offset on non-UTC sites. The editable input below
// still uses $booking_date_raw, so the save path is unaffected.
$booking_date_display = $booking_date_raw !== ''
    ? \Bookaro\Utils\BookingPolicyPresenter::format_datetime_label( $booking_date_raw )
    : '';
$back_url = admin_url( 'admin.php?page=bookaro-bookings' );
?>
<?php if ( ! empty( $notice ) ) : ?>
    <div class="notice <?php echo esc_attr( $notice_type ?: 'notice-success' ); ?>"><p><?php echo esc_html( $notice ); ?></p></div>
<?php endif; ?>
<div class="wrap bookaro-admin bookaro-booking-edit">
    <div class="bookaro-card bookaro-hero bookaro-booking-edit-hero">
        <div class="bookaro-hero__content">
            <div class="bookaro-hero__brand">
                <img src="<?php echo esc_url( BOOKARO_PLUGIN_URL . 'assets/img/mb-logo.svg' ); ?>" alt="<?php esc_attr_e( 'MyBookaro', 'mybookaro' ); ?>" width="120" height="36" />
            </div>
            <h1>
                <?php
                printf(
                    /* translators: %d: booking ID. */
                    esc_html__( 'Booking #%d', 'mybookaro' ),
                    (int) $id
                );
                ?>
            </h1>
            <p class="description"><?php esc_html_e( 'Update booking details and review notifications.', 'mybookaro' ); ?></p>
            <div class="bookaro-hero__meta">
                <span class="bookaro-status badge-<?php echo esc_attr( $status_class ); ?>"><?php echo esc_html( $status_label ); ?></span>
                <?php if ( $booking_date_display !== '' ) : ?>
                    <span class="bookaro-pill"><?php echo esc_html__( 'Date:', 'mybookaro' ) . ' ' . esc_html( $booking_date_display ); ?></span>
                <?php endif; ?>
                <?php if ( $listing_id > 0 ) : ?>
                    <span class="bookaro-pill"><?php echo esc_html__( 'Listing', 'mybookaro' ) . ' #' . esc_html( (string) $listing_id ); ?></span>
                <?php endif; ?>
                <?php if ( $customer_name !== '' ) : ?>
                    <span class="bookaro-pill"><?php echo esc_html__( 'Customer:', 'mybookaro' ) . ' ' . esc_html( $customer_name ); ?></span>
                <?php endif; ?>
                <?php if ( $provider_name !== '' ) : ?>
                    <span class="bookaro-pill"><?php echo esc_html__( 'Provider:', 'mybookaro' ) . ' ' . esc_html( $provider_name ); ?></span>
                <?php endif; ?>
            </div>
        </div>
        <div class="bookaro-hero__actions">
            <a class="button button-secondary" href="<?php echo esc_url( $back_url ); ?>">
                <?php esc_html_e( 'Back to list', 'mybookaro' ); ?>
            </a>
        </div>
    </div>

    <div class="bookaro-overview-grid bookaro-booking-edit__grid">
        <div class="bookaro-card bookaro-booking-edit__card">
            <div class="bookaro-card__header">
                <h2><?php esc_html_e( 'Booking details', 'mybookaro' ); ?></h2>
                <p class="description"><?php esc_html_e( 'Edit the booking and save changes.', 'mybookaro' ); ?></p>
            </div>
            <form method="post" class="bookaro-booking-edit__form">
                <?php wp_nonce_field( 'edit_booking_' . $id, 'edit_booking_nonce' ); ?>
                <table class="form-table">
                    <tr>
                        <th><label for="service_label"><?php esc_html_e( 'Service', 'mybookaro' ); ?></label></th>
                        <td>
                            <input name="service_label" id="service_label" class="regular-text"
                                   value="<?php echo esc_attr( $row['service_label'] ); ?>" />
                        </td>
                    </tr>
                    <tr>
                        <th><label for="booking_date"><?php esc_html_e( 'Date & Time', 'mybookaro' ); ?></label></th>
                        <td>
                            <input name="booking_date" id="booking_date" class="regular-text"
                                   value="<?php echo esc_attr( $row['booking_date'] ); ?>" />
                            <p class="description"><?php esc_html_e( 'Format: YYYY-MM-DD HH:MM:SS', 'mybookaro' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="price"><?php esc_html_e( 'Price', 'mybookaro' ); ?></label></th>
                        <td>
                            <input name="price" id="price" class="regular-text"
                                   value="<?php echo esc_attr( $row['price'] ); ?>" />
                        </td>
                    </tr>
                    <tr>
                        <th><label for="status"><?php esc_html_e( 'Status', 'mybookaro' ); ?></label></th>
                        <td>
                            <select name="status" id="status">
                                <?php foreach ( $status_labels as $s => $label ) : ?>
                                    <option value="<?php echo esc_attr( $s ); ?>" <?php selected( $row['status'], $s ); ?>>
                                        <?php echo esc_html( $label ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="notes"><?php esc_html_e( 'Notes', 'mybookaro' ); ?></label></th>
                        <td>
                            <textarea name="notes" id="notes" rows="5" cols="50"><?php echo esc_html( $row['notes'] ); ?></textarea>
                        </td>
                    </tr>
                </table>
                <div class="bookaro-actions">
                    <?php submit_button( esc_html__( 'Save Booking', 'mybookaro' ), 'primary', 'submit', false ); ?>
                    <a href="<?php echo esc_url( $back_url ); ?>" class="button button-secondary"><?php esc_html_e( 'Back to list', 'mybookaro' ); ?></a>
                </div>
            </form>
        </div>

        <?php do_action( 'bookaro_admin_booking_custom_fields', $id, $row ); ?>

        <div class="bookaro-card bookaro-booking-edit__card">
            <div class="bookaro-card__header">
                <h2><?php esc_html_e( 'Notification log', 'mybookaro' ); ?></h2>
                <p class="description"><?php esc_html_e( 'Tracks delivery of email, SMS, and webhook notifications.', 'mybookaro' ); ?></p>
            </div>
            <?php if ( empty( $notification_logs ) ) : ?>
                <p class="description"><?php esc_html_e( 'No notifications logged for this booking yet.', 'mybookaro' ); ?></p>
            <?php else : ?>
                <table class="widefat striped bookaro-log-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Date', 'mybookaro' ); ?></th>
                            <th><?php esc_html_e( 'Channel', 'mybookaro' ); ?></th>
                            <th><?php esc_html_e( 'Status', 'mybookaro' ); ?></th>
                            <th><?php esc_html_e( 'Summary', 'mybookaro' ); ?></th>
                            <th><?php esc_html_e( 'Error', 'mybookaro' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ( $notification_logs as $log ) : ?>
                        <?php
                        $summary_data = is_array( $log['summary_data'] ?? null ) ? $log['summary_data'] : [];
                        $summary_parts = [];
                        foreach ( $summary_data as $key => $value ) {
                            $summary_parts[] = $key . ': ' . $value;
                        }
                        $summary_text = implode( ' | ', $summary_parts );
                        $created_at = ! empty( $log['created_at'] ) ? $log['created_at'] : '';
                        // Bug 72: log created_at is stored site-local (current_time('mysql')); format via presenter to avoid GMT shift.
                        $created_display = $created_at ? \Bookaro\Utils\BookingPolicyPresenter::format_datetime_label( $created_at ) : '';
                        ?>
                        <tr>
                            <td><?php echo esc_html( $created_display ); ?></td>
                            <td><?php echo esc_html( $log['channel'] ?? '' ); ?></td>
                            <td><?php echo esc_html( $log['status'] ?? '' ); ?></td>
                            <td><?php echo esc_html( $summary_text ); ?></td>
                            <td><?php echo esc_html( $log['error_message'] ?? '' ); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
</div>
