<?php
/**
 * SMS লগ ভিউয়ার - সব পাঠানো এসএমএস দেখুন
 */

session_start();

// Check admin role - support both new and legacy session variables
$user_role = $_SESSION['user_role'] ?? $_SESSION['role'] ?? '';
if (!isset($_SESSION['user_id']) || ($user_role !== 'admin')) {
    header('Location: ../login.php');
    exit;
}

require_once(__DIR__ . '/../config/database.php');

// ফিল্টার এবং পেজিনেশন
$page = max(1, intval($_GET['page'] ?? 1));
$limit = 50;
$offset = ($page - 1) * $limit;

$filter_status = $_GET['status'] ?? '';
$filter_phone = $_GET['phone'] ?? '';
$filter_date = $_GET['date'] ?? '';

// বেস কোয়েরি তৈরি করুন
$where = [];
$params = [];

if (!empty($filter_status)) {
    $where[] = "status = ?";
    $params[] = $filter_status;
}

if (!empty($filter_phone)) {
    $where[] = "phone_number LIKE ?";
    $params[] = '%' . $filter_phone . '%';
}

if (!empty($filter_date)) {
    $where[] = "DATE(created_at) = ?";
    $params[] = $filter_date;
}

$whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// মোট রেকর্ড গণনা করুন
try {
    $countStmt = $pdo->prepare("SELECT COUNT(*) as total FROM sms_logs $whereClause");
    $countStmt->execute($params);
    $total = $countStmt->fetch()['total'];
    $totalPages = ceil($total / $limit);
} catch (Exception $e) {
    $total = 0;
    $totalPages = 0;
}

