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

$summary = $summary ?: (object) array();
$cards = array(
    array('label' => 'Bookings', 'value' => intval($summary->total_bookings ?? 0), 'tone' => '#111827'),
    array('label' => 'Completed', 'value' => intval($summary->completed_count ?? 0), 'tone' => '#166534'),
    array('label' => 'No Shows', 'value' => intval($summary->no_show_count ?? 0), 'tone' => '#b91c1c'),
    array('label' => 'Cancelled', 'value' => intval($summary->cancelled_count ?? 0), 'tone' => '#6b7280'),
    array('label' => 'Unpaid', 'value' => intval($summary->unpaid_count ?? 0), 'tone' => '#b45309'),
    array('label' => 'Scheduled Revenue', 'value' => '$' . number_format((float) ( $summary->scheduled_revenue ?? 0 ), 0), 'tone' => '#7c3aed'),
    array('label' => 'Repeat Clients', 'value' => intval($repeat_clients ?? 0), 'tone' => '#0f766e'),
    array('label' => 'Next 7 Days', 'value' => intval($upcoming_7_days ?? 0), 'tone' => '#0369a1'),
);
$today_cards = array(
    array('label' => 'Today Bookings', 'value' => intval($today_summary->booking_count ?? 0), 'tone' => '#111827'),
    array('label' => 'Today Active', 'value' => intval($today_summary->active_count ?? 0), 'tone' => '#166534'),
    array('label' => 'Today Unpaid', 'value' => intval($today_summary->unpaid_count ?? 0), 'tone' => '#b45309'),
    array('label' => 'Today Revenue', 'value' => '$' . number_format((float) ( $today_summary->scheduled_revenue ?? 0 ), 0), 'tone' => '#7c3aed'),
);
$export_url = add_query_arg(
    array(
		'action'    => 'yatoon_export_reports',
		'nonce'     => wp_create_nonce('yatoon_export_reports'),
		'date_from' => $date_from,
		'date_to'   => $date_to,
	),
    admin_url('admin-ajax.php')
);
$pdf_url = add_query_arg(
    array(
        'action'    => 'yatoon_export_reports_pdf',
        'nonce'     => wp_create_nonce('yatoon_export_reports'),
        'date_from' => $date_from,
        'date_to'   => $date_to,
    ),
    admin_url('admin-ajax.php')
);
$advanced_metrics = is_array($advanced_metrics ?? null) ? $advanced_metrics : array();
$growth_cards = array(
    array('label' => __('Repeat Client Rate', 'yatoon-booking-system'), 'value' => number_format_i18n((float) ( $advanced_metrics['repeat_rate'] ?? 0 ), 1) . '%', 'tone' => '#0f766e'),
    array('label' => __('Client Retention', 'yatoon-booking-system'), 'value' => number_format_i18n((float) ( $advanced_metrics['retention_rate'] ?? 0 ), 1) . '%', 'tone' => '#166534'),
    array('label' => __('Rebooking Rate', 'yatoon-booking-system'), 'value' => number_format_i18n((float) ( $advanced_metrics['rebook_rate'] ?? 0 ), 1) . '%', 'tone' => '#0369a1'),
    array('label' => __('Cancellation Rate', 'yatoon-booking-system'), 'value' => number_format_i18n((float) ( $advanced_metrics['cancellation_rate'] ?? 0 ), 1) . '%', 'tone' => '#b45309'),
    array('label' => __('No-show Rate', 'yatoon-booking-system'), 'value' => number_format_i18n((float) ( $advanced_metrics['no_show_rate'] ?? 0 ), 1) . '%', 'tone' => '#b91c1c'),
    array('label' => __('Next 30 Days', 'yatoon-booking-system'), 'value' => '$' . number_format_i18n((float) ( $advanced_metrics['future_revenue_30'] ?? 0 ), 0), 'tone' => '#7c3aed'),
    array('label' => __('Commission Due', 'yatoon-booking-system'), 'value' => '$' . number_format_i18n((float) ( $advanced_metrics['commission_total'] ?? 0 ), 0), 'tone' => '#92400e'),
    array('label' => __('Estimated Contribution', 'yatoon-booking-system'), 'value' => '$' . number_format_i18n((float) ( $advanced_metrics['contribution_after_commission'] ?? 0 ), 0), 'tone' => '#166534'),
);

