<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('include/header.php');
$page_title = WEB_NAME . " | SMS Numbers";

// Get filter parameters
$status_filter        = isset($_GET['status'])        ? trim($_GET['status'])        : 'all';
$active_status_filter = isset($_GET['active_status']) ? trim($_GET['active_status']) : 'all';
$provider_filter      = isset($_GET['provider'])      ? trim($_GET['provider'])      : 'all';
$search               = isset($_GET['search'])        ? trim($_GET['search'])        : '';
$date_from            = isset($_GET['date_from'])     ? trim($_GET['date_from'])     : '';
$date_to              = isset($_GET['date_to'])       ? trim($_GET['date_to'])       : '';

// Build query using PDO with LEFT JOIN to users table
$where = "WHERE 1=1";
$params = [];

if ($status_filter !== 'all') {
    $where .= " AND an.status = :status";
    $params['status'] = $status_filter;
}
if ($active_status_filter !== 'all') {
    $where .= " AND an.active_status = :active_status";
    $params['active_status'] = $active_status_filter;
}
if (!empty($search)) {
    $where .= " AND (an.number LIKE :search OR an.order_id LIKE :search2 OR u.email LIKE :search3 OR u.full_name LIKE :search4 OR u.username LIKE :search5 OR an.service_name LIKE :search6)";
    $params['search']  = "%$search%";
    $params['search2'] = "%$search%";
    $params['search3'] = "%$search%";
    $params['search4'] = "%$search%";
    $params['search5'] = "%$search%";
    $params['search6'] = "%$search%";
}
if (!empty($date_from)) {
    $where .= " AND DATE(an.buy_time) >= :date_from";
    $params['date_from'] = $date_from;
}
if (!empty($date_to)) {
    $where .= " AND DATE(an.buy_time) <= :date_to";
    $params['date_to'] = $date_to;
}
if ($provider_filter === 'smspva') {
    $where .= " AND an.provider = 'smspva'";
} elseif ($provider_filter === 'smscodes') {
    $where .= " AND (an.provider = 'smscodes' OR an.provider IS NULL OR an.provider = '')";
} elseif ($provider_filter === '5sim') {
    $where .= " AND an.provider = '5sim'";
} elseif ($provider_filter === 'smsbus') {
    $where .= " AND an.provider = 'smsbus'";
}

