<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

// --- 1. CORE SETTINGS ---
$api_key   = "ic9mQDkIkey3hcdNGT7NSA0tOEZ49K"; 
$sender_no = "918273147063"; 
$api_url   = "https://ads.alixdeal.info/send-message"; 
$my_wa_link = "https://wa.me/918273147063";

// --- 2. AJAX OPERATIONS (Delete & Clear All) ---
if (isset($_POST['action'])) {
    if ($_POST['action'] == 'direct_resend') {
        $num = $_POST['number'];
        $msg = $_POST['message'];
        $data = ["api_key" => $api_key, "sender" => $sender_no, "number" => $num, "message" => $msg];
        $ch = curl_init($api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        echo curl_exec($ch);
    } 
    elseif ($_POST['action'] == 'delete_single') {
        $del = $conn->prepare("DELETE FROM whatsapp_logs WHERE id = ?");
        if($del->execute([$_POST['id']])) { echo "success"; }
    }
    elseif ($_POST['action'] == 'clear_all_logs') {
        if($conn->query("DELETE FROM whatsapp_logs")) { echo "success"; }
    }
    exit;
}

// --- 3. DATA FETCH ---
$query = "SELECT l.*, c.username FROM whatsapp_logs l 
          INNER JOIN orders o ON l.order_id = o.order_id 
          LEFT JOIN clients c ON o.client_id = c.client_id 
          ORDER BY l.id DESC LIMIT 50";
$crm_logs = $conn->query($query)->fetchAll(PDO::FETCH_ASSOC);
$total_msgs = $conn->query("SELECT COUNT(id) as total FROM whatsapp_logs")->fetch(PDO::FETCH_ASSOC)['total'];

require_once 'admin/views/header.php'; 
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    .crm-body { background: #f1f5f9 !important; padding: 15px; font-family: 'Segoe UI', sans-serif; }
    .alix-card { background: #fff; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); margin-bottom: 20px; border: none; overflow: hidden; }
    .card-header-crm { background: #0f172a; color: #fff; padding: 15px; font-weight: 700; display: flex; justify-content: space-between; align-items: center; }
    .history-scroll-box { max-height: 550px; overflow-y: auto; background: #fff; }
    .table-crm thead th { position: sticky; top: 0; background: #f8fafc; color: #64748b; font-size: 11px; text-transform: uppercase; padding: 15px; z-index: 10; border: none; }
    .table-crm td { vertical-align: middle !important; padding: 12px 15px !important; border-top: 1px solid #f1f5f9; font-size: 13px; color: #334155; }
    .st-badge { padding: 4px 10px; border-radius: 6px; font-size: 10px; font-weight: 800; text-transform: uppercase; color: #fff; }
    .st-sent { background: #10b981; }
    .st-fail { background: #ef4444; }
    .btn-act { background: #fff; border: 1.5px solid #e2e8f0; color: #475569; padding: 6px 10px; border-radius: 6px; font-size: 12px; cursor: pointer; }
    .btn-act:hover { background: #f8fafc; transform: translateY(-1px); }
    .count-badge { background: #3b82f6; color: #fff; padding: 2px 8px; border-radius: 10px; font-size: 11px; margin-left: 5px; }
    .tool-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-top: 20px; }
    .tool-card { background: #fff; border-radius: 12px; padding: 15px; text-align: center; border: 1px solid #e2e8f0; }
    .tool-card img { width: 45px; margin-bottom: 10px; }
</style>

<div class="crm-body">
    <div class="alix-card">
        <div class="card-header-crm">
            <span><i class="fa fa-whatsapp mr-2 text-success"></i> MPWA REAL-TIME LOGS <span class="count-badge"><?= $total_msgs ?></span></span>
            <div>
                <button onclick="location.reload()" class="btn btn-sm btn-info" style="margin-right:5px;"><i class="fa fa-sync"></i> Refresh</button>
                <button onclick="clearAllLogs()" class="btn btn-sm btn-danger"><i class="fa fa-trash-alt"></i> Clear All</button>
            </div>
        </div>
        
        <div class="history-scroll-box">
            <div class="table-responsive">
                <table class="table table-hover mb-0 table-crm" id="logTable">
                    <thead>
                        <tr><th>Order</th><th>User Details</th><th>Status</th><th>Actions</th></tr>
                    </thead>
                    <tbody>
                        <?php if(empty($crm_logs)): ?>
                            <tr id="noData"><td colspan="4" class="text-center p-5">Koi real history nahi mili.</td></tr>
                        <?php else: foreach($crm_logs as $row): 
                            $status_class = (strtolower($row['status']) == 'sent') ? 'st-sent' : 'st-fail';
                        ?>
                            <tr id="row_<?= $row['id'] ?>">
                                <td><b class="text-primary">#<?= $row['order_id'] ?></b></td>
                                <td><div class="font-weight-bold"><?= $row['username'] ?? 'User' ?></div><small class="text-muted"><?= $row['receiver'] ?></small></td>
                                <td><span class="st-badge <?= $status_class ?>"><?= $row['status'] ?></span></td>
                                <td>
                                    <button class="btn-act" onclick="sendAgain('<?= $row['receiver'] ?>', `<?= addslashes($row['message']) ?>`)" title="Resend"><i class="fa fa-paper-plane text-primary"></i></button>
                                    <button class="btn-act" onclick="openEdit('<?= $row['receiver'] ?>', `<?= addslashes($row['message']) ?>`)" title="Edit"><i class="fa fa-edit text-warning"></i></button>
                                    <button class="btn-act" onclick="deleteLog(<?= $row['id'] ?>)" title="Delete"><i class="fa fa-trash-alt text-danger"></i></button>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="tool-grid">
        <div class="tool-card"><img src="https://cdn-icons-png.flaticon.com/512/733/733585.png"><h4>CRM Tool</h4><a href="<?= $my_wa_link ?>?text=Buy CRM" class="btn btn-sm btn-dark">BUY</a></div>
        <div class="tool-card"><img src="https://cdn-icons-png.flaticon.com/512/2165/2165004.png"><h4>API Msg</h4><a href="<?= $my_wa_link ?>?text=Buy API" class="btn btn-sm btn-dark">BUY</a></div>
        <div class="tool-card"><img src="https://cdn-icons-png.flaticon.com/512/2504/2504814.png"><h4>OTP Num</h4><a href="<?= $my_wa_link ?>?text=Buy OTP" class="btn btn-sm btn-dark">BUY</a></div>
    </div>
</div>

<div class="modal fade" id="editLogModal" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content"><div class="modal-header bg-dark text-white"><h6 class="modal-title">Edit Message</h6><button type="button" class="close text-white" data-dismiss="modal">&times;</button></div><div class="modal-body p-3"><input type="hidden" id="wa_num"><textarea id="wa_msg" class="form-control" rows="8"></textarea><button onclick="saveAndSend()" id="sendBtn" class="btn btn-primary btn-block mt-3">UPDATE & SEND</button></div></div></div>
</div>

<script>
// --- AJAX Resend ---
function sendAgain(num, msg) {
    Swal.fire({ title: 'Sending...', didOpen: () => { Swal.showLoading() } });
    $.post('', { action: 'direct_resend', number: num, message: msg }, function(res) {
        Swal.close();
        let r = JSON.parse(res);
        if(r.status == true) { Swal.fire({ icon: 'success', title: 'Sent!', timer: 1500, showConfirmButton: false }); }
        else { Swal.fire('Error', r.message, 'error'); }
    });
}

function openEdit(num, msg) { $('#wa_num').val(num); $('#wa_msg').val(msg); $('#editLogModal').modal('show'); }

function saveAndSend() {
    let n = $('#wa_num').val(); let m = $('#wa_msg').val();
    $('#sendBtn').prop('disabled', true).text('Sending...');
    $.post('', { action: 'direct_resend', number: n, message: m }, function() {
        Swal.fire({ icon: 'success', title: 'Updated & Sent!' });
        $('#editLogModal').modal('hide');
        $('#sendBtn').prop('disabled', false).text('UPDATE & SEND');
    });
}

// --- AJAX Delete Single (Fixed Redirect Issue) ---
function deleteLog(id) {
    Swal.fire({
        title: 'Delete?', text: "Lucky Bhai, ye hat jayega!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#ef4444'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('', { action: 'delete_single', id: id }, function(res) {
                if(res == "success") {
                    $('#row_'+id).fadeOut(500);
                    Swal.fire({ icon: 'success', title: 'Deleted!', timer: 1000, showConfirmButton: false });
                }
            });
        }
    });
}

// --- AJAX Clear All ---
function clearAllLogs() {
    Swal.fire({
        title: 'Clear All?', text: "Sara data saaf ho jayega!", icon: 'error', showCancelButton: true, confirmButtonColor: '#d33'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('', { action: 'clear_all_logs' }, function(res) {
                if(res == "success") {
                    $('tbody').html('<tr><td colspan="4" class="text-center p-5">Koi real history nahi mili.</td></tr>');
                    $('.count-badge').text('0');
                    Swal.fire('Cleaned!', 'Sari history delete ho gayi.', 'success');
                }
            });
        }
    });
}
</script>

<?php require_once 'admin/views/footer.php'; ?>