<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';

$msg = '';
$error = '';

// Create necessary tables if not exists
$conn->query("CREATE TABLE IF NOT EXISTS patient_notifications (
    id INT AUTO_INCREMENT PRIMARY KEY,
    patient_id VARCHAR(50) NOT NULL,
    title VARCHAR(255) NOT NULL,
    message TEXT NOT NULL,
    type ENUM('info','success','warning','danger') DEFAULT 'info',
    is_read TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$conn->query("CREATE TABLE IF NOT EXISTS doctor_notifications (
    id INT AUTO_INCREMENT PRIMARY KEY,
    doctor_id INT NOT NULL,
    title VARCHAR(255),
    message TEXT,
    type VARCHAR(50) DEFAULT 'info',
    is_read TINYINT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = $conn->real_escape_string($_POST['title']);
    $message = $conn->real_escape_string($_POST['message']);
    $type = $_POST['type'];
    $recipient = $_POST['recipient'];
    
    $count = 0;
    
    if ($recipient == 'patients' || $recipient == 'all') {
        $patients = $conn->query("SELECT patient_id FROM patients WHERE portal_active = 1");
        while ($p = $patients->fetch_assoc()) {
            $stmt = $conn->prepare("INSERT INTO patient_notifications (patient_id, title, message, type) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $p['patient_id'], $title, $message, $type);
            if ($stmt->execute()) $count++;
            $stmt->close();
        }
        $msg = "Broadcast sent to $count patients!";
    }
    
    if ($recipient == 'doctors' || $recipient == 'all') {
        $doctors = $conn->query("SELECT doctor_id FROM doctors WHERE status = 'active'");
        while ($d = $doctors->fetch_assoc()) {
            $stmt = $conn->prepare("INSERT INTO doctor_notifications (doctor_id, title, message, type) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("isss", $d['doctor_id'], $title, $message, $type);
            if ($stmt->execute()) $count++;
            $stmt->close();
        }
        if ($recipient == 'doctors') $msg = "Broadcast sent to $count doctors!";
    }
    
    if ($recipient == 'all') {
        $msg = "Broadcast sent to all patients and doctors!";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Broadcast Message - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: #0a3d2f; font-family: 'Segoe UI', sans-serif; }
        .navbar { background: #064e3b !important; }
        .card { border-radius: 20px; background: rgba(255,255,255,0.95); border: none; }
        .card-header { background: linear-gradient(135deg, #0f6b4c, #064e3b); color: white; border-radius: 20px 20px 0 0; }
        .btn-primary { background: #0f6b4c; border: none; border-radius: 30px; padding: 10px; }
        .btn-primary:hover { background: #0a523b; }
        .form-control, .form-select { border-radius: 12px; padding: 10px 15px; }
        @media (max-width: 768px) { .container { padding: 10px; } }
    </style>
</head>
<body>
<nav class="navbar navbar-dark">
    <div class="container">
        <span class="navbar-brand"><i class="fas fa-broadcast-tower me-2"></i> Broadcast Message</span>
        <a href="dashboard.php" class="btn btn-light btn-sm"><i class="fas fa-arrow-left"></i> Back</a>
    </div>
</nav>

<div class="container mt-4">
    <div class="card">
        <div class="card-header">
            <i class="fas fa-globe me-2"></i> Send Broadcast to All Users
        </div>
        <div class="card-body">
            <?php if($msg): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="fas fa-check-circle me-2"></i> <?= htmlspecialchars($msg) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            <?php if($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-triangle me-2"></i> <?= htmlspecialchars($error) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <strong>Warning:</strong> This will send a notification to ALL patients and doctors in the system. Use with caution.
            </div>
            
            <form method="POST">
                <div class="mb-3">
                    <label class="form-label fw-semibold"><i class="fas fa-users me-1"></i> Send To</label>
                    <select name="recipient" class="form-select" required>
                        <option value="patients">All Patients Only</option>
                        <option value="doctors">All Doctors Only</option>
                        <option value="all">All Patients and Doctors</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-semibold"><i class="fas fa-tag me-1"></i> Message Type</label>
                    <select name="type" class="form-select" required>
                        <option value="info">📘 Information</option>
                        <option value="success">✅ Success / Good News</option>
                        <option value="warning">⚠️ Warning</option>
                        <option value="danger">🚨 Urgent / Emergency</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-semibold"><i class="fas fa-heading me-1"></i> Title</label>
                    <input type="text" name="title" class="form-control" placeholder="e.g., System Maintenance, New Feature Available, Health Alert" required>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-semibold"><i class="fas fa-envelope me-1"></i> Message</label>
                    <textarea name="message" class="form-control" rows="5" placeholder="Enter your broadcast message here..." required></textarea>
                </div>
                
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-paper-plane me-2"></i> Send Broadcast
                </button>
            </form>
        </div>
    </div>
</div>

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