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

global $wpdb;

// -- Pagination & Search ---------------------------------------------------
$per_page = 30;
$page     = isset( $_GET['paged'] ) ? max( 1, intval( $_GET['paged'] ) ) : 1;
$offset   = ( $page - 1 ) * $per_page;
$search   = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';

$table    = $wpdb->prefix . 'yatoon_clients';
$bookings = $wpdb->prefix . 'yatoon_bookings';

// -- Build query -----------------------------------------------------------
$where = '';
$args  = array();
if ( $search ) {
    $like  = '%' . $wpdb->esc_like( $search ) . '%';
    $where = 'WHERE (c.customer_name LIKE %s OR c.customer_email LIKE %s OR c.customer_phone LIKE %s OR c.tags LIKE %s)';
    $args  = array( $like, $like, $like, $like );
}

$total_sql = "SELECT COUNT(*) FROM $table c $where";
$total     = $args ? $wpdb->get_var( $wpdb->prepare( $total_sql, $args ) ) : $wpdb->get_var( $total_sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$pages     = ceil( $total / $per_page );

$select_sql = "SELECT c.*,
    COUNT(b.id)      AS visit_count,
    MAX(b.start_time) AS last_visit,
    SUM(b.total_price) AS total_spent,
    SUM(CASE WHEN b.status IN ('no_show','NO_SHOW') THEN 1 ELSE 0 END) AS no_show_count,
    SUM(CASE WHEN b.payment_status IS NULL OR b.payment_status = 'unpaid' THEN 1 ELSE 0 END) AS unpaid_count,
    SUM(CASE WHEN b.start_time >= NOW() AND b.status NOT IN ('cancelled','CANCELLED_BY_CUSTOMER','CANCELLED_BY_SELLER','DECLINED','no_show','NO_SHOW') THEN 1 ELSE 0 END) AS upcoming_count
FROM $table c
LEFT JOIN $bookings b ON (b.customer_phone = c.customer_phone OR b.customer_email = c.customer_email)
    AND b.status NOT IN ('cancelled','CANCELLED_BY_CUSTOMER','CANCELLED_BY_SELLER','DECLINED')
$where
GROUP BY c.id
ORDER BY last_visit DESC, c.created_at DESC
LIMIT %d OFFSET %d";

$query_args = $args ? array_merge( $args, array( $per_page, $offset ) ) : array( $per_page, $offset );
$clients    = $wpdb->get_results( $wpdb->prepare( $select_sql, $query_args ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

$nonce = wp_create_nonce( 'yatoon_client_nonce' );
?>

<div class="wrap" id="yatoon-clients-wrap">
<h1 style="display:flex;align-items:center;gap:10px;margin-bottom:4px;">
    <span style="font-size:24px;">👤</span> Clients
    <span style="font-size:14px;color:#888;font-weight:400;margin-left:4px;"><?php echo intval($total); ?> total</span>
</h1>
<p style="color:#666;margin-top:0;">Client profiles are automatically created when a booking is made. Add notes, allergies, and preferences here.</p>

<style>
#yatoon-clients-wrap .yc-search-bar{display:flex;gap:10px;align-items:center;margin-bottom:16px;}
#yatoon-clients-wrap .yc-search-bar input{padding:7px 12px;border:1px solid #ccc;border-radius:5px;font-size:14px;width:280px;}
#yatoon-clients-wrap .yc-table-wrap{width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;}
#yatoon-clients-wrap .yc-table-wrap table{min-width:880px;}
#yatoon-clients-wrap table{border-collapse:collapse;width:100%;background:#fff;border:1px solid #ddd;border-radius:8px;overflow:hidden;}
#yatoon-clients-wrap th{background:#f8f8f8;padding:10px 14px;text-align:left;font-size:13px;color:#555;border-bottom:1px solid #eee;}
#yatoon-clients-wrap td{padding:10px 14px;font-size:14px;border-bottom:1px solid #f5f5f5;vertical-align:middle;}
#yatoon-clients-wrap tr:last-child td{border-bottom:none;}
#yatoon-clients-wrap tr:hover td{background:#fafafa;}
#yatoon-clients-wrap .yc-tag{display:inline-block;background:#f0f0f0;border-radius:20px;padding:2px 10px;font-size:12px;margin:1px 2px;color:#555;}
#yatoon-clients-wrap .yc-tag.allergy{background:#fff0f0;color:#c62828;}
#yatoon-clients-wrap .btn-edit{background:#fff;border:1px solid #ddd;border-radius:5px;padding:5px 12px;cursor:pointer;font-size:13px;}
#yatoon-clients-wrap .btn-edit:hover{background:#f0f0f0;}
#yatoon-clients-wrap .yc-visits-btn{background:none;border:0;color:#0073aa;font-weight:700;cursor:pointer;padding:0;text-decoration:underline;}
#yatoon-clients-wrap .yc-visits-btn:hover{color:#005177;}
#yatoon-clients-wrap .yc-note-preview{color:#888;font-size:12px;max-width:200px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
#yatoon-clients-wrap .yc-risk{display:inline-block;background:#fee2e2;color:#991b1b;border-radius:999px;padding:2px 8px;font-size:11px;font-weight:600;margin-left:4px;}
#yatoon-clients-wrap .yc-signal{display:inline-flex;align-items:center;gap:4px;border-radius:999px;padding:2px 8px;font-size:11px;font-weight:700;margin:2px 3px 2px 0;}
#yatoon-clients-wrap .yc-signal.vip{background:#ecfdf5;color:#047857;}
#yatoon-clients-wrap .yc-signal.warn{background:#fef2f2;color:#991b1b;}
#yatoon-clients-wrap .yc-signal.money{background:#fffbeb;color:#92400e;}
#yatoon-clients-wrap .yc-signal.next{background:#eff6ff;color:#1d4ed8;}
#yatoon-clients-wrap .yc-client-name-cell small{display:block;color:#6b7280;font-weight:500;margin-top:2px;}

/* Modal */
#yc-modal-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99999;align-items:center;justify-content:center;}
#yc-modal-overlay.open{display:flex;}
#yc-modal{background:#fff;border-radius:10px;width:92%;max-width:700px;max-height:90vh;overflow-y:auto;box-shadow:0 12px 40px rgba(0,0,0,.25);}
#yc-modal-header{padding:20px 24px 0;display:flex;justify-content:space-between;align-items:center;position:sticky;top:0;background:#fff;border-bottom:1px solid #eee;padding-bottom:16px;z-index:2;}
#yc-modal-header h2{margin:0;font-size:18px;}
#yc-modal-close{background:none;border:none;font-size:20px;cursor:pointer;color:#888;padding:4px 8px;}
#yc-modal-body{padding:20px 24px;}
.yc-form-row{margin-bottom:16px;}
.yc-form-row label{display:block;font-weight:600;font-size:13px;margin-bottom:5px;color:#444;}
.yc-form-row input,.yc-form-row textarea,.yc-form-row select{width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:5px;font-size:14px;box-sizing:border-box;}
.yc-form-row textarea{resize:vertical;min-height:80px;font-family:inherit;}
.yc-stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:18px;}
.yc-stat{border:1px solid #e5e7eb;border-radius:8px;padding:10px 12px;background:#fafafa;}
.yc-stat strong{display:block;font-size:18px;color:#111;line-height:1.2;}
.yc-stat span{display:block;font-size:11px;color:#6b7280;text-transform:uppercase;letter-spacing:.04em;margin-top:3px;}
.yc-history-table{width:100%;border-collapse:collapse;font-size:13px;margin-top:8px;}
.yc-history-table th{background:#f5f5f5;padding:7px 10px;text-align:left;color:#555;}
.yc-history-table td{padding:7px 10px;border-bottom:1px solid #f0f0f0;}
.yc-history-table tr:last-child td{border-bottom:none;}
.status-confirmed,.status-ACCEPTED{color:#2e7d32;font-weight:600;}
.status-cancelled,.status-CANCELLED_BY_CUSTOMER,.status-CANCELLED_BY_SELLER{color:#c62828;}
.status-pending{color:#e65100;}
.payment-unpaid{color:#b45309;font-weight:600;}
.payment-paid_square_pos,.payment-deposit_paid{color:#15803d;font-weight:600;}
.payment-refunded,.payment-waived{color:#6b7280;font-weight:600;}
@media (max-width: 782px){.yc-stats-grid{grid-template-columns:repeat(2,1fr);}}
</style>

<!-- Search bar -->
<form method="get" class="yc-search-bar">
    <input type="hidden" name="page" value="yatoon-clients">
    <input type="text" name="s" value="<?php echo esc_attr($search); ?>" placeholder="Search name, email, phone, tag...">
    <button type="submit" class="button">Search</button>
    <?php if ($search) : ?><a href="?page=yatoon-clients" class="button">Clear</a><?php endif; ?>
</form>

<!-- Clients table -->
<?php if ( empty($clients) ) : ?>
    <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:40px;text-align:center;color:#888;">
        <?php echo $search ? 'No clients found matching your search.' : 'No clients yet - they\'ll appear automatically after bookings are made.'; ?>
    </div>
<?php else : ?>
<div class="yc-table-wrap">
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Phone</th>
            <th>Email</th>
            <th>Visits</th>
            <th>Last Visit</th>
            <th>Total Spent</th>
            <th>Loyalty</th>
            <th>Notes / Tags</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ( $clients as $c ) :
        $tags = array_filter( array_map( 'trim', explode( ',', $c->tags ?? '' ) ) );
        $allergy_short = $c->allergies ? mb_substr( $c->allergies, 0, 40 ) . ( mb_strlen($c->allergies) > 40 ? '...' : '' ) : '';
        $visit_count = (int) ($c->visit_count ?? 0);
        $no_show_count = (int) ($c->no_show_count ?? 0);
        $unpaid_count = (int) ($c->unpaid_count ?? 0);
        $upcoming_count = (int) ($c->upcoming_count ?? 0);
        $total_spent = (float) ($c->total_spent ?? 0);
        $client_level = $total_spent >= 500 ? 'VIP' : ( $visit_count >= 5 ? 'Regular' : '' );
    ?>
        <tr data-client-id="<?php echo intval($c->id); ?>">
            <td class="yc-client-name-cell">
                <strong><?php echo esc_html( $c->customer_name ?: '-' ); ?></strong>
                <?php if ( $client_level ) : ?><small><?php echo esc_html($client_level); ?> client</small><?php endif; ?>
            </td>
            <td><?php echo esc_html( $c->customer_phone ?: '-' ); ?></td>
            <td style="font-size:13px;color:#555;"><?php echo esc_html( $c->customer_email ?: '-' ); ?></td>
            <td style="text-align:center;">
                <button type="button" class="yc-visits-btn yc-open-modal" data-id="<?php echo intval($c->id); ?>" title="View visit history"><?php echo $visit_count; ?></button>
                <div>
                    <?php if ( $client_level === 'VIP' ) : ?><span class="yc-signal vip">VIP</span><?php endif; ?>
                    <?php if ( $upcoming_count > 0 ) : ?><span class="yc-signal next"><?php echo $upcoming_count; ?> upcoming</span><?php endif; ?>
                    <?php if ( $no_show_count > 0 ) : ?><span class="yc-signal warn"><?php echo $no_show_count; ?> no-show</span><?php endif; ?>
                    <?php if ( $unpaid_count > 0 ) : ?><span class="yc-signal money"><?php echo $unpaid_count; ?> unpaid</span><?php endif; ?>
                </div>
            </td>
            <td style="font-size:13px;"><?php echo $c->last_visit ? esc_html( date('M j, Y', strtotime($c->last_visit)) ) : '-'; ?></td>
            <td>$<?php echo number_format( $total_spent, 0 ); ?></td>
            <td><?php echo intval( $c->loyalty_points ?? 0 ); ?></td>
            <td class="yc-client-meta-cell">
                <?php if ( $allergy_short ) : ?>
                    <span class="yc-tag allergy">Warning: <?php echo esc_html($allergy_short); ?></span><br>
                <?php endif; ?>
                <?php if ( ! empty( $c->preferences ) ) : ?>
                    <span class="yc-tag">Prefs saved</span>
                <?php endif; ?>
                <?php foreach ( $tags as $tag ) : ?>
                    <span class="yc-tag"><?php echo esc_html($tag); ?></span>
                <?php endforeach; ?>
                <?php if ( $c->notes ) : ?>
                    <div class="yc-note-preview"><?php echo esc_html($c->notes); ?></div>
                <?php endif; ?>
            </td>
            <td>
                <button class="btn-edit yc-open-modal"
                    data-id="<?php echo intval($c->id); ?>">✏️ Edit</button>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>

<!-- Pagination -->
<?php if ( $pages > 1 ) : ?>
<div style="margin-top:16px;display:flex;gap:6px;align-items:center;">
    <?php for ( $i = 1; $i <= $pages; $i++ ) : ?>
        <a href="?page=yatoon-clients&paged=<?php echo $i; ?><?php echo $search ? '&s='.urlencode($search) : ''; ?>"
           style="padding:5px 12px;border:1px solid <?php echo $i===$page ? '#0073aa' : '#ddd'; ?>;border-radius:4px;background:<?php echo $i===$page ? '#0073aa' : '#fff'; ?>;color:<?php echo $i===$page ? '#fff' : '#333'; ?>;text-decoration:none;font-size:13px;">
            <?php echo $i; ?>
        </a>
    <?php endfor; ?>
</div>
<?php endif; ?>
<?php endif; ?>

<!-- -- Edit Client Modal ------------------------------------------------ -->
<div id="yc-modal-overlay">
    <div id="yc-modal">
        <div id="yc-modal-header">
            <h2 id="yc-modal-title">Client Profile</h2>
            <button id="yc-modal-close">✕</button>
        </div>
        <div id="yc-modal-body">
            <div id="yc-modal-loading" style="text-align:center;padding:40px;color:#888;">Loading...</div>
            <div id="yc-modal-content" style="display:none;">

                <div class="yc-stats-grid">
                    <div class="yc-stat"><strong id="yc-stats-total">0</strong><span>Bookings</span></div>
                    <div class="yc-stat"><strong id="yc-stats-spent">$0</strong><span>Lifetime</span></div>
                    <div class="yc-stat"><strong id="yc-stats-noshow">0</strong><span>No Shows</span></div>
                    <div class="yc-stat"><strong id="yc-stats-unpaid">0</strong><span>Unpaid</span></div>
                </div>

                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px;">
                    <div class="yc-form-row" style="margin:0;">
                        <label>Name</label>
                        <input type="text" id="yc-client-name">
                    </div>
                    <div class="yc-form-row" style="margin:0;">
                        <label>Phone</label>
                        <input type="text" id="yc-client-phone" disabled style="background:#f9f9f9;color:#888;">
                    </div>
                    <div class="yc-form-row" style="margin:0;grid-column:1/-1;">
                        <label>Email</label>
                        <input type="text" id="yc-client-email" disabled style="background:#f9f9f9;color:#888;">
                    </div>
                </div>

                <div class="yc-form-row">
                    <label>Warning: Allergies / Sensitivities</label>
                    <textarea id="yc-client-allergies" rows="2" placeholder="e.g. Allergic to acrylic, sensitive to gel remover..."></textarea>
                </div>

                <div class="yc-form-row">
                    <label>👩 Preferred Staff</label>
                    <select id="yc-client-staff">
                        <option value="">No preference</option>
                    </select>
                </div>

                <div class="yc-form-row">
                    <label>* Client Preferences</label>
                    <textarea id="yc-client-preferences" rows="3" placeholder="Favorite colors, usual shape, likes/dislikes, drink preference, service notes..."></textarea>
                </div>

                <div class="yc-form-row">
                    <label>🏷️ Tags <span style="font-weight:400;color:#888;">(comma separated, e.g. VIP, Regular, Nail Art)</span></label>
                    <input type="text" id="yc-client-tags" placeholder="VIP, Regular, Gel only...">
                </div>

                <div class="yc-form-row">
                    <label>📝 Admin Notes</label>
                    <textarea id="yc-client-notes" rows="4" placeholder="Internal notes for preferences, cautions, special requests, or service reminders..."></textarea>
                </div>

                <div style="display:flex;gap:10px;align-items:center;margin-bottom:20px;">
                    <button id="yc-save-btn" class="button button-primary" style="padding:8px 24px;">💾 Save Profile</button>
                    <span id="yc-save-msg" style="font-size:13px;"></span>
                </div>

                <!-- Booking history -->
                <h3 style="margin:0 0 10px;font-size:15px;border-top:1px solid #eee;padding-top:16px;">📅 Booking History</h3>
                <div id="yc-history-wrap"></div>

            </div><!-- /yc-modal-content -->
        </div><!-- /yc-modal-body -->
    </div><!-- /yc-modal -->
</div><!-- /yc-modal-overlay -->

<input type="hidden" id="yc-current-client-id" value="">

<script>
jQuery(function($){
    const nonce = '<?php echo esc_js($nonce); ?>';
    const initialClientId = new URLSearchParams(window.location.search).get('client_id') || '';

    function escapeHtml(value) {
        return $('<div>').text(value || '').html();
    }

    function buildMetaPreview(tags, allergies, preferences, notes) {
        let html = '';
        const allergyText = (allergies || '').trim();
        if (allergyText) {
            const shortened = allergyText.length > 40 ? allergyText.slice(0, 40) + '...' : allergyText;
            html += '<span class="yc-tag allergy">Warning: ' + escapeHtml(shortened) + '</span><br>';
        }

        if ((preferences || '').trim()) {
            html += '<span class="yc-tag">Prefs saved</span>';
        }

        (tags || '').split(',').map(tag => tag.trim()).filter(Boolean).forEach(tag => {
            html += '<span class="yc-tag">' + escapeHtml(tag) + '</span>';
        });

        if ((notes || '').trim()) {
            html += '<div class="yc-note-preview">' + escapeHtml(notes.trim()) + '</div>';
        }

        return html || '-';
    }

    function updateClientRowPreview(id) {
        const $row = $('tr[data-client-id="' + id + '"]');
        if (!$row.length) {
            return;
        }

        $row.find('.yc-client-name-cell strong').text($('#yc-client-name').val().trim() || '-');
        $row.find('.yc-client-meta-cell').html(buildMetaPreview(
            $('#yc-client-tags').val(),
            $('#yc-client-allergies').val(),
            $('#yc-client-preferences').val(),
            $('#yc-client-notes').val()
        ));
    }

    // Open modal
    $(document).on('click', '.yc-open-modal', function(){
        const id = $(this).data('id');
        $('#yc-current-client-id').val(id);
        $('#yc-modal-loading').show();
        $('#yc-modal-content').hide();
        $('#yc-modal-title').text('Client Profile');
        $('#yc-modal-overlay').addClass('open');

        $.post(ajaxurl, { action: 'yatoon_get_client', nonce, id }, function(res){
            if (!res.success) { $('#yc-modal-loading').text('Error loading client.'); return; }
            const c  = res.data.client;
            const bk = res.data.bookings;
            const st = res.data.staff_list;
            const stats = res.data.stats || {};

            $('#yc-modal-title').text(c.customer_name || c.customer_phone || 'Client');
            $('#yc-client-name').val(c.customer_name || '');
            $('#yc-client-phone').val(c.customer_phone || '');
            $('#yc-client-email').val(c.customer_email || '');
            $('#yc-client-notes').val(c.notes || '');
            $('#yc-client-allergies').val(c.allergies || '');
            $('#yc-client-preferences').val(c.preferences || '');
            $('#yc-client-tags').val(c.tags || '');

            $('#yc-stats-total').text(stats.total_bookings || 0);
            $('#yc-stats-spent').text('$' + parseFloat(stats.lifetime_value || 0).toFixed(0));
            $('#yc-stats-noshow').text(stats.no_show_count || 0);
            $('#yc-stats-unpaid').text(stats.unpaid_count || 0);

            // Populate staff dropdown
            let staffOpts = '<option value="">No preference</option>';
            st.forEach(s => {
                const sel = c.preferred_staff == s.id ? ' selected' : '';
                staffOpts += `<option value="${s.id}"${sel}>${s.name}</option>`;
            });
            $('#yc-client-staff').html(staffOpts);

            // Booking history
            if (!bk || !bk.length) {
                $('#yc-history-wrap').html('<p style="color:#888;font-size:13px;">No booking history yet.</p>');
            } else {
                let rows = bk.map(b => {
                    const dt   = b.start_time ? new Date(b.start_time).toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'}) : '-';
                    const time = b.start_time ? new Date(b.start_time).toLocaleTimeString('en-US',{hour:'numeric',minute:'2-digit'}) : '';
                    const st_cls = 'status-' + (b.status||'');
                    return `<tr>
                        <td>${dt} ${time}</td>
                        <td>${b.service_name||'-'}</td>
                        <td>${b.staff_name||'-'}</td>
                        <td class="${st_cls}">${b.status||'-'}</td>
                        <td class="payment-${b.payment_status||'unpaid'}">${b.payment_status||'unpaid'}</td>
                        <td>$${parseFloat(b.total_price||0).toFixed(2)}</td>
                        <td style="color:#888;font-size:12px;">${b.notes||''}</td>
                    </tr>`;
                }).join('');
                $('#yc-history-wrap').html(`
                    <table class="yc-history-table">
                        <thead><tr><th>Date</th><th>Service</th><th>Staff</th><th>Status</th><th>Payment</th><th>Price</th><th>Notes</th></tr></thead>
                        <tbody>${rows}</tbody>
                    </table>`);
            }

            $('#yc-modal-loading').hide();
            $('#yc-modal-content').show();
            $('#yc-save-msg').text('');
        });
    });

    // Close modal
    $('#yc-modal-close, #yc-modal-overlay').on('click', function(e){
        if (e.target.id === 'yc-modal-overlay' || e.target.id === 'yc-modal-close') {
            $('#yc-modal-overlay').removeClass('open');
        }
    });

    // Save
    $('#yc-save-btn').on('click', function(){
        const id = $('#yc-current-client-id').val();
        const btn = $(this).prop('disabled', true).text('Saving...');
        $.post(ajaxurl, {
            action:          'yatoon_save_client_notes',
            nonce,
            id,
            customer_name:   $('#yc-client-name').val(),
            notes:           $('#yc-client-notes').val(),
            allergies:       $('#yc-client-allergies').val(),
            preferences:     $('#yc-client-preferences').val(),
            preferred_staff: $('#yc-client-staff').val(),
            tags:            $('#yc-client-tags').val(),
        }, function(res){
            btn.prop('disabled', false).text('💾 Save Profile');
            if (res.success) {
                updateClientRowPreview(id);
                $('#yc-save-msg').text('OK Saved!').css('color','#2e7d32');
                setTimeout(() => { $('#yc-save-msg').text(''); }, 3000);
            } else {
                $('#yc-save-msg').text('❌ Error saving.').css('color','#c62828');
            }
        });
    });

    if (initialClientId) {
        const $initialClient = $('.yc-open-modal[data-id="' + initialClientId + '"]').first();
        if ($initialClient.length) {
            $initialClient.trigger('click');
        }
    }
});
</script>
</div>
