<?php
session_start();
require_once 'config.php';

// Check if user is Super Admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 0) {
    header("location: login.php");
    exit;
}

$user_id = $_SESSION["id"];
$error_message = "";
$success_message = "";

// Fetch all schools for selection
$schools_list = [];
if (isset($conn) && $conn instanceof mysqli) {
    $sql = "SELECT school_id, school_name FROM schools ORDER BY school_name";
    if ($result = $conn->query($sql)) {
        while ($row = $result->fetch_assoc()) {
            $schools_list[] = $row;
        }
        $result->free();
    }
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = trim($_POST['title']);
    $message = trim($_POST['message']);
    $broadcast_type = $_POST['broadcast_type'];
    $target_schools = isset($_POST['all_schools']) ? 'all' : implode(',', $_POST['schools'] ?? []);
    
    if (empty($target_schools)) {
        $error_message = "Please select at least one school or check 'All Schools'.";
    } else {
        // Handle file upload
        $attachment_type = 'none';
        $attachment_path = null;
        
        if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
            $upload_dir = 'uploads/broadcasts/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $file_extension = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
            $allowed_extensions = ['pdf', 'jpg', 'jpeg', 'png', 'gif'];
            
            if (in_array($file_extension, $allowed_extensions)) {
                if (in_array($file_extension, ['pdf'])) {
                    $attachment_type = 'pdf';
                } else {
                    $attachment_type = 'image';
                }
                
                $filename = 'broadcast_' . uniqid() . '.' . $file_extension;
                $attachment_path = $upload_dir . $filename;
                move_uploaded_file($_FILES['attachment']['tmp_name'], $attachment_path);
            } else {
                $error_message = "Invalid file type. Only PDF and image files are allowed.";
            }
        }
        
        if (empty($error_message) && isset($conn) && $conn instanceof mysqli) {
            // Check if super_admin_broadcasts table exists
            $check_table = "SHOW TABLES LIKE 'super_admin_broadcasts'";
            $table_exists = $conn->query($check_table)->num_rows > 0;
            
            if ($table_exists) {
                // Insert broadcast
                $sql = "INSERT INTO super_admin_broadcasts (title, message, broadcast_type, target_schools, attachment_type, attachment_path, created_by, status) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, 'sent')";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("ssssssi", $title, $message, $broadcast_type, $target_schools, $attachment_type, $attachment_path, $user_id);
                    $stmt->execute();
                    $stmt->close();
                }
            }
            
            // Determine which schools to send to
            $school_ids = [];
            if ($target_schools === 'all') {
                foreach ($schools_list as $school) {
                    $school_ids[] = $school['school_id'];
                }
            } else {
                $school_ids = explode(',', $target_schools);
            }
            
            // Send message to all admins of selected schools
            $sender_id = $user_id; // Super Admin
            $status = 'Unread';
            
            foreach ($school_ids as $school_id) {
                $school_id = intval($school_id);
                
                // Get all admin users for this school
                $sql_admins = "SELECT id FROM users WHERE school_id = ? AND role = 1";
                if ($stmt_admins = $conn->prepare($sql_admins)) {
                    $stmt_admins->bind_param("i", $school_id);
                    $stmt_admins->execute();
                    $result_admins = $stmt_admins->get_result();
                    
                    while ($admin = $result_admins->fetch_assoc()) {
                        // Insert message with attachment info
                        $message_content = $message;
                        if ($attachment_path) {
                            $message_content .= "\n\n[Attachment: " . basename($attachment_path) . "]\n";
                            $message_content .= "View attachment: <a href='$attachment_path' target='_blank'>Click here</a>";
                        }
                        
                        $sql_msg = "INSERT INTO messages (school_id, sender_id, receiver_id, subject, message_content, status) 
                                    VALUES (?, ?, ?, ?, ?, ?)";
                        if ($stmt_msg = $conn->prepare($sql_msg)) {
                            $stmt_msg->bind_param("iiisss", $school_id, $sender_id, $admin['id'], $title, $message_content, $status);
                            $stmt_msg->execute();
                            $stmt_msg->close();
                        }
                    }
                    $stmt_admins->close();
                }
            }
            
            $success_message = "Broadcast sent successfully to " . count($school_ids) . " school(s)!";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Broadcast Message - Super Admin</title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="images/logo.png" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Fixed Layout Styles */
        body {
            margin: 0;
            padding: 0;
            height: 100vh;
            overflow: hidden;
        }

        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            overflow-y: auto;
            z-index: 1000;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
            margin-left: 250px; /* Adjust based on your sidebar width */
        }

        .header {
            position: sticky;
            top: 0;
            z-index: 999;
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .dashboard-content {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 20px;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .main-content {
                margin-left: 0;
            }
        }

        .broadcast-container {
            max-width: 900px;
            margin: 20px auto;
            background: white;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
        }

        .broadcast-container h2 {
            color: #4f46e5;
            margin-bottom: 30px;
            text-align: center;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group label .required {
            color: #ef4444;
        }

        .form-group input[type="text"],
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.2s;
        }

        .form-group textarea {
            min-height: 150px;
            resize: vertical;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #4f46e5;
        }

        .schools-selection {
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 15px;
            max-height: 300px;
            overflow-y: auto;
        }

        .school-checkbox {
            display: flex;
            align-items: center;
            padding: 8px;
            margin-bottom: 8px;
        }

        .school-checkbox input {
            margin-right: 10px;
        }

        .all-schools-checkbox {
            background-color: #f8f9fa;
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 15px;
            font-weight: 600;
        }

        .file-upload-area {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            background-color: #f8f9fa;
            transition: all 0.3s;
            position: relative;
        }

        .file-upload-area:hover {
            border-color: #4f46e5;
            background-color: #f0f0ff;
        }

        .file-upload-area i {
            font-size: 3em;
            color: #4f46e5;
            margin-bottom: 15px;
        }

        .btn-submit {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            color: white;
            padding: 14px 40px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            width: 100%;
            margin-top: 20px;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
        }

        .alert {
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .alert-success {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #10b981;
        }

        .alert-error {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #ef4444;
        }

        .info-box {
            background-color: #e0e7ff;
            border-left: 4px solid #4f46e5;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
        }

        .info-box i {
            color: #4f46e5;
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <?php include 'includes/super_admin_sidebar.php'; ?>
        
        <div class="main-content">
            <?php include 'includes/super_admin_header.php'; ?>
            
            <div class="dashboard-content">
                <div class="broadcast-container">
                    <h2><i class="fas fa-bullhorn"></i> Send Broadcast Message</h2>

                    <?php if ($error_message): ?>
                        <div class="alert alert-error">
                            <i class="fas fa-exclamation-circle"></i> <?php echo $error_message; ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($success_message): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                        </div>
                    <?php endif; ?>

                    <div class="info-box">
                        <i class="fas fa-info-circle"></i>
                        <strong>Note:</strong> This message will appear on the dashboard of all selected schools' admin users. 
                        Attach PDFs for invoices/documents or images for announcements.
                    </div>

                    <form method="POST" action="" enctype="multipart/form-data">
                        <div class="form-group">
                            <label>Broadcast Type <span class="required">*</span></label>
                            <select name="broadcast_type" required>
                                <option value="general">General Announcement</option>
                                <option value="payment_reminder">Payment Reminder</option>
                                <option value="survey">Survey Request</option>
                                <option value="announcement">Important Announcement</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Message Title <span class="required">*</span></label>
                            <input type="text" name="title" required placeholder="e.g., Payment Reminder for Term 3">
                        </div>

                        <div class="form-group">
                            <label>Message Content <span class="required">*</span></label>
                            <textarea name="message" required placeholder="Enter your message here..."></textarea>
                        </div>

                        <div class="form-group">
                            <label>Target Schools <span class="required">*</span></label>
                            <div class="all-schools-checkbox">
                                <input type="checkbox" id="allSchools" name="all_schools" value="1" onchange="toggleSchoolSelection()">
                                <label for="allSchools" style="display: inline; margin: 0;">Send to All Schools</label>
                            </div>
                            <div class="schools-selection" id="schoolsSelection">
                                <?php foreach ($schools_list as $school): ?>
                                    <div class="school-checkbox">
                                        <input type="checkbox" name="schools[]" value="<?php echo $school['school_id']; ?>" 
                                               id="school_<?php echo $school['school_id']; ?>" class="school-cb">
                                        <label for="school_<?php echo $school['school_id']; ?>" style="margin: 0;">
                                            <?php echo htmlspecialchars($school['school_name']); ?>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Attachment (PDF or Image) - Optional</label>
                            <div class="file-upload-area">
                                <i class="fas fa-cloud-upload-alt"></i>
                                <p>Click to select or drag and drop a file here</p>
                                <input type="file" name="attachment" accept=".pdf,.jpg,.jpeg,.png,.gif" 
                                       style="position: absolute; opacity: 0; width: 100%; height: 100%; top: 0; left: 0; cursor: pointer;">
                                <small>Accepted formats: PDF, JPG, PNG, GIF (Max 10MB)</small>
                            </div>
                        </div>

                        <button type="submit" class="btn-submit">
                            <i class="fas fa-paper-plane"></i> Send Broadcast
                        </button>
                    </form>
                </div>
            </div>
        </div>
        
        <?php include 'includes/super_admin_mobile_nav.php'; ?>
    </div>

    <script>
        function toggleSchoolSelection() {
            const allSchoolsCheckbox = document.getElementById('allSchools');
            const schoolCheckboxes = document.querySelectorAll('.school-cb');
            const schoolsSelection = document.getElementById('schoolsSelection');
            
            if (allSchoolsCheckbox.checked) {
                schoolsSelection.style.opacity = '0.5';
                schoolsSelection.style.pointerEvents = 'none';
                schoolCheckboxes.forEach(cb => cb.checked = false);
            } else {
                schoolsSelection.style.opacity = '1';
                schoolsSelection.style.pointerEvents = 'auto';
            }
        }

        // File upload feedback
        document.querySelector('input[type="file"]').addEventListener('change', function(e) {
            if (this.files.length > 0) {
                const fileName = this.files[0].name;
                const fileSize = (this.files[0].size / 1024 / 1024).toFixed(2);
                this.parentElement.querySelector('p').textContent = `Selected: ${fileName} (${fileSize}MB)`;
            }
        });

        // Sidebar toggle
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');
        
        if (menuToggle) {
            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('collapsed');
                dashboardContainer.classList.toggle('sidebar-collapsed');
            });
        }
    </script>
</body>
</html>
<?php
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>
