<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
if ( ! defined( 'ABSPATH' ) ) exit;
$nonce = wp_create_nonce( 'yatoon_admin_nonce' );
$loyalty_enabled = get_option( 'yatoon_loyalty_enabled', '0' ) === '1';
$earn_rate = (float) get_option( 'yatoon_loyalty_earn_rate', 1 );
?>
<div class="wrap sbs-admin-page" id="yatoon-loyalty-wrap">
    <h1>Loyalty</h1>
    <p class="yatoon-admin-subtitle">Clients earn points automatically when a visit is paid, and can redeem them for a discount at checkout - no extra sign-up required.</p>

    <style>
    #yatoon-loyalty-wrap .yl-card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:20px;margin-bottom:20px;box-shadow:0 1px 4px rgba(15,23,42,.05);}
    #yatoon-loyalty-wrap .yl-card h2{margin:0 0 4px;font-size:16px;}
    #yatoon-loyalty-wrap .yl-card p.desc{color:#6b7280;font-size:13px;margin:0 0 16px;}
    #yatoon-loyalty-wrap .yl-row{display:flex;align-items:center;gap:14px;margin-bottom:14px;flex-wrap:wrap;}
    #yatoon-loyalty-wrap .yl-row label{font-weight:600;font-size:13px;min-width:140px;}
    #yatoon-loyalty-wrap input[type=number], #yatoon-loyalty-wrap input[type=text]{border:1px solid #d1d5db;border-radius:6px;padding:7px 10px;font-size:13.5px;}
    #yatoon-loyalty-wrap .yl-reward-row{display:flex;align-items:center;gap:12px;padding:12px;border:1px solid #e5e7eb;border-radius:10px;margin-bottom:10px;background:#fafafa;}
    #yatoon-loyalty-wrap .yl-reward-row .yl-reward-main{flex:1;}
    #yatoon-loyalty-wrap .yl-reward-name{font-weight:700;font-size:14px;}
    #yatoon-loyalty-wrap .yl-reward-detail{color:#6b7280;font-size:12.5px;margin-top:2px;}
    #yatoon-loyalty-wrap table.yl-table{width:100%;border-collapse:collapse;font-size:13px;}
    #yatoon-loyalty-wrap table.yl-table th{text-align:left;padding:8px;border-bottom:2px solid #e5e7eb;color:#6b7280;font-size:11.5px;text-transform:uppercase;letter-spacing:.03em;}
    #yatoon-loyalty-wrap table.yl-table td{padding:8px;border-bottom:1px solid #f0f0f1;}
    #yatoon-loyalty-wrap .yl-pos{color:#166534;font-weight:700;}
    #yatoon-loyalty-wrap .yl-neg{color:#b91c1c;font-weight:700;}
    #yatoon-loyalty-wrap .yl-toggle-off{opacity:.4;pointer-events:none;}
    /* Modal */
    #yl-reward-modal-overlay{display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:100000;align-items:center;justify-content:center;padding:20px;}
    #yl-reward-modal-overlay.is-open{display:flex;}
    #yl-reward-modal{background:#fff;border-radius:14px;max-width:440px;width:100%;padding:24px;position:relative;}
    #yl-reward-modal h2{margin:0 0 16px;font-size:17px;}
    #yl-reward-modal label{display:block;font-weight:700;font-size:12.5px;color:#374151;margin:12px 0 5px;}
    #yl-reward-modal input, #yl-reward-modal select{width:100%;box-sizing:border-box;border:1px solid #d1d5db;border-radius:8px;padding:9px 11px;font-size:13.5px;}
    #yl-reward-modal-close{position:absolute;top:16px;right:16px;background:none;border:none;font-size:22px;cursor:pointer;color:#9ca3af;}
    </style>

    <div class="yl-card">
        <h2>Program Settings</h2>
        <p class="desc">Points are tracked against the same phone number/email already used for bookings - clients don't need a separate account.</p>
        <div class="yl-row">
            <label><input type="checkbox" id="yl-enabled" <?php checked( $loyalty_enabled ); ?>> Enable loyalty points</label>
        </div>
        <div class="yl-row<?php echo $loyalty_enabled ? '' : ' yl-toggle-off'; ?>" id="yl-rate-row">
            <label for="yl-earn-rate">Points earned</label>
            <input type="number" id="yl-earn-rate" min="0" step="0.1" value="<?php echo esc_attr( $earn_rate ); ?>" style="width:80px;">
            <span>points per $1 spent (awarded automatically once a visit is marked paid)</span>
        </div>
        <button type="button" class="button button-primary" id="yl-save-settings">Save Settings</button>
        <span id="yl-settings-msg" style="margin-left:10px;color:#16a34a;font-size:13px;"></span>
    </div>

    <div class="yl-card">
        <div style="display:flex;justify-content:space-between;align-items:center;">
            <div>
                <h2>Rewards</h2>
                <p class="desc" style="margin-bottom:0;">What clients can redeem their points for. Shown to staff at Checkout once a client has enough points.</p>
            </div>
            <button type="button" class="button button-primary" id="yl-add-reward-btn">+ New Reward</button>
        </div>
        <div id="yl-reward-list" style="margin-top:16px;">
            <?php if ( empty( $rewards ) ) : ?>
                <p style="color:#9ca3af;text-align:center;padding:20px 0;">No rewards yet. Try: "$10 off after 100 points."</p>
            <?php else : foreach ( $rewards as $r ) :
                $discount_label = $r->discount_type === 'percent' ? ( (float) $r->discount_value . '% off' ) : ( '$' . number_format( (float) $r->discount_value, 2 ) . ' off' );
            ?>
            <div class="yl-reward-row" data-reward='<?php echo esc_attr( wp_json_encode( $r ) ); ?>'>
                <div class="yl-reward-main">
                    <div class="yl-reward-name"><?php echo esc_html( $r->name ); ?></div>
                    <div class="yl-reward-detail"><?php echo intval( $r->points_required ); ?> points -> <?php echo esc_html( $discount_label ); ?><?php echo $r->is_enabled ? '' : ' - disabled'; ?></div>
                </div>
                <button type="button" class="button yl-edit-reward">Edit</button>
                <button type="button" class="button yl-delete-reward" style="color:#dc2626;">Delete</button>
            </div>
            <?php endforeach; endif; ?>
        </div>
    </div>

    <div class="yl-card">
        <h2>Top Point Balances</h2>
        <p class="desc">Your most loyal clients right now.</p>
        <table class="yl-table">
            <thead><tr><th>Client</th><th>Contact</th><th>Points</th></tr></thead>
            <tbody>
                <?php if ( empty( $top_clients ) ) : ?>
                    <tr><td colspan="3" style="text-align:center;color:#9ca3af;padding:16px;">No point balances yet.</td></tr>
                <?php else : foreach ( $top_clients as $c ) : ?>
                    <tr>
                        <td><?php echo esc_html( $c->customer_name ?: '(no name)' ); ?></td>
                        <td><?php echo esc_html( $c->customer_phone ?: $c->customer_email ); ?></td>
                        <td><strong><?php echo intval( $c->loyalty_points ); ?></strong></td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

    <div class="yl-card">
        <h2>Recent Activity</h2>
        <table class="yl-table">
            <thead><tr><th>When</th><th>Client</th><th>Points</th><th>Reason</th></tr></thead>
            <tbody>
                <?php if ( empty( $recent_activity ) ) : ?>
                    <tr><td colspan="4" style="text-align:center;color:#9ca3af;padding:16px;">No activity yet.</td></tr>
                <?php else : foreach ( $recent_activity as $log ) : ?>
                    <tr>
                        <td><?php echo esc_html( mysql2date( 'M j, g:ia', $log->created_at ) ); ?></td>
                        <td><?php echo esc_html( $log->customer_name ?: ( $log->customer_phone ?: $log->customer_email ) ); ?></td>
                        <td class="<?php echo $log->points_change >= 0 ? 'yl-pos' : 'yl-neg'; ?>"><?php echo ( $log->points_change >= 0 ? '+' : '' ) . intval( $log->points_change ); ?></td>
                        <td><?php echo esc_html( $log->note ?: ucfirst( str_replace( '_', ' ', $log->reason ) ) ); ?></td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div id="yl-reward-modal-overlay">
    <div id="yl-reward-modal">
        <button type="button" id="yl-reward-modal-close">&times;</button>
        <h2 id="yl-reward-modal-title">New Reward</h2>
        <input type="hidden" id="yl-field-id" value="0">
        <label for="yl-field-name">Reward name</label>
        <input type="text" id="yl-field-name" placeholder="e.g. $10 off">
        <label for="yl-field-points">Points required</label>
        <input type="number" id="yl-field-points" min="1" value="100">
        <label for="yl-field-discount-type">Discount type</label>
        <select id="yl-field-discount-type">
            <option value="percent">Percent off</option>
            <option value="fixed">Fixed amount off</option>
        </select>
        <label for="yl-field-discount-value">Discount value</label>
        <input type="number" id="yl-field-discount-value" min="0" step="0.01" value="10">
        <div style="margin-top:20px;display:flex;justify-content:flex-end;gap:10px;">
            <button type="button" class="button" id="yl-reward-cancel">Cancel</button>
            <button type="button" class="button button-primary" id="yl-reward-save">Save Reward</button>
        </div>
    </div>
