<?php
// phpcs:ignoreFile
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>Gift Cards 🎁</h1>
<p style="color:#6b7280;margin-top:0;">Create and manage gift cards. Customers redeem codes at checkout.</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>Cards issued</span></div>
    <div class="ygc-kpi"><strong>$<?php echo number_format(floatval($stats->total_sold ?? 0), 2); ?></strong><span>Total sold</span></div>
    <div class="ygc-kpi"><strong style="color:#16a34a;">$<?php echo number_format(floatval($stats->total_balance ?? 0), 2); ?></strong><span>Outstanding balance</span></div>
    <div class="ygc-kpi"><strong>$<?php echo number_format(floatval($stats->total_redeemed ?? 0), 2); ?></strong><span>Redeemed</span></div>
</div>

<div class="ygc-layout">

<!-- Left: card list -->
<div>
    <div class="ygc-tabs">
        <?php foreach(['all'=>'All','active'=>'Active','used'=>'Used Up','void'=>'Voided','expired'=>'Expired'] as $slug=>$label):
            $active = $filter === $slug ? 'active' : ''; ?>
        <a class="ygc-tab <?php echo $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">No gift cards yet. Create one using the form on the right.</div>
        <?php else: ?>
        <table>
            <thead><tr><th>Code</th><th>Recipient</th><th>Balance</th><th>Expires</th><th>Status</th><th>Actions</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 ? date('M j, Y', strtotime($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(date('M j, Y', strtotime($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 $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;">Void</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);?>">History</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>Issue New Gift Card</h2></div>
        <div class="ygc-body">
            <div class="ygc-form-row">
                <label>Amount ($) *</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([25,50,75,100,150,200] as $amt):?>
                    <button type="button" class="button button-small ygc-preset-btn" data-val="<?php echo $amt;?>">$<?php echo $amt;?></button>
                    <?php endforeach;?>
                </div>
            </div>
            <div class="ygc-form-row">
                <label>Recipient Name</label>
                <input type="text" id="ygc-recipient-name" placeholder="e.g. Jane Smith">
            </div>
            <div class="ygc-form-row">
                <label>Recipient Email</label>
                <input type="email" id="ygc-recipient-email" placeholder="jane@example.com">
                <p class="ygc-hint">Gift card code will be emailed here automatically.</p>
            </div>
            <div class="ygc-form-row">
                <label>Purchased By</label>
                <input type="text" id="ygc-purchased-by" placeholder="e.g. John Smith (buyer)">
            </div>
            <div class="ygc-form-row">
                <label>Personal Message</label>
                <textarea id="ygc-message" placeholder="Happy Birthday! Enjoy your visit."></textarea>
            </div>
            <div class="ygc-form-row">
                <label>Expires (optional)</label>
                <input type="date" id="ygc-expires" min="<?php echo date('Y-m-d');?>">
                <p class="ygc-hint">Leave blank for no expiry.</p>
            </div>
            <div class="ygc-form-row">
                <label>Custom Code (optional)</label>
                <input type="text" id="ygc-custom-code" placeholder="Auto-generated if blank" maxlength="32" style="text-transform:uppercase;">
                <p class="ygc-hint">Letters and numbers only, e.g. BIRTHDAY2026</p>
            </div>
            <button type="button" id="ygc-create-btn" class="button button-primary" style="width:100%;padding:9px;">Issue Gift Card</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">Transaction History</h3>
            <button type="button" id="ygc-modal-close" style="background:none;border:none;font-size:20px;cursor:pointer;color:#6b7280;">&times;</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('Please enter an amount.'); 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 style="background:#dcfce7;color:#166534;padding:10px 14px;border-radius:8px;font-weight:600;">Yes Gift card created! Code: <span style="font-family:monospace;font-size:15px;letter-spacing:.05em;">' + 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('Void this gift card? This cannot be undone.')) 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>