// --- Chart data prep -------------------------------------------------------
// Pure presentation: reuses the report queries already run above, no new
// database access. Kept local to this view so it never affects the data
// available to other Reports consumers (CSV/PDF export, etc.).
$yr_trend_days = array_values(array_reverse((array) $daily_breakdown)); // oldest -> newest
$yr_trend_labels = array();
$yr_trend_revenue = array();
$yr_trend_bookings = array();
foreach ($yr_trend_days as $yr_d) {
    $yr_trend_labels[]   = gmdate('M j', strtotime($yr_d->booking_date));
    $yr_trend_revenue[]  = round((float) ( $yr_d->total_revenue ?? 0 ), 2);
    $yr_trend_bookings[] = (int) ( $yr_d->booking_count ?? 0 );
}

$yr_service_bars = (array) $top_services;
usort($yr_service_bars, function ($a, $b) {
    return ( (float) ( $b->total_revenue ?? 0 ) ) <=> ( (float) ( $a->total_revenue ?? 0 ) );
});
$yr_service_bars = array_slice($yr_service_bars, 0, 8);
$yr_service_labels = array();
$yr_service_values = array();
foreach ($yr_service_bars as $yr_s) {
    $yr_service_labels[] = $yr_s->name ?: __('Unknown Service', 'yatoon-booking-system');
    $yr_service_values[] = round((float) ( $yr_s->total_revenue ?? 0 ), 2);
}

$yr_staff_bars = (array) $staff_performance;
usort($yr_staff_bars, function ($a, $b) {
    return ( (float) ( $b->total_revenue ?? 0 ) ) <=> ( (float) ( $a->total_revenue ?? 0 ) );
});
$yr_staff_bars = array_slice($yr_staff_bars, 0, 8);
$yr_staff_labels = array();
$yr_staff_values = array();
foreach ($yr_staff_bars as $yr_st) {
    $yr_staff_labels[] = $yr_st->name ?: __('Unassigned', 'yatoon-booking-system');
    $yr_staff_values[] = round((float) ( $yr_st->total_revenue ?? 0 ), 2);
}

// Chart.js is enqueued conditionally for this admin page only (see
// enqueue_admin_scripts() in class-yatoon-admin.php); localize the chart
// data onto the already-registered handle so the init script can read it.
if ( function_exists( 'wp_script_is' ) && wp_script_is( 'yatoon-reports-charts', 'registered' ) ) {
    wp_localize_script( 'yatoon-reports-charts', 'yatoonReportsData', array(
        'trend' => array(
            'labels'   => $yr_trend_labels,
            'revenue'  => $yr_trend_revenue,
            'bookings' => $yr_trend_bookings,
        ),
        'services' => array(
            'labels' => $yr_service_labels,
            'values' => $yr_service_values,
        ),
        'staff' => array(
            'labels' => $yr_staff_labels,
            'values' => $yr_staff_values,
        ),
        'currencySymbol' => '$',
        'strings' => array(
            'revenue'  => __( 'Revenue', 'yatoon-booking-system' ),
            'bookings' => __( 'Bookings', 'yatoon-booking-system' ),
        ),
    ) );
}
?>

