<?php include 'header.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    .wa-card { border-radius: 15px; border: none; box-shadow: 0 4px 15px rgba(0,0,0,0.1); margin-bottom: 25px; }
    .header-green { background: #25D366; color: #fff; padding: 15px; border-radius: 15px 15px 0 0; font-weight: bold; }
    .header-dark { background: #075E54; color: #fff; padding: 15px; border-radius: 15px 15px 0 0; font-weight: bold; }
    .btn-wa { background: #25D366; color: #fff; border-radius: 10px; font-weight: 600; transition: 0.3s; height: 50px; font-size: 16px; }
    .btn-wa:hover { background: #128C7E; transform: scale(1.01); }
    .badge-manual { background: #e3f2fd; color: #1976d2; padding: 4px 8px; border-radius: 4px; font-size: 10px; }
    .badge-price { background: #e8f5e9; color: #2e7d32; padding: 4px 8px; border-radius: 4px; font-size: 10px; }
    /* Naya Style Resend Button ke liye */
    .btn-resend { background: #ff9800; color: white; border: none; padding: 4px 8px; border-radius: 4px; margin-right: 5px; cursor: pointer; }
    .btn-resend:hover { background: #e68a00; }
</style>

<div class="container-fluid" style="max-width: 1200px; margin-top: 20px;">
    <div class="row">
        <div class="col-md-5">
            <div class="card wa-card">
                <div class="header-green"><i class="fa fa-cog"></i> WA API Configuration</div>
                <div class="card-body">
                    <form method="post">
                        <div class="form-group"><label>API Key</label><input type="text" name="api" class="form-control" value="<?= $wa_settings['mpwa_api_key'] ?>"></div>
                        <div class="form-group"><label>Sender Number</label><input type="text" name="sender" class="form-control" value="<?= $wa_settings['mpwa_sender'] ?>"></div>
                        <div class="form-group"><label>Channel URL</label><input type="text" name="url" class="form-control" value="<?= $wa_settings['channel_url'] ?>"></div>
                        <div class="form-group"><label>Footer Text</label><input type="text" name="footer" class="form-control" value="<?= $wa_settings['footer_text'] ?>"></div>
                        <div class="row">
                            <div class="col-xs-6"><button type="submit" name="save_all" class="btn btn-primary btn-block">Save Settings</button></div>
                            <div class="col-xs-6"><button type="button" onclick="runAction('test')" class="btn btn-warning btn-block">Test API</button></div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-7">
            <div class="card wa-card">
                <div class="header-dark"><i class="fa fa-paper-plane"></i> Quick Broadcast</div>
                <div class="card-body">
                    <textarea id="manual_msg" class="form-control" rows="8" placeholder="Type your offer..."></textarea>
                    <button type="button" onclick="runAction('send')" class="btn btn-wa btn-block" style="margin-top:15px;">🚀 Send to WhatsApp Channel</button>
                </div>
            </div>
        </div>
    </div>

    <div class="card wa-card">
        <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center" style="padding:15px; border-radius: 15px 15px 0 0; font-weight: bold;">
            <span><i class="fa fa-history"></i> Broadcast & Price Logs (Synced)</span>
            <button onclick="clearLogs()" class="btn btn-danger btn-xs">Clear All</button>
        </div>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Date & Time</th>
                        <th>Type</th>
                        <th>Service / Content</th>
                        <th>Price Details</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="logTable">
                    <?php foreach($price_logs as $log): 
                        // HTML Tags saaf karein description se
                        $clean_price_info = strip_tags($log['price_info']);

                        // 🔥 [PHP FIX] Lambe numbers ko 2 decimal tak round karne ke liye
                        $display_info = preg_replace_callback('/(\d+\.\d{2})\d+/', function($m) {
                            return $m[1];
                        }, $clean_price_info);

                        // 🕒 [TIME FIX] 24-hour se 12-hour format (h:i A)
                        $formatted_time = date('d M, h:i A', strtotime($log['date']));
                    ?>
                    <tr id="row_<?= $log['id'] ?>">
                        <td style="font-size: 11px; white-space: nowrap;"><?= $formatted_time ?></td>
                        <td>
                            <?php if($log['type'] == 'MANUAL'): ?>
                                <span class="badge-manual">MANUAL</span>
                            <?php else: ?>
                                <span class="badge-price">AUTO</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if($log['service_id'] != '0'): ?>
                                <b>#<?= $log['service_id'] ?></b> <?= $log['service_name'] ?>
                            <?php else: ?>
                                <i><?= $log['service_name'] ?></i>
                            <?php endif; ?>
                        </td>
                        <td>
                            <small class="text-muted"><?= $display_info ?></small>
                        </td>
                        <td style="white-space: nowrap;">
                            <button onclick="smartResend('<?= $log['service_id'] ?>', '<?= addslashes($log['service_name']) ?>', '<?= addslashes($display_info) ?>')" class="btn-resend" title="Resend to Channel">
                                <i class="fa fa-sync"></i>
                            </button>
                            <button onclick="confirmDelete('<?= $log['id'] ?>')" class="btn btn-danger btn-xs" title="Delete Log">
                                <i class="fa fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
// --- Resend Function ---
function smartResend(sid, name, info) {
    /**
     * 🔥 [JS FIX] Lambe numbers ko replace karke professional banana
     */
    let shortInfo = info.replace(/(\d+\.\d{2})\d+/g, '$1');

    // Professional Message Format
    let msg = `📢 *ALIXDEAL BROADCAST*\n\n🔹 *Service:* ${name}\n🔹 *Update:* ${shortInfo}\n\n🔗 *Link:* alixdeal.shop\n${sid != '0' ? '🆔 *ID:* #' + sid : ''}`;
    
    Swal.fire({
        title: 'Channel par phir se bhejein?',
        text: "Price point ko round kar diya gaya hai.",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#25D366',
        confirmButtonText: 'Haan, Bhejo! 🚀'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({ title: 'Sending...', didOpen: () => { Swal.showLoading() } });
            $.post('', { action: 'send_formatted', manual_msg: msg, is_ajax: 1 }, function(data) {
                let res = JSON.parse(data);
                if(res.status) {
                    Swal.fire('Success!', 'Message delivered to channel.', 'success');
                } else {
                    Swal.fire('Failed', res.msg, 'error');
                }
            });
        }
    });
}

// --- Action Logic (Test & Send) ---
function runAction(type) {
    let msg = (type == 'send') ? $('#manual_msg').val() : '';
    if(type == 'send' && !msg) return Swal.fire('Error', 'Message empty!', 'error');

    Swal.fire({ title: 'Sending...', didOpen: () => { Swal.showLoading() } });

    $.post('', { action: type, manual_msg: msg, is_ajax: 1 }, function(data) {
        let res = JSON.parse(data);
        if(res.status) {
            Swal.fire('Success!', 'Task completed successfully.', 'success').then(() => {
                if(type == 'send') location.reload();
            });
        } else {
            Swal.fire('Failed', res.msg, 'error');
        }
    });
}

// --- Single Delete ---
function confirmDelete(id) {
    Swal.fire({
        title: 'Delete this record?',
        text: "History se mita diya jayega.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Delete'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('', { action: 'delete_log', id: id, is_ajax: 1 }, function(data) {
                let res = JSON.parse(data);
                if(res.status) {
                    $('#row_'+id).fadeOut(500);
                    Swal.fire({ title: 'Deleted!', icon: 'success', timer: 1000, showConfirmButton: false });
                } else {
                    Swal.fire('Error', 'Delete failed', 'error');
                }
            });
        }
    });
}

// --- Clear All ---
function clearLogs() {
    Swal.fire({ title: 'Purani history saaf karein?', icon: 'warning', showCancelButton: true }).then((res) => {
        if(res.isConfirmed) {
            $.post('', { action: 'clear_all', is_ajax: 1 }, function() {
                location.reload();
            });
        }
    });
}
</script>
<?php include 'footer.php'; ?>