<?php
// phpcs:ignoreFile
if (!defined('ABSPATH')) { exit; }

global $wpdb;
$table   = $wpdb->prefix . 'yatoon_reviews';
$filter  = isset($_GET['status']) ? sanitize_key($_GET['status']) : 'all';
$is_pro  = class_exists('YATOON_License') && YATOON_License::is_pro();

$where   = $filter !== 'all' ? $wpdb->prepare("WHERE status = %s", $filter) : '';
$reviews = $wpdb->get_results("SELECT * FROM $table $where ORDER BY created_at DESC LIMIT 100");

$counts = $wpdb->get_results("SELECT status, COUNT(*) as n FROM $table GROUP BY status");
$count_map = array('all' => 0);
foreach ((array)$counts as $row) {
    $count_map[$row->status] = intval($row->n);
    $count_map['all'] += intval($row->n);
}

$avg = $wpdb->get_var("SELECT AVG(rating) FROM $table WHERE status = 'approved'");
$avg = $avg ? round(floatval($avg), 1) : 0;
$total_approved = $count_map['approved'] ?? 0;

$nonce = wp_create_nonce('yatoon_admin_nonce');
?>
<div class="wrap" id="yatoon-reviews-wrap">
<h1 style="margin-bottom:4px;">Customer Reviews</h1>
<p style="color:#6b7280;margin-top:0;">Manage star ratings collected after appointments. Use <code>[yatoon_reviews]</code> to display them on your site <?php echo $is_pro ? '' : '(Pro)'; ?>.</p>

<style>
#yatoon-reviews-wrap *{box-sizing:border-box;}
#yatoon-reviews-wrap .yr-kpis{display:flex;gap:12px;margin:16px 0;}
#yatoon-reviews-wrap .yr-kpi{background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:14px 18px;min-width:120px;}
#yatoon-reviews-wrap .yr-kpi strong{display:block;font-size:26px;font-weight:700;color:#111827;line-height:1;}
#yatoon-reviews-wrap .yr-kpi span{font-size:12px;color:#9ca3af;text-transform:uppercase;letter-spacing:.04em;}
#yatoon-reviews-wrap .yr-tabs{display:flex;gap:4px;margin-bottom:16px;border-bottom:1px solid #e5e7eb;padding-bottom:0;}
#yatoon-reviews-wrap .yr-tab{padding:8px 16px;font-size:13px;color:#6b7280;text-decoration:none;border-bottom:2px solid transparent;margin-bottom:-1px;}
#yatoon-reviews-wrap .yr-tab.active{color:#111827;font-weight:600;border-bottom-color:#111827;}
#yatoon-reviews-wrap .yr-tab:hover{color:#111827;}
#yatoon-reviews-wrap .yr-list{display:flex;flex-direction:column;gap:10px;}
#yatoon-reviews-wrap .yr-card{background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:16px 18px;display:grid;grid-template-columns:auto 1fr auto;gap:16px;align-items:start;}
#yatoon-reviews-wrap .yr-card.featured{border-color:#f59e0b;border-width:1.5px;}
#yatoon-reviews-wrap .yr-avatar{width:44px;height:44px;border-radius:50%;background:#f3f4f6;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:16px;color:#6b7280;flex-shrink:0;}
#yatoon-reviews-wrap .yr-stars{color:#f59e0b;font-size:16px;letter-spacing:1px;}
#yatoon-reviews-wrap .yr-name{font-weight:600;font-size:14px;color:#111827;}
#yatoon-reviews-wrap .yr-meta{font-size:12px;color:#9ca3af;margin-top:2px;}
#yatoon-reviews-wrap .yr-text{font-size:14px;color:#374151;line-height:1.6;margin-top:8px;}
#yatoon-reviews-wrap .yr-actions{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px;}
#yatoon-reviews-wrap .yr-btn{font-size:12px;padding:4px 10px;border-radius:6px;border:1px solid #e5e7eb;background:#fff;cursor:pointer;color:#374151;}
#yatoon-reviews-wrap .yr-btn:hover{background:#f9fafb;}
#yatoon-reviews-wrap .yr-btn.approve{border-color:#16a34a;color:#16a34a;}
#yatoon-reviews-wrap .yr-btn.reject{border-color:#dc2626;color:#dc2626;}
#yatoon-reviews-wrap .yr-btn.feature{border-color:#f59e0b;color:#92400e;}
#yatoon-reviews-wrap .yr-badge{display:inline-block;font-size:11px;padding:1px 8px;border-radius:20px;font-weight:600;}
#yatoon-reviews-wrap .badge-approved{background:#dcfce7;color:#166534;}
#yatoon-reviews-wrap .badge-submitted{background:#fef9c3;color:#854d0e;}
#yatoon-reviews-wrap .badge-rejected{background:#fee2e2;color:#991b1b;}
#yatoon-reviews-wrap .badge-pending{background:#f3f4f6;color:#6b7280;}
#yatoon-reviews-wrap .yr-actions-col{display:flex;flex-direction:column;align-items:flex-end;gap:6px;min-width:80px;}
#yatoon-reviews-wrap .yr-empty{background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:40px;text-align:center;color:#9ca3af;font-size:14px;}
#yatoon-reviews-wrap .yr-pro-banner{background:#f5f3ff;border:1px solid #c4b5fd;border-radius:10px;padding:14px 18px;margin-top:20px;display:flex;align-items:center;gap:12px;}
#yatoon-reviews-wrap .yr-shortcode{background:#f3f4f6;border-radius:6px;padding:4px 10px;font-family:monospace;font-size:13px;color:#374151;}
</style>