try {
    $stmt = $pdo->prepare("
        SELECT an.*, u.username, u.full_name, u.email,
               os.server_name AS country_name, ad.api_type AS provider_type
        FROM active_number an
        LEFT JOIN users u ON an.user_id = u.id
        LEFT JOIN otp_server os ON os.id = an.server_id
        LEFT JOIN api_detail ad ON ad.id = os.api_id
        $where
        ORDER BY an.buy_time DESC
    ");
    $stmt->execute($params);
    $numbers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $total_count = count($numbers);
} catch (PDOException $e) {
    $numbers = [];
    $total_count = 0;
    error_log("Error fetching numbers: " . $e->getMessage());
}

// Statistics
try {
    $stats_stmt = $pdo->query("
        SELECT 
            COUNT(*) as total_numbers,
            SUM(CASE WHEN active_status='2' THEN 1 ELSE 0 END) as active_numbers,
            SUM(CASE WHEN status='1' THEN 1 ELSE 0 END) as completed,
            SUM(CASE WHEN status='2' THEN 1 ELSE 0 END) as pending,
            SUM(CASE WHEN status='3' THEN 1 ELSE 0 END) as cancelled,
            SUM(CASE WHEN active_status='2' THEN CAST(service_price AS DECIMAL(10,2)) ELSE 0 END) as total_revenue,
            SUM(CASE WHEN provider='smspva' THEN 1 ELSE 0 END) as s1_total,
            SUM(CASE WHEN provider='smspva' AND status='1' THEN 1 ELSE 0 END) as s1_completed,
            SUM(CASE WHEN (provider='smscodes' OR provider IS NULL OR provider='') THEN 1 ELSE 0 END) as s2_total,
            SUM(CASE WHEN (provider='smscodes' OR provider IS NULL OR provider='') AND status='1' THEN 1 ELSE 0 END) as s2_completed,
            SUM(CASE WHEN provider='5sim' THEN 1 ELSE 0 END) as s3_total,
            SUM(CASE WHEN provider='5sim' AND status='1' THEN 1 ELSE 0 END) as s3_completed,
            SUM(CASE WHEN provider='smsbus' THEN 1 ELSE 0 END) as s4_total,
            SUM(CASE WHEN provider='smsbus' AND status='1' THEN 1 ELSE 0 END) as s4_completed
        FROM active_number
    ");
    $stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $stats = ['total_numbers'=>0,'active_numbers'=>0,'completed'=>0,'pending'=>0,'cancelled'=>0,'total_revenue'=>0];
}

// Today's stats
try {
    $today_stmt = $pdo->query("
        SELECT 
            COUNT(*) as today_numbers,
            SUM(CASE WHEN active_status='2' THEN CAST(service_price AS DECIMAL(10,2)) ELSE 0 END) as today_revenue
        FROM active_number
        WHERE DATE(buy_time) = CURDATE()
    ");
    $today_stats = $today_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $today_stats = ['today_numbers'=>0,'today_revenue'=>0];
}

// Top 5 popular services
try {
    $popular_stmt = $pdo->query("
        SELECT 
            service_name,
            COUNT(*) as total_purchases,
            SUM(CASE WHEN active_status='2' THEN CAST(service_price AS DECIMAL(10,2)) ELSE 0 END) as total_spent
        FROM active_number
        GROUP BY service_name
        ORDER BY total_purchases DESC
        LIMIT 5
    ");
    $popular_services = $popular_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $popular_services = [];
}
?>
<title>SMS Numbers - <?php echo $site_data['web_name']; ?></title>

<link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">

<style>
    .stat-card {
        border-left: 4px solid;
        transition: transform 0.2s;
    }
    .stat-card:hover {
        transform: translateY(-5px);
    }
    .status-badge {
        padding: 0.375rem 0.75rem;
        border-radius: 0.25rem;
        font-weight: 600;
        font-size: 0.75rem;
        text-transform: uppercase;
        display: inline-block;
    }
    .status-completed  { background-color: #d1fae5; color: #065f46; }
    .status-pending    { background-color: #fef3c7; color: #92400e; }
    .status-cancelled  { background-color: #fee2e2; color: #991b1b; }
    .active-status-active   { background-color: #dbeafe; color: #1e40af; }
    .active-status-inactive { background-color: #f3f4f6; color: #374151; }
    .number-display {
        font-family: 'Courier New', monospace;
        font-size: 0.9rem;
        color: #4e73df;
        font-weight: 600;
    }
    .sms-text {
        background: #f8f9fc;
        padding: 0.5rem;
        border-radius: 0.25rem;
        font-family: 'Courier New', monospace;
        font-size: 0.875rem;
        word-break: break-all;
    }
    .active-revenue-badge {
        display: inline-block;
        background: #d1fae5;
        color: #065f46;
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.7rem;
        font-weight: 600;
        margin-top: 0.25rem;
    }
    .active-revenue-badge i { margin-right: 0.25rem; }
</style>

<div class="container-fluid" id="container-wrapper">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">SMS Numbers</h1>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active" aria-current="page">SMS Numbers</li>
        </ol>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color: #4e73df;">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Total Numbers</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['total_numbers']); ?></div>
                        </div>
                        <div class="col-auto"><i class="fas fa-mobile-alt fa-2x text-primary"></i></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color: #1cc88a;">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Active Numbers</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['active_numbers']); ?></div>
                        </div>
                        <div class="col-auto"><i class="fas fa-check-circle fa-2x text-success"></i></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color: #36b9cc;">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Today's Numbers</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($today_stats['today_numbers']); ?></div>
                            <div class="active-revenue-badge mt-2">
                                <i class="fas fa-dollar-sign"></i>NGN<?php echo number_format($today_stats['today_revenue'], 2); ?> (Active)
                            </div>
                        </div>
                        <div class="col-auto"><i class="fas fa-calendar-day fa-2x text-info"></i></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100" style="border-left-color: #f6c23e;">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1">Total Revenue</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">NGN<?php echo number_format($stats['total_revenue'], 2); ?></div>
                            <div class="active-revenue-badge">
                                <i class="fas fa-check-circle"></i>Active Numbers Only
                            </div>
                        </div>
                        <div class="col-auto"><i class="fas fa-dollar-sign fa-2x text-warning"></i></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Status Overview -->
    <div class="row mb-4">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-chart-bar mr-2"></i>Status Overview
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-md-4">
                            <div class="p-3">
                                <i class="fas fa-check-circle fa-3x text-success mb-2"></i>
                                <h4 class="font-weight-bold"><?php echo number_format($stats['completed']); ?></h4>
                                <p class="text-muted mb-0">Completed</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="p-3">
                                <i class="fas fa-clock fa-3x text-warning mb-2"></i>
                                <h4 class="font-weight-bold"><?php echo number_format($stats['pending']); ?></h4>
                                <p class="text-muted mb-0">Pending</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="p-3">
                                <i class="fas fa-times-circle fa-3x text-danger mb-2"></i>
                                <h4 class="font-weight-bold"><?php echo number_format($stats['cancelled']); ?></h4>
                                <p class="text-muted mb-0">Cancelled</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Provider Breakdown -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                <i class="fas fa-server mr-1"></i>Server1 — smspva.com
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['s1_total'] ?? 0); ?> orders</div>
                            <small class="text-muted"><?php echo number_format($stats['s1_completed'] ?? 0); ?> completed</small>
                        </div>
                        <div class="col-auto"><i class="fas fa-server fa-2x text-gray-300"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                <i class="fas fa-satellite-dish mr-1"></i>Server2 — smscodes.io
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['s2_total'] ?? 0); ?> orders</div>
                            <small class="text-muted"><?php echo number_format($stats['s2_completed'] ?? 0); ?> completed</small>
                        </div>
                        <div class="col-auto"><i class="fas fa-satellite-dish fa-2x text-gray-300"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                <i class="fas fa-signal mr-1"></i>Server3 — 5sim.net
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['s3_total'] ?? 0); ?> orders</div>
                            <small class="text-muted"><?php echo number_format($stats['s3_completed'] ?? 0); ?> completed</small>
                        </div>
                        <div class="col-auto"><i class="fas fa-signal fa-2x text-gray-300"></i></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                <i class="fas fa-bus mr-1"></i>Server4 — smsbus
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['s4_total'] ?? 0); ?> orders</div>
                            <small class="text-muted"><?php echo number_format($stats['s4_completed'] ?? 0); ?> completed</small>
                        </div>
                        <div class="col-auto"><i class="fas fa-bus fa-2x text-gray-300"></i></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Top 5 Popular Services -->
    <div class="row mb-4">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-star mr-2"></i>Top 5 Popular Services
                        <small class="text-muted">(Revenue from active numbers only)</small>
                    </h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Rank</th>
                                    <th>Service Name</th>
                                    <th>Total Purchases</th>
                                    <th>Active Revenue</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($popular_services)): ?>
                                    <?php $rank = 0; foreach ($popular_services as $svc): $rank++;
                                        $medal = $rank == 1 ? '🥇' : ($rank == 2 ? '🥈' : ($rank == 3 ? '🥉' : '')); ?>
                                    <tr>
                                        <td><strong><?php echo $medal . ' ' . $rank; ?></strong></td>
                                        <td><strong><?php echo htmlspecialchars($svc['service_name']); ?></strong></td>
                                        <td><span class="badge badge-primary"><?php echo number_format($svc['total_purchases']); ?> purchases</span></td>
                                        <td><span class="badge badge-success">NGN<?php echo number_format($svc['total_spent'], 2); ?></span></td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="4" class="text-center text-muted">No data available</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" action="">
                <div class="row">
                    <div class="col-md-3 mb-2">
                        <input type="text" name="search" class="form-control"
                               placeholder="Search number, order ID, user..."
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-2 mb-2">
                        <select name="status" class="form-control">
                            <option value="all"  <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>All Status</option>
                            <option value="1"    <?php echo $status_filter == '1'   ? 'selected' : ''; ?>>Completed</option>
                            <option value="2"    <?php echo $status_filter == '2'   ? 'selected' : ''; ?>>Pending</option>
                            <option value="3"    <?php echo $status_filter == '3'   ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    <div class="col-md-2 mb-2">
                        <select name="active_status" class="form-control">
                            <option value="all" <?php echo $active_status_filter == 'all' ? 'selected' : ''; ?>>All Active Status</option>
                            <option value="1"   <?php echo $active_status_filter == '1'   ? 'selected' : ''; ?>>Inactive</option>
                            <option value="2"   <?php echo $active_status_filter == '2'   ? 'selected' : ''; ?>>Active</option>
                        </select>
                    </div>
                    <div class="col-md-2 mb-2">
                        <select name="provider" class="form-control">
                            <option value="all"      <?php echo $provider_filter == 'all'      ? 'selected' : ''; ?>>All Servers</option>
                            <option value="smspva"   <?php echo $provider_filter == 'smspva'   ? 'selected' : ''; ?>>Server1 (smspva)</option>
                            <option value="smscodes" <?php echo $provider_filter == 'smscodes' ? 'selected' : ''; ?>>Server2 (smscodes)</option>
                            <option value="5sim"     <?php echo $provider_filter == '5sim'     ? 'selected' : ''; ?>>Server3 (5sim)</option>
                            <option value="smsbus"   <?php echo $provider_filter == 'smsbus'   ? 'selected' : ''; ?>>Server4 (smsbus)</option>
                        </select>
                    </div>
                    <div class="col-md-2 mb-2">
                        <input type="date" name="date_from" class="form-control"
                               value="<?php echo htmlspecialchars($date_from); ?>">
                    </div>
                    <div class="col-md-2 mb-2">
                        <input type="date" name="date_to" class="form-control"
                               value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>
                    <div class="col-md-1 mb-2">
                        <button type="submit" class="btn btn-primary btn-block">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </div>
                <?php if ($search || $status_filter != 'all' || $active_status_filter != 'all' || $provider_filter != 'all' || $date_from || $date_to): ?>
                <div class="row mt-2">
                    <div class="col-12">
                        <a href="sms-numbers.php" class="btn btn-secondary btn-sm">
                            <i class="fas fa-redo"></i> Reset Filters
                        </a>
                    </div>
                </div>
                <?php endif; ?>
            </form>
        </div>
    </div>

    <!-- Numbers Table -->
    <div class="row">
        <div class="col-lg-12">
            <div class="card mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-list mr-2"></i>All Numbers (<?php echo $total_count; ?> records)
                    </h6>
                    <button class="btn btn-success btn-sm" onclick="exportToExcel()">
                        <i class="fas fa-file-excel mr-1"></i>Export to Excel
                    </button>
                </div>
                <div class="table-responsive p-3">
                    <?php if (!empty($numbers)): ?>
                    <table class="table align-items-center table-flush table-hover" id="dataTable">
                        <thead class="thead-light">
                            <tr>
                                <th>#</th>
                                <th>Order ID</th>
                                <th>User</th>
                                <th>Number</th>
                                <th>Service</th>
                                <th>Server / Provider</th>
                                <th>Price</th>
                                <th>SMS</th>
                                <th>Status</th>
                                <th>Active</th>
                                <th>Purchase Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $count = 0; foreach ($numbers as $row): $count++;
                                // Status mapping
                                if ($row['status'] == '1')      { $status_text = 'Completed'; $status_class = 'completed'; }
                                elseif ($row['status'] == '2')  { $status_text = 'Pending';   $status_class = 'pending'; }
                                elseif ($row['status'] == '3')  { $status_text = 'Cancelled'; $status_class = 'cancelled'; }
                                else                            { $status_text = 'Unknown';   $status_class = 'cancelled'; }

                                $active_text  = $row['active_status'] == '2' ? 'Active'   : 'Inactive';
                                $active_class = $row['active_status'] == '2' ? 'active'   : 'inactive';
                                $display_name = !empty($row['full_name']) ? $row['full_name'] : ($row['username'] ?? '—');
                            ?>
                            <tr>
                                <td><?php echo $count; ?></td>
                                <td>
                                    <code style="font-size:0.75rem;"><?php echo htmlspecialchars($row['order_id']); ?></code>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($display_name); ?></strong><br>
                                    <small class="text-muted"><?php echo htmlspecialchars($row['email'] ?? ''); ?></small><br>
                                    <small class="text-muted">ID: <?php echo htmlspecialchars($row['user_id']); ?></small>
                                </td>
                                <td>
                                    <span class="number-display">+<?php echo htmlspecialchars($row['number']); ?></span><br>
                                    <small class="text-muted">ID: <?php echo htmlspecialchars($row['number_id']); ?></small>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($row['service_name']); ?></strong><br>
                                    <small class="text-muted"><?php echo htmlspecialchars($row['service_id']); ?></small>
                                </td>
                                <td>
                                    <small><?php echo htmlspecialchars($row['country_name'] ?? $row['server_id']); ?></small><br>
                                    <?php
                                    $prov = $row['provider'] ?? ($row['provider_type'] ?? 'smscodes');
                                    if ($prov === 'smspva'): ?>
                                    <span class="badge" style="background:rgba(99,102,241,.12);color:#6366f1;border:1px solid rgba(99,102,241,.2);font-size:.65rem;">
                                        <i class="fas fa-server" style="font-size:.55rem;"></i> Server1
                                    </span>
                                    <?php elseif ($prov === '5sim'): ?>
                                    <span class="badge" style="background:rgba(54,185,204,.12);color:#36b9cc;border:1px solid rgba(54,185,204,.2);font-size:.65rem;">
                                        <i class="fas fa-signal" style="font-size:.55rem;"></i> Server3
                                    </span>
                                    <?php elseif ($prov === 'smsbus'): ?>
                                    <span class="badge" style="background:rgba(246,194,62,.12);color:#f6c23e;border:1px solid rgba(246,194,62,.2);font-size:.65rem;">
                                        <i class="fas fa-bus" style="font-size:.55rem;"></i> Server4
                                    </span>
                                    <?php else: ?>
                                    <span class="badge" style="background:rgba(34,184,100,.1);color:#16a354;border:1px solid rgba(34,184,100,.2);font-size:.65rem;">
                                        <i class="fas fa-satellite-dish" style="font-size:.55rem;"></i> Server2
                                    </span>
                                    <?php endif; ?>
                                </td>
                                <td><strong style="color:#4e73df;">NGN<?php echo number_format($row['service_price'], 2); ?></strong></td>
                                <td>
                                    <?php if (!empty($row['sms_text'])): ?>
                                    <button class="btn btn-info btn-sm" onclick="viewSMS('<?php echo htmlspecialchars($row['sms_text'], ENT_QUOTES); ?>')">
                                        <i class="fas fa-sms"></i> View
                                    </button>
                                    <?php else: ?>
                                    <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="status-badge status-<?php echo $status_class; ?>">
                                        <?php echo $status_text; ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="status-badge active-status-<?php echo $active_class; ?>">
                                        <?php echo $active_text; ?>
                                    </span>
                                </td>
                                <td>
                                    <small><?php echo date('M d, Y', strtotime($row['buy_time'])); ?></small><br>
                                    <small class="text-muted"><?php echo date('h:i A', strtotime($row['buy_time'])); ?></small>
                                </td>
                                <td>
                                    <button type="button" class="btn btn-info btn-sm"
                                            onclick="viewDetails(<?php echo $row['id']; ?>)"
                                            title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button type="button" class="btn btn-danger btn-sm"
                                            onclick="deleteNumber(<?php echo $row['id']; ?>)"
                                            title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php else: ?>
                    <div class="text-center py-5">
                        <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">No Numbers Found</h5>
                        <p class="text-muted">No numbers match your search criteria.</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

</div>

<!-- View Number Details Modal -->
<div class="modal fade" id="viewDetailsModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">
                    <i class="fas fa-mobile-alt mr-2"></i>Number Details
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body" id="detailsContent">
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="sr-only">Loading...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- View SMS Modal -->
<div class="modal fade" id="viewSMSModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">
                    <i class="fas fa-sms mr-2"></i>SMS Content
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="sms-text" id="smsContent"></div>
            </div>
        </div>
    </div>
</div>

<script src="vendor/datatables/jquery.dataTables.min.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

<script>
$(document).ready(function() {
    $('#dataTable').DataTable({
        ordering: true,
        pageLength: 25,
        order: [[0, 'desc']]
    });
});

// View number details via AJAX
function viewDetails(numberId) {
    $('#detailsContent').html('<div class="text-center py-4"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></div>');
    $('#viewDetailsModal').modal('show');

    $.ajax({
        url: 'ajax/get_number_details.php',
        type: 'POST',
        data: { number_id: numberId },
        success: function(response) {
            $('#detailsContent').html(response);
        },
        error: function() {
            $('#detailsContent').html('<div class="alert alert-danger">Failed to load number details. Please try again.</div>');
        }
    });
}

// View SMS content
function viewSMS(smsText) {
    $('#smsContent').text(smsText);
    $('#viewSMSModal').modal('show');
}

// Delete number
function deleteNumber(numberId) {
    Swal.fire({
        title: 'Delete Number?',
        text: 'Are you sure you want to delete this number record? This cannot be undone.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Yes, Delete',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Processing...',
                allowOutsideClick: false,
                didOpen: () => { Swal.showLoading(); }
            });

            $.ajax({
                url: 'ajax/delete_number.php',
                type: 'POST',
                data: { number_id: numberId },
                dataType: 'json',
                success: function(data) {
                    Swal.close();
                    if (data.status == '1') {
                        Swal.fire({
                            title: 'Deleted!',
                            text: data.msg,
                            icon: 'success',
                            confirmButtonColor: '#1cc88a'
                        }).then(() => { location.reload(); });
                    } else {
                        Swal.fire('Error!', data.msg, 'error');
                    }
                },
                error: function() {
                    Swal.close();
                    Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
                }
            });
        }
    });
}

// Export to Excel
function exportToExcel() {
    var table = document.getElementById('dataTable');
    var wb = XLSX.utils.table_to_book(table, { sheet: "SMS Numbers" });
    var filename = 'sms_numbers_' + new Date().toISOString().slice(0, 10) + '.xlsx';
    XLSX.writeFile(wb, filename);

    Swal.fire({
        title: 'Exported!',
        text: 'Numbers exported successfully.',
        icon: 'success',
        confirmButtonColor: '#1cc88a',
        timer: 2000,
        showConfirmButton: false
    });
}
</script>

<?php include('include/footer.php'); ?>