<?php
session_start();
require_once '../config/database.php';
require_once '../includes/sms_helper.php';

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];

// Get filter parameters
$message_type = $_GET['type'] ?? '';
$status = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

// Build query with filters
$where_conditions = ["method = 'non_musking'"];
$params = [];

if (!empty($message_type)) {
    $where_conditions[] = "message_type = ?";
    $params[] = $message_type;
}

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

if (!empty($date_from)) {
    $where_conditions[] = "DATE(sent_at) >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(sent_at) <= ?";
    $params[] = $date_to;
}

$where_clause = implode(' AND ', $where_conditions);
$order_by = "sent_at DESC";

$sql = "SELECT * FROM messages_log WHERE $where_clause ORDER BY $order_by";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$messages = $stmt->fetchAll();

// Get message types for filter dropdown
$type_stmt = $pdo->query("SELECT DISTINCT message_type FROM messages_log WHERE method = 'non_musking' ORDER BY message_type");
$message_types = $type_stmt->fetchAll();

// Get statuses for filter dropdown
$status_stmt = $pdo->query("SELECT DISTINCT status FROM messages_log WHERE method = 'non_musking' ORDER BY status");
$statuses = $status_stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>মেসেজ লগ - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-md-12">
                <h2><i class="fas fa-history"></i> মেসেজ লগ এবং ডেলিভারি স্ট্যাটাস</h2>
            </div>
        </div>

        <!-- Filters -->
        <div class="row mt-3">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label for="type" class="form-label">মেসেজের ধরন</label>
                                <select class="form-select" id="type" name="type">
                                    <option value="">সব ধরন</option>
                                    <?php foreach ($message_types as $type): ?>
                                        <option value="<?php echo $type['message_type']; ?>" <?php echo ($message_type == $type['message_type']) ? 'selected' : ''; ?>>
                                            <?php echo $type['message_type']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="status" class="form-label">অবস্থা</label>
                                <select class="form-select" id="status" name="status">
                                    <option value="">সব অবস্থা</option>
                                    <?php foreach ($statuses as $status_row): ?>
                                        <option value="<?php echo $status_row['status']; ?>" <?php echo ($status == $status_row['status']) ? 'selected' : ''; ?>>
                                            <?php echo $status_row['status']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="date_from" class="form-label">তারিখ হতে</label>
                                <input type="date" class="form-control" id="date_from" name="date_from" value="<?php echo $date_from; ?>">
                            </div>
                            <div class="col-md-3">
                                <label for="date_to" class="form-label">তারিখ পর্যন্ত</label>
                                <input type="date" class="form-control" id="date_to" name="date_to" value="<?php echo $date_to; ?>">
                            </div>
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-filter"></i> ফিল্টার
                                </button>
                                <a href="message_logs.php" class="btn btn-secondary">
                                    <i class="fas fa-sync"></i> রিসেট
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Messages Table -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-list"></i> মেসেজ লগ</h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($messages)): ?>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle"></i> কোনো মেসেজ পাওয়া যায়নি।
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>তারিখ</th>
                                            <th>ধরন</th>
                                            <th>মেসেজ</th>
                                            <th>প্রাপক</th>
                                            <th>পাঠানো হয়েছে</th>
                                            <th>ব্যর্থ</th>
                                            <th>অবস্থা</th>
                                            <th>পৌঁছেছে</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($messages as $msg): ?>
                                            <tr>
                                                <td><?php echo date('d/m/Y H:i', strtotime($msg['sent_at'])); ?></td>
                                                <td>
                                                    <?php 
                                                        $type_map = [
                                                            'notice' => 'নোটিশ',
                                                            'event' => 'ইভেন্ট',
                                                            'exam' => 'পরীক্ষা',
                                                            'fee' => 'ফি',
                                                            'general' => 'সাধারণ'
                                                        ]; 
                                                        echo $type_map[$msg['message_type']] ?? $msg['message_type'];
                                                    ?>
                                                </td>
                                                <td>
                                                    <div class="message-preview" style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                                        <?php echo htmlspecialchars($msg['message_content']); ?>
                                                    </div>
                                                </td>
                                                <td><?php echo $msg['recipient_count']; ?> জন</td>
                                                <td>
                                                    <?php 
                                                        $sent_count = count(json_decode($msg['sent_recipients'], true) ?: []);
                                                        echo $sent_count;
                                                    ?>
                                                </td>
                                                <td>
                                                    <?php 
                                                        $failed_count = count(json_decode($msg['failed_recipients'], true) ?: []);
                                                        echo $failed_count;
                                                    ?>
                                                </td>
                                                <td>
                                                    <span class="badge 
                                                        <?php 
                                                            switch($msg['status']) {
                                                                case 'delivered': echo 'bg-success'; break;
                                                                case 'sent': echo 'bg-info'; break;
                                                                case 'failed': echo 'bg-danger'; break;
                                                                case 'partial': echo 'bg-warning'; break;
                                                                default: echo 'bg-secondary'; break;
                                                            }
                                                        ?>
                                                    ">
                                                        <?php 
                                                            $status_map = [
                                                                'delivered' => 'পৌঁছেছে',
                                                                'sent' => 'পাঠানো হয়েছে',
                                                                'failed' => 'ব্যর্থ',
                                                                'partial' => 'আংশিক',
                                                                'pending' => 'অপেক্ষারত'
                                                            ];
                                                            echo $status_map[$msg['status']] ?? $msg['status'];
                                                        ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?php if ($msg['delivered_at']): ?>
                                                        <span class="text-success">
                                                            <i class="fas fa-check-circle"></i> 
                                                            <?php echo date('d/m/Y H:i', strtotime($msg['delivered_at'])); ?>
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="d-flex justify-content-between align-items-center mt-3">
                                <div>
                                    <span>মোট মেসেজ: <?php echo count($messages); ?></span>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>