<?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')
);
?>

<div class="wrap" id="yatoon-reports-wrap">
    <h1>Reports</h1>
    <p style="color:#6b7280;margin-top:0;">Simple business reporting for bookings, staff performance, service demand, and payment follow-up.</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;}}
    </style>

    <form method="get" class="yr-filter">
        <input type="hidden" name="page" value="yatoon-reports">
        <div>
            <label for="yr-date-from">From</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">Apply</button>
            <a class="button" href="<?php echo esc_url(admin_url('admin.php?page=yatoon-reports')); ?>">Last 30 Days</a>
            <a class="button" href="<?php echo esc_url($export_url); ?>">Export CSV</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>Today at a Glance</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>Top Services</h2>
            <div class="yr-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>Service</th>
                            <th>Bookings</th>
                            <th>Completed</th>
                            <th>Revenue</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($top_services)) : ?>
                            <tr><td colspan="4" class="yr-sub">No service data for this range.</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>Staff Performance</h2>
            <div class="yr-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>Staff</th>
                            <th>Bookings</th>
                            <th>No Show</th>
                            <th>Revenue</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($staff_performance)) : ?>
                            <tr><td colspan="4" class="yr-sub">No staff data for this range.</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>Staff Utilization</h2>
        <div class="yr-table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Staff</th>
                        <th>Booked Hours</th>
                        <th>Utilization</th>
                        <th>Bookings</th>
                        <th>Revenue</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($staff_utilization)) : ?>
                        <tr><td colspan="5" class="yr-sub">No staff utilization data for this range.</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>Upcoming This Week</h2>
            <div class="yr-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>Client</th>
                            <th>Appointment</th>
                            <th>Staff</th>
                            <th>Price</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($upcoming_bookings)) : ?>
                            <tr><td colspan="4" class="yr-sub">No upcoming bookings in the next 7 days.</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>Needs Follow-Up</h2>
            <div class="yr-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>Type</th>
                            <th>Client</th>
                            <th>Detail</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($unpaid_followups) && empty($at_risk_clients)) : ?>
                            <tr><td colspan="4" class="yr-sub">No payment or rebooking follow-ups right now.</td></tr>
                        <?php else : ?>
                            <?php foreach ((array) $unpaid_followups as $row) : ?>
                                <tr>
                                    <td><span class="yr-pill">Unpaid</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))); ?>">Open</a></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php foreach ((array) $at_risk_clients as $row) : ?>
                                <tr>
                                    <td><span class="yr-pill">Rebook</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); ?>">Email</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); ?>">Send Recall</button>
                                        <?php elseif (!empty($row->customer_phone)) : ?>
                                            <a class="button button-small" href="tel:<?php echo esc_attr($row->customer_phone); ?>">Call</a>
                                        <?php else : ?>
                                            <span class="yr-sub">No contact</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </div>

    <section class="yr-panel" style="margin-top:16px;">
        <h2>Daily Breakdown</h2>
        <div class="yr-table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Bookings</th>
                        <th>Completed</th>
                        <th>No Show</th>
                        <th>Revenue</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($daily_breakdown)) : ?>
                        <tr><td colspan="5" class="yr-sub">No booking activity in this range.</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 : 'Could not send recall email.');
                $btn.prop('disabled', false).text('Send Recall');
            }
        }).fail(function(){
            alert('Network error.');
            $btn.prop('disabled', false).text('Send Recall');
        });
    });
});
</script>
