<?php

if (!defined('ABSPATH')) { exit; }

global $wpdb;
$table_gc = $wpdb->prefix . 'yatoon_gift_cards';
$table_tx = $wpdb->prefix . 'yatoon_gift_card_transactions';

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

$stats = $wpdb->get_row("SELECT
    COUNT(*) AS total,
    SUM(initial_amount) AS total_sold,
    SUM(balance) AS total_balance,
    SUM(initial_amount - balance) AS total_redeemed
    FROM $table_gc WHERE status != 'void'");

$nonce = wp_create_nonce('yatoon_gift_cards');
?>
<div class="wrap" id="yatoon-gc-wrap">
<h1><?php esc_html_e( 'Gift Cards 🎁', 'yatoon-booking-system' ); ?></h1>
<p style="color:#6b7280;margin-top:0;"><?php esc_html_e( 'Create and manage gift cards. Customers redeem codes at checkout.', 'yatoon-booking-system' ); ?></p>

<style>
#yatoon-gc-wrap *{box-sizing:border-box;}
#yatoon-gc-wrap .ygc-layout{display:grid;grid-template-columns:1fr 320px;gap:20px;margin-top:16px;}
#yatoon-gc-wrap .ygc-kpis{display:flex;gap:12px;margin-bottom:16px;}
#yatoon-gc-wrap .ygc-kpi{background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:14px 18px;flex:1;}
#yatoon-gc-wrap .ygc-kpi strong{display:block;font-size:22px;font-weight:700;color:#111827;line-height:1.2;}
#yatoon-gc-wrap .ygc-kpi span{font-size:12px;color:#9ca3af;text-transform:uppercase;letter-spacing:.04em;}
#yatoon-gc-wrap .ygc-panel{background:#fff;border:1px solid #e5e7eb;border-radius:10px;overflow:hidden;}
#yatoon-gc-wrap .ygc-head{padding:13px 18px;border-bottom:1px solid #f3f4f6;display:flex;align-items:center;justify-content:space-between;}
#yatoon-gc-wrap .ygc-head h2{margin:0;font-size:14px;font-weight:600;color:#111827;}
#yatoon-gc-wrap .ygc-body{padding:18px;}
#yatoon-gc-wrap table{width:100%;border-collapse:collapse;font-size:13px;}
#yatoon-gc-wrap th{background:#f9fafb;padding:9px 14px;text-align:left;font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:.04em;border-bottom:1px solid #f3f4f6;}
#yatoon-gc-wrap td{padding:11px 14px;border-bottom:1px solid #f9fafb;vertical-align:top;}
#yatoon-gc-wrap tr:last-child td{border-bottom:none;}
#yatoon-gc-wrap .ygc-code{font-family:monospace;font-size:13px;font-weight:700;color:#111827;letter-spacing:.05em;background:#f3f4f6;padding:3px 8px;border-radius:6px;}
#yatoon-gc-wrap .ygc-badge{display:inline-block;font-size:11px;padding:2px 8px;border-radius:20px;font-weight:600;}
#yatoon-gc-wrap .badge-active{background:#dcfce7;color:#166534;}
#yatoon-gc-wrap .badge-used{background:#f3f4f6;color:#6b7280;}
#yatoon-gc-wrap .badge-void{background:#fee2e2;color:#991b1b;}
#yatoon-gc-wrap .badge-expired{background:#fef3c7;color:#92400e;}
#yatoon-gc-wrap .ygc-form-row{margin-bottom:13px;}
#yatoon-gc-wrap .ygc-form-row label{display:block;font-size:12px;font-weight:600;color:#374151;margin-bottom:4px;}
#yatoon-gc-wrap .ygc-form-row input,
#yatoon-gc-wrap .ygc-form-row textarea,
#yatoon-gc-wrap .ygc-form-row select{width:100%;padding:7px 10px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;font-family:inherit;}
#yatoon-gc-wrap .ygc-form-row textarea{min-height:60px;resize:vertical;}
#yatoon-gc-wrap .ygc-hint{font-size:11px;color:#9ca3af;margin-top:3px;}
#yatoon-gc-wrap .ygc-tabs{display:flex;gap:4px;margin-bottom:14px;border-bottom:1px solid #e5e7eb;}
#yatoon-gc-wrap .ygc-tab{padding:7px 14px;font-size:13px;color:#6b7280;text-decoration:none;border-bottom:2px solid transparent;margin-bottom:-1px;}
#yatoon-gc-wrap .ygc-tab.active{color:#111827;font-weight:600;border-bottom-color:#111827;}
#yatoon-gc-wrap .ygc-empty{padding:32px;text-align:center;color:#9ca3af;font-size:13px;}
#yatoon-gc-wrap .ygc-balance-bar{height:5px;background:#e5e7eb;border-radius:3px;margin-top:4px;overflow:hidden;}
#yatoon-gc-wrap .ygc-balance-fill{height:100%;background:#16a34a;border-radius:3px;}
@media(max-width:900px){#yatoon-gc-wrap .ygc-layout{grid-template-columns:1fr;}}
</style>

<!-- KPIs -->
<div class="ygc-kpis">
    <div class="ygc-kpi"><strong><?php echo esc_html($stats->total ?? 0); ?></strong><span><?php esc_html_e( 'Cards issued', 'yatoon-booking-system' ); ?></span></div>
    <div class="ygc-kpi"><strong>$<?php echo number_format(floatval($stats->total_sold ?? 0), 2); ?></strong><span><?php esc_html_e( 'Total sold', 'yatoon-booking-system' ); ?></span></div>
    <div class="ygc-kpi"><strong style="color:#16a34a;">$<?php echo number_format(floatval($stats->total_balance ?? 0), 2); ?></strong><span><?php esc_html_e( 'Outstanding balance', 'yatoon-booking-system' ); ?></span></div>
    <div class="ygc-kpi"><strong>$<?php echo number_format(floatval($stats->total_redeemed ?? 0), 2); ?></strong><span><?php esc_html_e( 'Redeemed', 'yatoon-booking-system' ); ?></span></div>
</div>

<div class="ygc-layout">

<!-- Left: card list -->
<div>
    <div class="ygc-tabs">
        <?php foreach(array('all'=>'All','active'=>'Active','used'=>'Used Up','void'=>'Voided','expired'=>'Expired') as $slug=>$label):
            $active = $filter === $slug ? 'active' : ''; ?>
        <a class="ygc-tab <?php echo esc_attr( $active ); ?>" href="?page=yatoon-gift-cards&status=<?php echo esc_attr($slug);?>"><?php echo esc_html($label);?></a>
        <?php endforeach;?>
    </div>

    <div class="ygc-panel">
        <?php if (empty($cards)): ?>
        <div class="ygc-empty"><?php esc_html_e( 'No gift cards yet. Create one using the form on the right.', 'yatoon-booking-system' ); ?></div>
        <?php else: ?>
        <table>
            <thead><tr><th><?php esc_html_e( 'Code', 'yatoon-booking-system' ); ?></th><th><?php esc_html_e( 'Recipient', 'yatoon-booking-system' ); ?></th><th><?php esc_html_e( 'Balance', 'yatoon-booking-system' ); ?></th><th><?php esc_html_e( 'Expires', 'yatoon-booking-system' ); ?></th><th><?php esc_html_e( 'Status', 'yatoon-booking-system' ); ?></th><th><?php esc_html_e( 'Actions', 'yatoon-booking-system' ); ?></th></tr></thead>
            <tbody>
            <?php foreach ($cards as $gc):
                $pct = $gc->initial_amount > 0 ? round(( $gc->balance / $gc->initial_amount ) * 100) : 0;
                $exp_str = $gc->expires_at ? yatoon_format_local('M j, Y', $gc->expires_at) : '-';
                $is_expired = $gc->expires_at && strtotime($gc->expires_at) < time();
                $display_status = $is_expired && $gc->status === 'active' ? 'expired' : $gc->status;
            ?>
            <tr>
                <td>
                    <span class="ygc-code"><?php echo esc_html($gc->code); ?></span>
                    <div style="font-size:11px;color:#9ca3af;margin-top:3px;"><?php echo esc_html(yatoon_format_local('M j, Y', $gc->created_at)); ?></div>
                </td>
                <td>
                    <?php echo $gc->recipient_name ? esc_html($gc->recipient_name) : '<span style="color:#9ca3af;">-</span>'; ?>
                    <?php if ($gc->recipient_email): ?><div style="font-size:11px;color:#9ca3af;"><?php echo esc_html($gc->recipient_email);?></div><?php endif;?>
                </td>
                <td>
                    <strong>$<?php echo number_format($gc->balance, 2);?></strong>
                    <div style="color:#9ca3af;font-size:11px;">of $<?php echo number_format($gc->initial_amount, 2);?></div>
                    <div class="ygc-balance-bar"><div class="ygc-balance-fill" style="width:<?php echo esc_attr( $pct ); ?>%"></div></div>
                </td>
                <td style="font-size:12px;"><?php echo esc_html($exp_str);?></td>
                <td><span class="ygc-badge badge-<?php echo esc_attr($display_status);?>"><?php echo esc_html(ucfirst($display_status));?></span></td>
                <td>
                    <div style="display:flex;gap:6px;flex-wrap:wrap;">
                        <?php if ($gc->status === 'active'): ?>
                        <button type="button" class="button button-small ygc-void-btn" data-id="<?php echo esc_attr($gc->id);?>" style="color:#dc2626;"><?php esc_html_e( 'Void', 'yatoon-booking-system' ); ?></button>
                        <?php endif;?>
                        <button type="button" class="button button-small ygc-history-btn" data-id="<?php echo esc_attr($gc->id);?>" data-code="<?php echo esc_attr($gc->code);?>"><?php esc_html_e( 'History', 'yatoon-booking-system' ); ?></button>
                    </div>
                </td>
            </tr>
            <?php endforeach;?>
            </tbody>
        </table>
        <?php endif;?>
    </div>
</div>

<!-- Right: create form -->
<div>
    <div class="ygc-panel">
        <div class="ygc-head"><h2><?php esc_html_e( 'Issue New Gift Card', 'yatoon-booking-system' ); ?></h2></div>
        <div class="ygc-body">
            <div class="ygc-form-row">
                <label><?php esc_html_e( 'Amount ($) *', 'yatoon-booking-system' ); ?></label>
                <input type="number" id="ygc-amount" min="1" step="0.01" placeholder="50.00">
                <div style="display:flex;gap:6px;margin-top:6px;flex-wrap:wrap;">
                    <?php foreach(array(25,50,75,100,150,200) as $amt):?>
                    <button type="button" class="button button-small ygc-preset-btn" data-val="<?php echo esc_attr( $amt ); ?>">$<?php echo esc_html( $amt ); ?></button>
                    <?php endforeach;?>
                </div>
            </div>
            <div class="ygc-form-row">
                <label><?php esc_html_e( 'Recipient Name', 'yatoon-booking-system' ); ?></label>
                <input type="text" id="ygc-recipient-name" placeholder="<?php echo esc_attr__( 'e.g. Jane Smith', 'yatoon-booking-system' ); ?>">
            </div>
            <div class="ygc-form-row">
                <label><?php esc_html_e( 'Recipient Email', 'yatoon-booking-system' ); ?></label>
                <input type="email" id="ygc-recipient-email" placeholder="<?php echo esc_attr__( 'jane@example.com', 'yatoon-booking-system' ); ?>">
                <p class="ygc-hint"><?php esc_html_e( 'Gift card code will be emailed here automatically.', 'yatoon-booking-system' ); ?></p>
            </div>
            <div class="ygc-form-row">
                <label><?php esc_html_e( 'Purchased By', 'yatoon-booking-system' ); ?></label>
                <input type="text" id="ygc-purchased-by" placeholder="<?php echo esc_attr__( 'e.g. John Smith (buyer)', 'yatoon-booking-system' ); ?>">
            </div>
            <div class="ygc-form-row">
                <label><?php esc_html_e( 'Personal Message', 'yatoon-booking-system' ); ?></label>
                <textarea id="ygc-message" placeholder="<?php echo esc_attr__( 'Happy Birthday! Enjoy your visit.', 'yatoon-booking-system' ); ?>"></textarea>
            </div>
            <div class="ygc-form-row">
                <label><?php esc_html_e( 'Expires (optional)', 'yatoon-booking-system' ); ?></label>
                <input type="date" id="ygc-expires" min="<?php echo esc_attr( wp_date('Y-m-d') );?>">
                <p class="ygc-hint"><?php esc_html_e( 'Leave blank for no expiry.', 'yatoon-booking-system' ); ?></p>
            </div>
            <div class="ygc-form-row">
                <label><?php esc_html_e( 'Custom Code (optional)', 'yatoon-booking-system' ); ?></label>
                <input type="text" id="ygc-custom-code" placeholder="<?php echo esc_attr__( 'Auto-generated if blank', 'yatoon-booking-system' ); ?>" maxlength="32" style="text-transform:uppercase;">
                <p class="ygc-hint"><?php esc_html_e( 'Letters and numbers only, e.g. BIRTHDAY2026', 'yatoon-booking-system' ); ?></p>
            </div>
            <button type="button" id="ygc-create-btn" class="button button-primary" style="width:100%;padding:9px;"><?php esc_html_e( 'Issue Gift Card', 'yatoon-booking-system' ); ?></button>
            <div id="ygc-create-result" style="margin-top:10px;font-size:13px;"></div>
        </div>
    </div>
</div>
</div>

<!-- Transaction history modal -->
<div id="ygc-history-modal" style="display:none;position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,.5);align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:12px;width:520px;max-width:95vw;max-height:80vh;overflow:auto;">
        <div style="padding:16px 20px;border-bottom:1px solid #f3f4f6;display:flex;align-items:center;justify-content:space-between;">
            <h3 style="margin:0;font-size:15px;" id="ygc-modal-title"><?php esc_html_e( 'Transaction History', 'yatoon-booking-system' ); ?></h3>
            <button type="button" id="ygc-modal-close" style="background:none;border:none;font-size:20px;cursor:pointer;color:#6b7280;"><?php esc_html_e( '&times;', 'yatoon-booking-system' ); ?></button>
        </div>
        <div id="ygc-modal-body" style="padding:16px 20px;"></div>
    </div>
</div>

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

    // Preset amount buttons
    $(document).on('click', '.ygc-preset-btn', function(){
        $('#ygc-amount').val($(this).data('val'));
    });

    // Auto-uppercase custom code
    $('#ygc-custom-code').on('input', function(){
        this.value = this.value.toUpperCase().replace(/[^A-Z0-9-]/g,'');
    });

    // Create gift card
    $('#ygc-create-btn').on('click', function(){
        const amount = parseFloat($('#ygc-amount').val());
            if (!amount || amount <= 0){ alert(<?php echo wp_json_encode( __( 'Please enter an amount.', 'yatoon-booking-system' ) ); ?>); return; }
        const $btn = $(this).prop('disabled', true).text('Creating...');
        $.post(ajaxurl, {
            action:          'yatoon_create_gift_card',
            nonce,
            amount,
            recipient_name:  $('#ygc-recipient-name').val(),
            recipient_email: $('#ygc-recipient-email').val(),
            purchased_by:    $('#ygc-purchased-by').val(),
            message:         $('#ygc-message').val(),
            expires:         $('#ygc-expires').val(),
            custom_code:     $('#ygc-custom-code').val(),
        }, function(resp){
            $btn.prop('disabled', false).text('Issue Gift Card');
            if (resp.success){
                $('#ygc-create-result').html('<div class="yatoon-inline-success"><span aria-hidden="true">&#10003;</span> Gift card created. Code: <span class="yatoon-code">' + resp.data.code + '</span></div>');
                setTimeout(function(){ location.reload(); }, 2000);
            } else {
                $('#ygc-create-result').html('<div style="background:#fee2e2;color:#991b1b;padding:10px 14px;border-radius:8px;">Error: ' + (resp.data?.message || 'Unknown error') + '</div>');
            }
        });
    });

    // Void
    $(document).on('click', '.ygc-void-btn', function(){
            if (!confirm(<?php echo wp_json_encode( __( 'Void this gift card? This cannot be undone.', 'yatoon-booking-system' ) ); ?>)) return;
        const $btn = $(this).prop('disabled', true);
        $.post(ajaxurl, { action: 'yatoon_void_gift_card', nonce, id: $(this).data('id') }, function(r){
            if (r.success) location.reload();
            else { alert('Failed'); $btn.prop('disabled', false); }
        });
    });

    // History modal
    $(document).on('click', '.ygc-history-btn', function(){
        const id = $(this).data('id');
        const code = $(this).data('code');
        $('#ygc-modal-title').text('History - ' + code);
        $('#ygc-modal-body').html('<p style="color:#9ca3af;text-align:center;padding:20px;">Loading...</p>');
        $('#ygc-history-modal').css('display','flex');
        $.post(ajaxurl, { action: 'yatoon_get_gift_card_history', nonce, id }, function(r){
            if (!r.success || !r.data.transactions.length){
                $('#ygc-modal-body').html('<p style="color:#9ca3af;text-align:center;padding:20px;">No transactions yet.</p>');
                return;
            }
            let html = '<table style="width:100%;border-collapse:collapse;font-size:13px;">';
            html += '<thead><tr><th style="text-align:left;padding:8px;background:#f9fafb;border-bottom:1px solid #f3f4f6;">Date</th><th style="text-align:left;padding:8px;background:#f9fafb;border-bottom:1px solid #f3f4f6;">Type</th><th style="text-align:right;padding:8px;background:#f9fafb;border-bottom:1px solid #f3f4f6;">Amount</th><th style="text-align:right;padding:8px;background:#f9fafb;border-bottom:1px solid #f3f4f6;">Balance after</th></tr></thead><tbody>';
            r.data.transactions.forEach(function(tx){
                const color = tx.type === 'issue' ? '#16a34a' : '#dc2626';
                html += '<tr><td style="padding:8px;border-bottom:1px solid #f9fafb;">' + tx.created_at + '</td>'
                    + '<td style="padding:8px;border-bottom:1px solid #f9fafb;text-transform:capitalize;">' + tx.type + (tx.note ? ' <span style="color:#9ca3af;font-size:11px;">- ' + tx.note + '</span>' : '') + '</td>'
                    + '<td style="padding:8px;border-bottom:1px solid #f9fafb;text-align:right;font-weight:600;color:' + color + ';">$' + parseFloat(tx.amount).toFixed(2) + '</td>'
                    + '<td style="padding:8px;border-bottom:1px solid #f9fafb;text-align:right;">$' + parseFloat(tx.balance_after).toFixed(2) + '</td></tr>';
            });
            html += '</tbody></table>';
            $('#ygc-modal-body').html(html);
        });
    });

    $('#ygc-modal-close').on('click', function(){ $('#ygc-history-modal').hide(); });
    $('#ygc-history-modal').on('click', function(e){ if(e.target===this)$(this).hide(); });
});
</script>
</div>