<div class="wrap" id="yatoon-reports-wrap">
    <h1><?php esc_html_e( 'Reports', 'yatoon-booking-system' ); ?></h1>
    <p style="color:#6b7280;margin-top:0;"><?php esc_html_e( 'Simple business reporting for bookings, staff performance, service demand, and payment follow-up.', 'yatoon-booking-system' ); ?></p>

    <style>
    #yatoon-reports-wrap .yr-filter{display:flex;gap:10px;align-items:end;flex-wrap:wrap;background:#fff;border:1px solid #dcdcde;border-radius:8px;padding:14px 16px;margin:14px 0 18px;}
    #yatoon-reports-wrap .yr-filter label{display:block;font-size:12px;font-weight:600;color:#4b5563;margin-bottom:4px;}
    #yatoon-reports-wrap .yr-cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin-bottom:18px;}
    #yatoon-reports-wrap .yr-card{background:#fff;border:1px solid #dcdcde;border-radius:8px;padding:14px;}
    #yatoon-reports-wrap .yr-card strong{display:block;font-size:28px;line-height:1.1;margin-bottom:4px;}
    #yatoon-reports-wrap .yr-card span{font-size:12px;color:#6b7280;text-transform:uppercase;letter-spacing:.04em;}
    #yatoon-reports-wrap .yr-grid{display:grid;grid-template-columns:1.1fr 1fr;gap:16px;}
    #yatoon-reports-wrap .yr-panel{background:#fff;border:1px solid #dcdcde;border-radius:8px;overflow:hidden;}
    #yatoon-reports-wrap .yr-panel h2{margin:0;padding:14px 16px;border-bottom:1px solid #ececec;font-size:15px;color:#111827;}
    #yatoon-reports-wrap table{width:100%;border-collapse:collapse;}
    #yatoon-reports-wrap th,#yatoon-reports-wrap td{padding:10px 12px;border-bottom:1px solid #f3f4f6;text-align:left;font-size:13px;vertical-align:top;}
    #yatoon-reports-wrap th{background:#f9fafb;color:#4b5563;font-size:12px;text-transform:uppercase;letter-spacing:.03em;}
    #yatoon-reports-wrap tr:last-child td{border-bottom:none;}
    #yatoon-reports-wrap .yr-table-wrap{overflow:auto;}
    #yatoon-reports-wrap .yr-sub{font-size:12px;color:#6b7280;}
    #yatoon-reports-wrap .yr-action-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap;}
    #yatoon-reports-wrap .yr-pill{display:inline-flex;align-items:center;border-radius:999px;padding:2px 8px;background:#f3f4f6;color:#374151;font-size:11px;font-weight:700;}
    #yatoon-reports-wrap .yr-money{font-weight:700;color:#7c3aed;}
    @media (max-width: 980px){#yatoon-reports-wrap .yr-grid{grid-template-columns:1fr;}}
    #yatoon-reports-wrap .yr-chart-wrap{padding:16px 16px 4px;}
    #yatoon-reports-wrap .yr-chart-wrap-canvas{position:relative;}
    #yatoon-reports-wrap .yr-chart-note{padding:8px 16px 4px;margin:0;}
    </style>

    <form method="get" class="yr-filter">
        <input type="hidden" name="page" value="yatoon-reports">
        <div>
            <label for="yr-date-from"><?php esc_html_e( 'From', 'yatoon-booking-system' ); ?></label>
            <input type="date" id="yr-date-from" name="date_from" value="<?php echo esc_attr($date_from); ?>">
        </div>
        <div>
            <label for="yr-date-to">To</label>
            <input type="date" id="yr-date-to" name="date_to" value="<?php echo esc_attr($date_to); ?>">
        </div>
        <div>
            <button type="submit" class="button button-primary"><?php esc_html_e( 'Apply', 'yatoon-booking-system' ); ?></button>
            <a class="button" href="<?php echo esc_url(admin_url('admin.php?page=yatoon-reports')); ?>"><?php esc_html_e( 'Last 30 Days', 'yatoon-booking-system' ); ?></a>
            <a class="button" href="<?php echo esc_url($export_url); ?>"><?php esc_html_e('Export CSV', 'yatoon-booking-system'); ?></a>
            <a class="button" href="<?php echo esc_url($pdf_url); ?>"><?php esc_html_e('Export PDF', 'yatoon-booking-system'); ?></a>
        </div>
        <div class="yr-sub">Range: <?php echo esc_html($date_from); ?> to <?php echo esc_html($date_to); ?></div>
    </form>

    <div class="yr-cards">
        <?php foreach ($cards as $card) : ?>
            <div class="yr-card">
                <strong style="color:<?php echo esc_attr($card['tone']); ?>;"><?php echo esc_html($card['value']); ?></strong>
                <span><?php echo esc_html($card['label']); ?></span>
            </div>
        <?php endforeach; ?>
    </div>

    <section class="yr-panel" style="margin-bottom:16px;">
        <h2><?php esc_html_e('Growth, Retention & Forecast', 'yatoon-booking-system'); ?></h2>
        <div class="yr-cards" style="padding:14px 16px;margin:0;">
            <?php foreach ($growth_cards as $card) : ?>
                <div class="yr-card" style="margin:0;">
                    <strong style="color:<?php echo esc_attr($card['tone']); ?>;"><?php echo esc_html($card['value']); ?></strong>
                    <span><?php echo esc_html($card['label']); ?></span>
                </div>
            <?php endforeach; ?>
        </div>
	        <p class="yr-sub" style="padding:0 16px 14px;margin:0;"><?php esc_html_e('Estimated contribution is scheduled revenue minus configured service supply costs and calculated staff commission. Rent, tax, payment fees, and other operating costs are not deducted.', 'yatoon-booking-system'); ?></p>
    </section>

    <div class="yr-grid" style="margin-bottom:16px;">
        <section class="yr-panel">
            <h2><?php esc_html_e('Staff Utilization', 'yatoon-booking-system'); ?></h2>
            <div class="yr-table-wrap"><table><thead><tr><th><?php esc_html_e('Staff', 'yatoon-booking-system'); ?></th><th><?php esc_html_e('Booked', 'yatoon-booking-system'); ?></th><th><?php esc_html_e('Capacity', 'yatoon-booking-system'); ?></th><th><?php esc_html_e('Utilization', 'yatoon-booking-system'); ?></th><th><?php esc_html_e('Revenue', 'yatoon-booking-system'); ?></th></tr></thead><tbody>
            <?php if (empty($advanced_metrics['staff'])) : ?><tr><td colspan="5" class="yr-sub"><?php esc_html_e('No staff data for this range.', 'yatoon-booking-system'); ?></td></tr><?php else : foreach ((array) $advanced_metrics['staff'] as $row) : ?>
                <tr><td><strong><?php echo esc_html($row->name ?: __('Staff', 'yatoon-booking-system')); ?></strong></td><td><?php echo esc_html(number_format_i18n((float) $row->booked_minutes / 60, 1)); ?>h</td><td><?php echo esc_html(number_format_i18n((float) $row->capacity_minutes / 60, 1)); ?>h</td><td><span class="yr-pill"><?php echo esc_html(number_format_i18n((float) $row->utilization, 1)); ?>%</span></td><td>$<?php echo esc_html(number_format_i18n((float) $row->revenue, 0)); ?></td></tr>
            <?php endforeach;
endif; ?>
            </tbody></table></div>
        </section>
        <section class="yr-panel">
            <h2><?php esc_html_e('Booking Sources', 'yatoon-booking-system'); ?></h2>
            <div class="yr-table-wrap"><table><thead><tr><th><?php esc_html_e('Source', 'yatoon-booking-system'); ?></th><th><?php esc_html_e('Bookings', 'yatoon-booking-system'); ?></th><th><?php esc_html_e('Revenue', 'yatoon-booking-system'); ?></th></tr></thead><tbody>
            <?php if (empty($advanced_metrics['sources'])) : ?><tr><td colspan="3" class="yr-sub"><?php esc_html_e('No source data for this range.', 'yatoon-booking-system'); ?></td></tr><?php else : foreach ((array) $advanced_metrics['sources'] as $row) : ?>
                <tr><td><strong><?php echo esc_html($row->source); ?></strong></td><td><?php echo intval($row->bookings); ?></td><td>$<?php echo esc_html(number_format_i18n((float) $row->revenue, 0)); ?></td></tr>
            <?php endforeach;
endif; ?>
            </tbody></table></div>
            <p class="yr-sub" style="padding:0 12px 12px;"><?php esc_html_e('Square-synced appointments are separated from WordPress/local bookings. Campaign conversion requires tagged links or an analytics integration.', 'yatoon-booking-system'); ?></p>
        </section>
	    </div>

	    <section class="yr-panel" style="margin-bottom:16px;">
	        <h2><?php esc_html_e('Service Revenue & Estimated Profit', 'yatoon-booking-system'); ?></h2>
	        <div class="yr-table-wrap"><table><thead><tr><th><?php esc_html_e('Service', 'yatoon-booking-system'); ?></th><th><?php esc_html_e('Bookings', 'yatoon-booking-system'); ?></th><th><?php esc_html_e('Revenue', 'yatoon-booking-system'); ?></th><th><?php esc_html_e('Supply cost', 'yatoon-booking-system'); ?></th><th><?php esc_html_e('Before commission', 'yatoon-booking-system'); ?></th></tr></thead><tbody>
	        <?php if (empty($advanced_metrics['services'])) : ?><tr><td colspan="5" class="yr-sub"><?php esc_html_e('No service data for this range.', 'yatoon-booking-system'); ?></td></tr><?php else : foreach ((array) $advanced_metrics['services'] as $row) : ?>
	            <tr><td><strong><?php echo esc_html($row->name); ?></strong></td><td><?php echo intval($row->bookings); ?></td><td>$<?php echo esc_html(number_format_i18n((float) $row->revenue, 2)); ?></td><td>$<?php echo esc_html(number_format_i18n((float) $row->supply_cost, 2)); ?></td><td>$<?php echo esc_html(number_format_i18n((float) $row->profit_before_commission, 2)); ?></td></tr>
	        <?php endforeach;
endif; ?>
	        </tbody></table></div>
	        <p class="yr-sub" style="padding:0 12px 12px;"><?php esc_html_e('Set an optional estimated supply cost on each service. These figures are planning estimates, not tax accounting.', 'yatoon-booking-system'); ?></p>
	    </section>
    <section class="yr-panel" style="margin-bottom:16px;">
        <h2><?php esc_html_e( 'Today at a Glance', 'yatoon-booking-system' ); ?></h2>
        <div class="yr-cards" style="padding:14px 16px;margin:0;">
            <?php foreach ($today_cards as $card) : ?>
                <div class="yr-card" style="margin:0;">
                    <strong style="color:<?php echo esc_attr($card['tone']); ?>;"><?php echo esc_html($card['value']); ?></strong>
                    <span><?php echo esc_html($card['label']); ?></span>
                </div>
            <?php endforeach; ?>
        </div>
    </section>

    <div class="yr-grid">
        <section class="yr-panel">
            <h2><?php esc_html_e( 'Top Services', 'yatoon-booking-system' ); ?></h2>
            <div class="yr-chart-wrap yr-chart-wrap-canvas">
                <canvas id="yr-canvas-services" height="220" role="img" aria-label="<?php esc_attr_e( 'Revenue by service, bar chart', 'yatoon-booking-system' ); ?>"></canvas>
            </div>
            <div class="yr-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Service', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Bookings', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Completed', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Revenue', 'yatoon-booking-system' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($top_services)) : ?>
                            <tr><td colspan="4" class="yr-sub"><?php esc_html_e( 'No service data for this range.', 'yatoon-booking-system' ); ?></td></tr>
                        <?php else : ?>
                            <?php foreach ($top_services as $row) : ?>
                                <tr>
                                    <td><strong><?php echo esc_html($row->name ?: 'Unknown Service'); ?></strong></td>
                                    <td><?php echo intval($row->booking_count); ?></td>
                                    <td><?php echo intval($row->completed_count); ?></td>
                                    <td>$<?php echo number_format((float) $row->total_revenue, 0); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <section class="yr-panel">
            <h2><?php esc_html_e( 'Staff Performance', 'yatoon-booking-system' ); ?></h2>
            <div class="yr-chart-wrap yr-chart-wrap-canvas">
                <canvas id="yr-canvas-staff" height="220" role="img" aria-label="<?php esc_attr_e( 'Revenue by staff, bar chart', 'yatoon-booking-system' ); ?>"></canvas>
            </div>
            <div class="yr-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Staff', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Bookings', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'No Show', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Revenue', 'yatoon-booking-system' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($staff_performance)) : ?>
                            <tr><td colspan="4" class="yr-sub"><?php esc_html_e( 'No staff data for this range.', 'yatoon-booking-system' ); ?></td></tr>
                        <?php else : ?>
                            <?php foreach ($staff_performance as $row) : ?>
                                <tr>
                                    <td>
                                        <strong><?php echo esc_html($row->name ?: 'Any / Unassigned'); ?></strong><br>
                                        <span class="yr-sub"><?php echo intval($row->completed_count); ?> completed</span>
                                    </td>
                                    <td><?php echo intval($row->booking_count); ?></td>
                                    <td><?php echo intval($row->no_show_count); ?></td>
                                    <td>$<?php echo number_format((float) $row->total_revenue, 0); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </div>

    <section class="yr-panel" style="margin-top:16px;">
        <h2><?php esc_html_e( 'Staff Utilization', 'yatoon-booking-system' ); ?></h2>
        <div class="yr-table-wrap">
            <table>
                <thead>
                    <tr>
                        <th><?php esc_html_e( 'Staff', 'yatoon-booking-system' ); ?></th>
                        <th><?php esc_html_e( 'Booked Hours', 'yatoon-booking-system' ); ?></th>
                        <th><?php esc_html_e( 'Utilization', 'yatoon-booking-system' ); ?></th>
                        <th><?php esc_html_e( 'Bookings', 'yatoon-booking-system' ); ?></th>
                        <th><?php esc_html_e( 'Revenue', 'yatoon-booking-system' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($staff_utilization)) : ?>
                        <tr><td colspan="5" class="yr-sub"><?php esc_html_e( 'No staff utilization data for this range.', 'yatoon-booking-system' ); ?></td></tr>
                    <?php else : ?>
                        <?php foreach ($staff_utilization as $row) : ?>
                            <?php
                            $booked_minutes = max(0, intval($row->booked_minutes ?? 0));
                            $util_pct = $staff_capacity_minutes > 0 ? min(100, round(( $booked_minutes / $staff_capacity_minutes ) * 100)) : 0;
                            ?>
                            <tr>
                                <td><strong><?php echo esc_html($row->name ?: 'Any / Unassigned'); ?></strong></td>
                                <td><?php echo esc_html(number_format($booked_minutes / 60, 1)); ?>h</td>
                                <td>
                                    <div style="height:8px;background:#f3f4f6;border-radius:999px;overflow:hidden;min-width:110px;">
                                        <span style="display:block;height:100%;width:<?php echo esc_attr($util_pct); ?>%;background:#111827;border-radius:999px;"></span>
                                    </div>
                                    <span class="yr-sub"><?php echo esc_html($util_pct); ?>% of 8h/day estimate</span>
                                </td>
                                <td><?php echo intval($row->booking_count); ?></td>
                                <td>$<?php echo number_format((float) $row->total_revenue, 0); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>

    <div class="yr-grid" style="margin-top:16px;">
        <section class="yr-panel">
            <h2><?php esc_html_e( 'Upcoming This Week', 'yatoon-booking-system' ); ?></h2>
            <div class="yr-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Client', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Appointment', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Staff', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Price', 'yatoon-booking-system' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($upcoming_bookings)) : ?>
                            <tr><td colspan="4" class="yr-sub"><?php esc_html_e( 'No upcoming bookings in the next 7 days.', 'yatoon-booking-system' ); ?></td></tr>
                        <?php else : ?>
                            <?php foreach ($upcoming_bookings as $row) : ?>
                                <tr>
                                    <td>
                                        <strong><?php echo esc_html($row->customer_name ?: 'Guest'); ?></strong><br>
                                        <span class="yr-sub"><?php echo esc_html($row->customer_phone ?: $row->customer_email); ?></span>
                                    </td>
                                    <td>
                                        <?php echo esc_html(gmdate('M j, g:i A', strtotime($row->start_time))); ?><br>
                                        <span class="yr-sub"><?php echo esc_html($row->service_name ?: 'Service'); ?></span>
                                    </td>
                                    <td><?php echo esc_html($row->staff_name ?: 'Any / Unassigned'); ?></td>
                                    <td class="yr-money">$<?php echo number_format((float) $row->total_price, 0); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <section class="yr-panel">
            <h2><?php esc_html_e( 'Needs Follow-Up', 'yatoon-booking-system' ); ?></h2>
            <div class="yr-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Type', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Client', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Detail', 'yatoon-booking-system' ); ?></th>
                            <th><?php esc_html_e( 'Action', 'yatoon-booking-system' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($unpaid_followups) && empty($at_risk_clients)) : ?>
                            <tr><td colspan="4" class="yr-sub"><?php esc_html_e( 'No payment or rebooking follow-ups right now.', 'yatoon-booking-system' ); ?></td></tr>
                        <?php else : ?>
                            <?php foreach ((array) $unpaid_followups as $row) : ?>
                                <tr>
                                    <td><span class="yr-pill"><?php esc_html_e( 'Unpaid', 'yatoon-booking-system' ); ?></span></td>
                                    <td>
                                        <strong><?php echo esc_html($row->customer_name ?: 'Guest'); ?></strong><br>
                                        <span class="yr-sub"><?php echo esc_html($row->customer_phone ?: $row->customer_email); ?></span>
                                    </td>
                                    <td>
                                        $<?php echo number_format((float) $row->total_price, 0); ?> · <?php echo esc_html($row->service_name ?: 'Service'); ?><br>
                                        <span class="yr-sub"><?php echo esc_html(gmdate('M j, Y', strtotime($row->start_time))); ?></span>
                                    </td>
                                    <td><a class="button button-small" href="<?php echo esc_url(admin_url('admin.php?page=sbs-bookings&s=' . rawurlencode($row->customer_phone ?: $row->customer_email))); ?>"><?php esc_html_e( 'Open', 'yatoon-booking-system' ); ?></a></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php foreach ((array) $at_risk_clients as $row) : ?>
                                <tr>
                                    <td><span class="yr-pill"><?php esc_html_e( 'Rebook', 'yatoon-booking-system' ); ?></span></td>
                                    <td>
                                        <strong><?php echo esc_html($row->customer_name ?: 'Client'); ?></strong><br>
                                        <span class="yr-sub"><?php echo esc_html($row->customer_phone ?: $row->customer_email); ?></span>
                                    </td>
                                    <td>
                                        Last visit <?php echo esc_html(gmdate('M j, Y', strtotime($row->last_visit))); ?><br>
                                        <span class="yr-sub"><?php echo intval($row->visit_count); ?> visits · $<?php echo number_format((float) $row->lifetime_value, 0); ?> lifetime</span>
                                    </td>
                                    <td>
                                        <?php if (!empty($row->customer_email)) : ?>
                                            <a class="button button-small" href="mailto:<?php echo esc_attr($row->customer_email); ?>"><?php esc_html_e( 'Email', 'yatoon-booking-system' ); ?></a>
                                            <button type="button" class="button button-small yatoon-send-recall" data-name="<?php echo esc_attr($row->customer_name); ?>" data-email="<?php echo esc_attr($row->customer_email); ?>" data-phone="<?php echo esc_attr($row->customer_phone); ?>"><?php esc_html_e( 'Send Recall', 'yatoon-booking-system' ); ?></button>
                                        <?php elseif (!empty($row->customer_phone)) : ?>
                                            <a class="button button-small" href="tel:<?php echo esc_attr($row->customer_phone); ?>"><?php esc_html_e( 'Call', 'yatoon-booking-system' ); ?></a>
                                        <?php else : ?>
                                            <span class="yr-sub"><?php esc_html_e( 'No contact', 'yatoon-booking-system' ); ?></span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </div>

    <section class="yr-panel" style="margin-top:16px;">
        <h2><?php esc_html_e( 'Revenue &amp; Bookings Trend', 'yatoon-booking-system' ); ?></h2>
        <?php if ( empty( $yr_trend_days ) ) : ?>
            <p class="yr-sub" style="padding:14px 16px 0;margin:0;"><?php esc_html_e( 'No booking activity in this range.', 'yatoon-booking-system' ); ?></p>
        <?php else : ?>
            <div class="yr-chart-wrap yr-chart-wrap-canvas">
                <canvas id="yr-canvas-trend" height="90" role="img" aria-label="<?php esc_attr_e( 'Revenue and bookings trend over the selected date range', 'yatoon-booking-system' ); ?>"></canvas>
                <p class="yr-sub yr-chart-note"><?php esc_html_e( 'Bars are daily revenue; the line is bookings per day.', 'yatoon-booking-system' ); ?></p>
            </div>
        <?php endif; ?>
        <h3 style="margin:18px 16px 0;font-size:13px;color:#6b7280;text-transform:uppercase;letter-spacing:.03em;"><?php esc_html_e( 'Daily Breakdown', 'yatoon-booking-system' ); ?></h3>
        <div class="yr-table-wrap">
            <table>
                <thead>
                    <tr>
                        <th><?php esc_html_e( 'Date', 'yatoon-booking-system' ); ?></th>
                        <th><?php esc_html_e( 'Bookings', 'yatoon-booking-system' ); ?></th>
                        <th><?php esc_html_e( 'Completed', 'yatoon-booking-system' ); ?></th>
                        <th><?php esc_html_e( 'No Show', 'yatoon-booking-system' ); ?></th>
                        <th><?php esc_html_e( 'Revenue', 'yatoon-booking-system' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($daily_breakdown)) : ?>
                        <tr><td colspan="5" class="yr-sub"><?php esc_html_e( 'No booking activity in this range.', 'yatoon-booking-system' ); ?></td></tr>
                    <?php else : ?>
                        <?php foreach ($daily_breakdown as $day) : ?>
                            <tr>
                                <td><strong><?php echo esc_html($day->booking_date); ?></strong></td>
                                <td><?php echo intval($day->booking_count); ?></td>
                                <td><?php echo intval($day->completed_count); ?></td>
                                <td><?php echo intval($day->no_show_count); ?></td>
                                <td>$<?php echo number_format((float) $day->total_revenue, 0); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>
</div>
<script>
jQuery(function($){
    const nonce = '<?php echo esc_js(wp_create_nonce('yatoon_admin_nonce')); ?>';
    $(document).on('click', '.yatoon-send-recall', function(){
        const $btn = $(this).prop('disabled', true).text('Sending...');
        $.post(ajaxurl, {action:'yatoon_send_recall_email', nonce, name:$btn.data('name'), email:$btn.data('email'), phone:$btn.data('phone')}, function(resp){
            $btn.text(resp.success ? 'Sent' : 'Failed');
            if (!resp.success) {
                    alert(resp.data && resp.data.message ? resp.data.message : <?php echo wp_json_encode( __( 'Could not send recall email.', 'yatoon-booking-system' ) ); ?>);
                $btn.prop('disabled', false).text('Send Recall');
            }
        }).fail(function(){
            alert('Network error.');
            $btn.prop('disabled', false).text('Send Recall');
        });
    });
});
</script>