<div class="yr-kpis">
    <div class="yr-kpi">
        <strong><?php echo esc_html($avg ?: '-'); ?></strong>
        <span>Avg rating</span>
    </div>
    <div class="yr-kpi">
        <strong style="color:#16a34a;"><?php echo esc_html($total_approved); ?></strong>
        <span>Approved</span>
    </div>
    <div class="yr-kpi">
        <strong style="color:#d97706;"><?php echo esc_html($count_map['submitted'] ?? 0); ?></strong>
        <span>Awaiting review</span>
    </div>
    <div class="yr-kpi">
        <strong><?php echo esc_html($count_map['all']); ?></strong>
        <span>Total collected</span>
    </div>
</div>

<div class="yr-tabs">
    <?php
    $tab_labels = array('all' => 'All', 'submitted' => 'Awaiting', 'approved' => 'Approved', 'rejected' => 'Rejected', 'pending' => 'Not yet submitted');
    foreach ($tab_labels as $slug => $label):
        $n = $count_map[$slug] ?? 0;
        $active = $filter === $slug ? 'active' : '';
    ?>
    <a class="yr-tab <?php echo $active; ?>" href="?page=yatoon-reviews&status=<?php echo esc_attr($slug); ?>">
        <?php echo esc_html($label); ?> <?php if ($n) echo '<span style="color:#9ca3af;">(' . $n . ')</span>'; ?>
    </a>
    <?php endforeach; ?>
</div>

<div class="yr-list">
<?php if (empty($reviews)): ?>
    <div class="yr-empty">
        <?php if ($filter === 'all'): ?>
            No reviews collected yet. Rating request emails are sent automatically after each appointment.
        <?php else: ?>
            No reviews in this category.
        <?php endif; ?>
    </div>
<?php else: foreach ($reviews as $r):
    $rating      = max(0, min(5, intval($r->rating)));
    $stars_full  = str_repeat('*', $rating) . str_repeat('-', 5 - $rating);
    $initials    = strtoupper(substr($r->customer_name ?: 'G', 0, 1));
    $date_str    = $r->submitted_at ? date('M j, Y', strtotime($r->submitted_at)) : date('M j, Y', strtotime($r->created_at));
?>
<div class="yr-card <?php echo $r->is_featured ? 'featured' : ''; ?>" id="yr-card-<?php echo esc_attr($r->id); ?>">
    <div class="yr-avatar"><?php echo esc_html($initials); ?></div>
    <div>
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
            <span class="yr-name"><?php echo esc_html($r->customer_name ?: 'Guest'); ?></span>
            <span class="yr-stars"><?php echo esc_html($stars_full); ?></span>
            <span class="yr-badge badge-<?php echo esc_attr($r->status); ?>"><?php echo esc_html(ucfirst($r->status)); ?></span>
            <?php if ($r->is_featured): ?><span class="yr-badge" style="background:#fef3c7;color:#92400e;">* Featured</span><?php endif; ?>
        </div>
        <div class="yr-meta">
            <?php echo esc_html($r->service_name ?: ''); ?>
            <?php if ($r->service_name && $date_str) echo ' · '; ?>
            <?php echo esc_html($date_str); ?>
        </div>
        <?php if ($r->review_text): ?>
            <div class="yr-text"><?php echo esc_html($r->review_text); ?></div>
        <?php else: ?>
            <div class="yr-text" style="color:#9ca3af;font-style:italic;">No written review.</div>
        <?php endif; ?>
        <div class="yr-actions">
            <?php if ($r->status !== 'approved'): ?>
                <button class="yr-btn approve" onclick="yrAction(<?php echo $r->id; ?>,'approve',this)">Approve</button>
            <?php endif; ?>
            <?php if ($r->status !== 'rejected'): ?>
                <button class="yr-btn reject" onclick="yrAction(<?php echo $r->id; ?>,'reject',this)">Reject</button>
            <?php endif; ?>
            <button class="yr-btn feature" onclick="yrAction(<?php echo $r->id; ?>,'feature',this)"><?php echo $r->is_featured ? 'Unfeature' : 'Feature'; ?></button>
            <button class="yr-btn" style="color:#dc2626;" onclick="if(confirm('Delete this review?'))yrAction(<?php echo $r->id; ?>,'delete',this)">Delete</button>
        </div>
    </div>
    <div class="yr-actions-col">
        <span style="font-size:12px;color:#9ca3af;">#<?php echo esc_html($r->id); ?></span>
    </div>
</div>
<?php endforeach; endif; ?>
</div>

<?php if (!$is_pro): ?>
<div class="yr-pro-banner">
    <span style="font-size:20px;">*</span>
    <div style="flex:1;">
        <strong>Display reviews on your website</strong> - add <span class="yr-shortcode">[yatoon_reviews]</span> to any page to show approved reviews as a beautiful card grid.
    </div>
    <a href="<?php echo esc_url(admin_url('admin.php?page=yatoon-booking-system-pricing')); ?>" style="background:#7c3aed;color:#fff;padding:8px 18px;border-radius:8px;text-decoration:none;font-size:13px;font-weight:600;white-space:nowrap;">Activate license</a>
</div>
<?php endif; ?>

</div>

<script>
function yrAction(id, action, btn) {
    btn.disabled = true;
    btn.textContent = '...';
    jQuery.post(ajaxurl, {
        action: 'yatoon_review_action',
        nonce: '<?php echo esc_js($nonce); ?>',
        id: id,
        review_action: action
    }, function(r) {
        if (r.success) {
            if (action === 'delete') {
                document.getElementById('yr-card-' + id).remove();
            } else {
                location.reload();
            }
        } else {
            btn.disabled = false;
            btn.textContent = 'Error';
        }
    });
}
</script>