</div>

<script>
jQuery(function($) {
    const nonce = '<?php echo esc_js( $nonce ); ?>';

    $('#yl-enabled').on('change', function() {
        $('#yl-rate-row').toggleClass('yl-toggle-off', !this.checked);
    });

    $('#yl-save-settings').on('click', function() {
        const $btn = $(this);
        $btn.prop('disabled', true);
        $.post(ajaxurl, {
            action: 'yatoon_save_loyalty_settings',
            nonce: nonce,
            enabled: $('#yl-enabled').is(':checked') ? 1 : 0,
            earn_rate: $('#yl-earn-rate').val(),
        }, function(resp) {
            $btn.prop('disabled', false);
            $('#yl-settings-msg').text(resp.success ? 'Saved.' : 'Could not save.');
            setTimeout(() => $('#yl-settings-msg').text(''), 2500);
        });
    });

    function openRewardModal(reward) {
        $('#yl-field-id').val(reward ? reward.id : 0);
        $('#yl-reward-modal-title').text(reward ? 'Edit Reward' : 'New Reward');
        $('#yl-field-name').val(reward ? reward.name : '');
        $('#yl-field-points').val(reward ? reward.points_required : 100);
        $('#yl-field-discount-type').val(reward ? reward.discount_type : 'percent');
        $('#yl-field-discount-value').val(reward ? reward.discount_value : 10);
        $('#yl-reward-modal-overlay').addClass('is-open');
    }
    function closeRewardModal() { $('#yl-reward-modal-overlay').removeClass('is-open'); }

    $('#yl-add-reward-btn').on('click', () => openRewardModal(null));
    $('#yl-reward-modal-close, #yl-reward-cancel').on('click', closeRewardModal);
    $('#yl-reward-modal-overlay').on('click', function(e) { if (e.target === this) closeRewardModal(); });

    $(document).on('click', '.yl-edit-reward', function() {
        openRewardModal($(this).closest('.yl-reward-row').data('reward'));
    });

    $('#yl-reward-save').on('click', function() {
        const $btn = $(this);
        $btn.prop('disabled', true);
        $.post(ajaxurl, {
            action: 'yatoon_save_loyalty_reward',
            nonce: nonce,
            id: $('#yl-field-id').val(),
            name: $('#yl-field-name').val(),
            points_required: $('#yl-field-points').val(),
            discount_type: $('#yl-field-discount-type').val(),
            discount_value: $('#yl-field-discount-value').val(),
        }, function(resp) {
            $btn.prop('disabled', false);
            if (resp.success) {
                location.reload();
            } else {
                alert((resp.data && resp.data.message) || 'Could not save.');
            }
        });
    });

    $(document).on('click', '.yl-delete-reward', function() {
        if (!confirm('Delete this reward?')) return;
        const $row = $(this).closest('.yl-reward-row');
        $.post(ajaxurl, {
            action: 'yatoon_delete_loyalty_reward',
            nonce: nonce,
            id: $row.data('reward').id,
        }, function(resp) {
            if (resp.success) $row.remove();
        });
    });
});
</script>