// লগ নিন
try {
    $logsStmt = $pdo->prepare("
        SELECT * FROM sms_logs
        $whereClause
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
    ");
    
    $logsStmt->execute(array_merge($params, [$limit, $offset]));
    $logs = $logsStmt->fetchAll();
} catch (Exception $e) {
    $logs = [];
}

// স্ট্যাটিস্টিক্স
try {
    $statsStmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent,
            SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed,
            SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending
        FROM sms_logs
    ");
    $statsStmt->execute();
    $stats = $statsStmt->fetch();
} catch (Exception $e) {
    $stats = null;
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>এসএমএস লগ ভিউয়ার - Admin</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            color: #333;
            margin-bottom: 5px;
        }
        
        .header p {
            color: #666;
            font-size: 14px;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .stat-box {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .stat-box h3 {
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
            font-weight: 500;
        }
        
        .stat-number {
            font-size: 28px;
            font-weight: bold;
            color: #333;
        }
        
        .stat-box.sent .stat-number {
            color: #28a745;
        }
        
        .stat-box.failed .stat-number {
            color: #dc3545;
        }
        
        .stat-box.pending .stat-number {
            color: #ffc107;
        }
        
        .filters {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .filters h3 {
            margin-bottom: 15px;
            color: #333;
        }
        
        .filter-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
        }
        
        .filter-group label {
            margin-bottom: 5px;
            color: #333;
            font-size: 14px;
            font-weight: 500;
        }
        
        .filter-group input,
        .filter-group select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .filter-group input:focus,
        .filter-group select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 5px rgba(102, 126, 234, 0.3);
        }
        
        .filter-buttons {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 5px;
            font-size: 14px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-search {
            background: #667eea;
            color: white;
        }
        
        .btn-search:hover {
            background: #5568d3;
        }
        
        .btn-reset {
            background: #6c757d;
            color: white;
        }
        
        .btn-reset:hover {
            background: #5a6268;
        }
        
        .logs-table {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow-x: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        thead {
            background: #f5f5f5;
            border-bottom: 2px solid #ddd;
        }
        
        th {
            padding: 12px;
            text-align: left;
            color: #333;
            font-weight: 600;
            font-size: 13px;
        }
        
        td {
            padding: 12px;
            border-bottom: 1px solid #eee;
            font-size: 13px;
        }
        
        tbody tr:hover {
            background: #f9f9f9;
        }
        
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .status-sent {
            background: #d4edda;
            color: #155724;
        }
        
        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }
        
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .phone-code {
            background: #f0f0f0;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: monospace;
        }
        
        .message-preview {
            max-width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            gap: 5px;
            margin-top: 20px;
            padding: 20px;
            background: white;
            border-radius: 10px;
        }
        
        .pagination a,
        .pagination span {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            color: #667eea;
            text-decoration: none;
            cursor: pointer;
        }
        
        .pagination a:hover {
            background: #667eea;
            color: white;
        }
        
        .pagination .active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .pagination .disabled {
            color: #ccc;
            cursor: not-allowed;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .empty-state svg {
            width: 64px;
            height: 64px;
            margin-bottom: 15px;
            opacity: 0.5;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 এসএমএস লগ ভিউয়ার</h1>
            <p>পাঠানো সকল SMS এর বিস্তারিত রেকর্ড</p>
        </div>
        
        <!-- স্ট্যাটিস্টিক্স -->
        <?php if ($stats): ?>
            <div class="stats-grid">
                <div class="stat-box">
                    <h3>মোট SMS</h3>
                    <div class="stat-number"><?php echo number_format($stats['total']); ?></div>
                </div>
                <div class="stat-box sent">
                    <h3>সফল</h3>
                    <div class="stat-number"><?php echo number_format($stats['sent'] ?? 0); ?></div>
                </div>
                <div class="stat-box failed">
                    <h3>ব্যর্থ</h3>
                    <div class="stat-number"><?php echo number_format($stats['failed'] ?? 0); ?></div>
                </div>
                <div class="stat-box pending">
                    <h3>পেন্ডিং</h3>
                    <div class="stat-number"><?php echo number_format($stats['pending'] ?? 0); ?></div>
                </div>
            </div>
        <?php endif; ?>
        
        <!-- ফিল্টার -->
        <div class="filters">
            <h3>🔍 ফিল্টার করুন</h3>
            <form method="GET">
                <div class="filter-row">
                    <div class="filter-group">
                        <label>স্ট্যাটাস</label>
                        <select name="status">
                            <option value="">সব</option>
                            <option value="sent" <?php echo $filter_status === 'sent' ? 'selected' : ''; ?>>সফল</option>
                            <option value="failed" <?php echo $filter_status === 'failed' ? 'selected' : ''; ?>>ব্যর্থ</option>
                            <option value="pending" <?php echo $filter_status === 'pending' ? 'selected' : ''; ?>>পেন্ডিং</option>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label>ফোন নম্বর</label>
                        <input type="text" name="phone" value="<?php echo htmlspecialchars($filter_phone); ?>" placeholder="01...">
                    </div>
                    
                    <div class="filter-group">
                        <label>তারিখ</label>
                        <input type="date" name="date" value="<?php echo htmlspecialchars($filter_date); ?>">
                    </div>
                </div>
                
                <div class="filter-buttons">
                    <button type="submit" class="btn btn-search">🔍 খুঁজুন</button>
                    <a href="<?php echo $_SERVER['PHP_SELF']; ?>" class="btn btn-reset">↺ রিসেট করুন</a>
                </div>
            </form>
        </div>
        
        <!-- লগ টেবিল -->
        <div class="logs-table">
            <?php if (!empty($logs)): ?>
                <table>
                    <thead>
                        <tr>
                            <th>ফোন নম্বর</th>
                            <th>বার্তা</th>
                            <th>টাইপ</th>
                            <th>স্ট্যাটাস</th>
                            <th>API কোড</th>
                            <th>তারিখ এবং সময়</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($logs as $log): ?>
                            <tr>
                                <td>
                                    <span class="phone-code">
                                        <?php echo htmlspecialchars(substr($log['phone_number'], -11)); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="message-preview" title="<?php echo htmlspecialchars($log['message']); ?>">
                                        <?php echo htmlspecialchars(substr($log['message'], 0, 100)); ?>
                                    </div>
                                </td>
                                <td><?php echo ucfirst($log['type']); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $log['status']; ?>">
                                        <?php
                                        $statusText = [
                                            'sent' => 'সফল',
                                            'failed' => 'ব্যর্থ',
                                            'pending' => 'পেন্ডিং'
                                        ];
                                        echo $statusText[$log['status']] ?? ucfirst($log['status']);
                                        ?>
                                    </span>
                                </td>
                                <td>
                                    <?php echo htmlspecialchars($log['api_status_code'] ?? '-'); ?>
                                </td>
                                <td>
                                    <small>
                                        <?php echo date('d M Y H:i', strtotime($log['created_at'])); ?>
                                    </small>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="empty-state">
                    <p>কোনো এসএমএস লগ পাওয়া যায়নি</p>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- পেজিনেশন -->
        <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="?page=1<?php echo !empty($filter_status) ? '&status=' . urlencode($filter_status) : ''; ?>&phone=<?php echo urlencode($filter_phone); ?>&date=<?php echo urlencode($filter_date); ?>">« প্রথম</a>
                    <a href="?page=<?php echo $page - 1; ?><?php echo !empty($filter_status) ? '&status=' . urlencode($filter_status) : ''; ?>&phone=<?php echo urlencode($filter_phone); ?>&date=<?php echo urlencode($filter_date); ?>">‹ আগে</a>
                <?php else: ?>
                    <span class="disabled">« প্রথম</span>
                    <span class="disabled">‹ আগে</span>
                <?php endif; ?>
                
                <?php
                $startPage = max(1, $page - 2);
                $endPage = min($totalPages, $page + 2);
                
                if ($startPage > 1) {
                    echo '<span>...</span>';
                }
                
                for ($i = $startPage; $i <= $endPage; $i++) {
                    if ($i === $page) {
                        echo '<span class="active">' . $i . '</span>';
                    } else {
                        echo '<a href="?page=' . $i . '<?php echo !empty($filter_status) ? \'&status=\' . urlencode($filter_status) : \'\'; ?>&phone=' . urlencode($filter_phone) . '&date=' . urlencode($filter_date) . '">' . $i . '</a>';
                    }
                }
                
                if ($endPage < $totalPages) {
                    echo '<span>...</span>';
                }
                ?>
                
                <?php if ($page < $totalPages): ?>
                    <a href="?page=<?php echo $page + 1; ?><?php echo !empty($filter_status) ? '&status=' . urlencode($filter_status) : ''; ?>&phone=<?php echo urlencode($filter_phone); ?>&date=<?php echo urlencode($filter_date); ?>">পরে ›</a>
                    <a href="?page=<?php echo $totalPages; ?><?php echo !empty($filter_status) ? '&status=' . urlencode($filter_status) : ''; ?>&phone=<?php echo urlencode($filter_phone); ?>&date=<?php echo urlencode($filter_date); ?>">শেষ »</a>
                <?php else: ?>
                    <span class="disabled">পরে ›</span>
                    <span class="disabled">শেষ »</span>
                <?php endif; ?>
            </div>
            
            <div style="text-align: center; margin-top: 10px; color: white; font-size: 14px;">
                পৃষ্ঠা <?php echo $page; ?> এর <?php echo $totalPages; ?> (মোট <?php echo $total; ?> রেকর্ড)
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
