<?php
// Ensure database table exists
mysqli_query($connection, "CREATE TABLE IF NOT EXISTS internal_mail (
    id INT AUTO_INCREMENT PRIMARY KEY,
    sender_id VARCHAR(50) DEFAULT '0',
    sender_name VARCHAR(100) DEFAULT '',
    sender_role VARCHAR(50) DEFAULT '',
    recipient_type VARCHAR(50) DEFAULT '',
    recipient_id VARCHAR(50) DEFAULT '',
    recipient_name VARCHAR(100) DEFAULT '',
    subject VARCHAR(255) DEFAULT '',
    message TEXT,
    is_read TINYINT(1) DEFAULT 0,
    sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$sender_id   = $_SESSION['user_id'] ?? $_SESSION['admin_id'] ?? $_SESSION['staff'] ?? 0;
$sender_name = $_SESSION['admin_name'] ?? $_SESSION['staff_name'] ?? $_SESSION['name'] ?? $_SESSION['student_name'] ?? 'User';
$sender_role = $_SESSION['role_name'] ?? 'staff';

// SEND MAIL
if (isset($_POST['send_mail_btn'])) {
    $subject        = mysqli_real_escape_string($connection, $_POST['subject'] ?? '');
    $message        = mysqli_real_escape_string($connection, $_POST['message'] ?? '');
    $recipient_type = mysqli_real_escape_string($connection, $_POST['recipient_type'] ?? '');
    $recipient_id   = '';
    $recipient_name = '';

    if ($recipient_type === 'student') {
        $recipient_id   = mysqli_real_escape_string($connection, $_POST['recipient_student'] ?? '');
        $res = mysqli_query($connection, "SELECT CONCAT_WS(' ', firstname, othername, lastname) AS name FROM students WHERE reg_number='$recipient_id' LIMIT 1");
        $recipient_name = ($res && ($r = mysqli_fetch_assoc($res))) ? $r['name'] : $recipient_id;
    } elseif ($recipient_type === 'teacher') {
        $recipient_id   = mysqli_real_escape_string($connection, $_POST['recipient_teacher'] ?? '');
        $res = mysqli_query($connection, "SELECT name FROM staff WHERE id='$recipient_id' LIMIT 1");
        $recipient_name = ($res && ($r = mysqli_fetch_assoc($res))) ? $r['name'] : "Staff #$recipient_id";
    } elseif ($recipient_type === 'all') {
        $recipient_name = 'All Users';
    } elseif ($recipient_type === 'admin') {
        $recipient_name = 'Admin / Management';
    }

    $stmt = $connection->prepare("INSERT INTO internal_mail (sender_id, sender_name, sender_role, recipient_type, recipient_id, recipient_name, subject, message) VALUES (?,?,?,?,?,?,?,?)");
    if ($stmt) {
        $stmt->bind_param("ssssssss", $sender_id, $sender_name, $sender_role, $recipient_type, $recipient_id, $recipient_name, $subject, $message);
        if ($stmt->execute()) {
            $_SESSION['msg']  = "Message sent successfully.";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg']  = "Failed to send: " . $stmt->error;
            $_SESSION['type'] = "danger";
        }
        $stmt->close();
    } else {
        $_SESSION['msg']  = "Failed to send message: Database error.";
        $_SESSION['type'] = "danger";
    }
    header("Location: mailbox");
    exit;
}

// MARK AS READ
if (isset($_GET['read'])) {
    $mid = (int)$_GET['read'];
    mysqli_query($connection, "UPDATE internal_mail SET is_read=1 WHERE id=$mid");
}

// DELETE MAIL
if (isset($_GET['delete_mail'])) {
    $mid = (int)$_GET['delete_mail'];
    mysqli_query($connection, "DELETE FROM internal_mail WHERE id=$mid");
    $_SESSION['msg']  = "Message deleted.";
    $_SESSION['type'] = "success";
    header("Location: mailbox");
    exit;
}

// INBOX — messages sent to me or to 'all'
$reg_clean = mysqli_real_escape_string($connection, $_SESSION['reg_number'] ?? '');
$sender_id_clean = mysqli_real_escape_string($connection, (string)$sender_id);
$inbox_sql = "SELECT * FROM internal_mail WHERE recipient_type='all'
              OR (recipient_type='student' AND recipient_id='$reg_clean' AND recipient_id != '')
              OR (recipient_type='teacher' AND recipient_id='$sender_id_clean')
              OR (recipient_type='admin')
              ORDER BY sent_at DESC";
$inbox = mysqli_query($connection, $inbox_sql);
$unread_query = mysqli_query($connection, "SELECT id FROM internal_mail WHERE is_read=0");
$unread = ($unread_query && $unread_query instanceof mysqli_result) ? mysqli_num_rows($unread_query) : 0;

// SENT — messages I sent
$sent  = mysqli_query($connection, "SELECT * FROM internal_mail WHERE sender_id='$sender_id_clean' ORDER BY sent_at DESC");

$view_mail = null;
if (isset($_GET['read'])) {
    $mid       = (int)$_GET['read'];
    $res       = mysqli_query($connection, "SELECT * FROM internal_mail WHERE id=$mid LIMIT 1");
    $view_mail = ($res && $res instanceof mysqli_result) ? mysqli_fetch_assoc($res) : null;
}
?>

<div class="page-title">
    <div>
        <h1><i class="fa fa-envelope"></i> Internal Mailbox</h1>
        <p>Send and receive messages within the school portal</p>
    </div>
    <div>
        <button class="btn btn-primary" data-toggle="modal" data-target="#composeModal">
            <i class="fa fa-pencil"></i> Compose Message
        </button>
    </div>
</div>

<div class="row">
    <!-- Sidebar Nav -->
    <div class="col-md-2">
        <div class="list-group shadow-sm border-0">
            <a href="mailbox" class="list-group-item list-group-item-action <?= (!isset($_GET['tab']) || $_GET['tab'] !== 'sent') ? 'active' : '' ?>">
                <i class="fa fa-inbox mr-2"></i> Inbox
                <?php if ($unread > 0): ?>
                    <span class="badge badge-danger float-right"><?= $unread ?></span>
                <?php endif; ?>
            </a>
            <a href="mailbox?tab=sent" class="list-group-item list-group-item-action <?= (isset($_GET['tab']) && $_GET['tab'] === 'sent') ? 'active' : '' ?>">
                <i class="fa fa-paper-plane mr-2"></i> Sent
            </a>
        </div>
    </div>

    <!-- Mail Content -->
    <div class="col-md-10">
        <?php if ($view_mail): ?>
        <!-- Read View -->
        <div class="card border-0 shadow-sm p-4" style="background:#fff; border-radius:8px; padding:20px; box-shadow:0 2px 4px rgba(0,0,0,0.08);">
            <h4 class="font-weight-bold"><?= htmlspecialchars($view_mail['subject'] ?? '') ?></h4>
            <p class="text-muted small">
                From: <strong><?= htmlspecialchars($view_mail['sender_name'] ?? '') ?></strong> &nbsp;|&nbsp;
                To: <strong><?= ($view_mail['recipient_type'] ?? '') == 'all' ? 'Everyone' : htmlspecialchars($view_mail['recipient_name'] ?? '') ?></strong> &nbsp;|&nbsp;
                <?= !empty($view_mail['sent_at']) ? date('d M Y, h:i A', strtotime($view_mail['sent_at'])) : '' ?>
            </p>
            <hr>
            <div class="mail-body" style="white-space: pre-wrap; line-height: 1.8; font-size: 15px; margin: 20px 0;">
                <?= nl2br(htmlspecialchars($view_mail['message'] ?? '')) ?>
            </div>
            <div class="mt-3">
                <a href="mailbox" class="btn btn-sm btn-secondary"><i class="fa fa-arrow-left"></i> Back</a>
                <a href="mailbox?delete_mail=<?= $view_mail['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this message?')">
                    <i class="fa fa-trash"></i> Delete
                </a>
            </div>
        </div>

        <?php elseif (isset($_GET['tab']) && $_GET['tab'] === 'sent'): ?>
        <!-- Sent Box -->
        <div class="card border-0 shadow-sm" style="background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.08);">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="bg-light">
                        <tr><th>To</th><th>Subject</th><th>Date</th><th>Action</th></tr>
                    </thead>
                    <tbody>
                        <?php if ($sent && ($sent instanceof mysqli_result) && mysqli_num_rows($sent) > 0): ?>
                            <?php while ($row = mysqli_fetch_assoc($sent)): ?>
                            <tr>
                                <td><?= ($row['recipient_type'] ?? '') == 'all' ? '<span class="badge badge-info">Everyone</span>' : htmlspecialchars($row['recipient_name'] ?? '') ?></td>
                                <td><?= htmlspecialchars($row['subject'] ?? '') ?></td>
                                <td class="text-muted small"><?= !empty($row['sent_at']) ? date('d M Y', strtotime($row['sent_at'])) : '' ?></td>
                                <td>
                                    <a href="mailbox?read=<?= $row['id'] ?>" class="btn btn-xs btn-info"><i class="fa fa-eye"></i></a>
                                    <a href="mailbox?delete_mail=<?= $row['id'] ?>" class="btn btn-xs btn-danger" onclick="return confirm('Delete?')"><i class="fa fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="4" class="text-center text-muted p-4">No sent messages yet.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php else: ?>
        <!-- Inbox -->
        <div class="card border-0 shadow-sm" style="background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.08);">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="bg-light">
                        <tr><th>From</th><th>Subject</th><th>Date</th><th>Status</th><th>Action</th></tr>
                    </thead>
                    <tbody>
                        <?php if ($inbox && ($inbox instanceof mysqli_result) && mysqli_num_rows($inbox) > 0): ?>
                            <?php while ($row = mysqli_fetch_assoc($inbox)): ?>
                            <tr class="<?= !empty($row['is_read']) ? '' : 'font-weight-bold' ?>">
                                <td><?= htmlspecialchars($row['sender_name'] ?? '') ?> <span class="badge badge-secondary small"><?= htmlspecialchars($row['sender_role'] ?? '') ?></span></td>
                                <td><?= htmlspecialchars($row['subject'] ?? '') ?></td>
                                <td class="text-muted small"><?= !empty($row['sent_at']) ? date('d M Y', strtotime($row['sent_at'])) : '' ?></td>
                                <td><?= !empty($row['is_read']) ? '<span class="badge badge-light">Read</span>' : '<span class="badge badge-primary">New</span>' ?></td>
                                <td>
                                    <a href="mailbox?read=<?= $row['id'] ?>" class="btn btn-xs btn-info"><i class="fa fa-eye"></i> Read</a>
                                    <a href="mailbox?delete_mail=<?= $row['id'] ?>" class="btn btn-xs btn-danger" onclick="return confirm('Delete?')"><i class="fa fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="5" class="text-center text-muted p-4"><i class="fa fa-inbox fa-2x d-block mb-2"></i>Your inbox is empty.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Compose Modal -->
<div class="modal fade" id="composeModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <form method="POST">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title"><i class="fa fa-pencil mr-2"></i> Compose New Message</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Send To</label>
                        <select name="recipient_type" id="recipientType" class="form-control" onchange="toggleRecipient(this.value)" required>
                            <option value="">-- Select Recipient --</option>
                            <option value="all">📢 Everyone (Broadcast)</option>
                            <option value="admin">🔑 Admin / Management</option>
                            <option value="teacher">👨‍🏫 Specific Teacher</option>
                            <option value="student">🎓 Specific Student</option>
                        </select>
                    </div>
                    <div id="teacherSelect" style="display:none" class="form-group">
                        <label>Select Teacher</label>
                        <select name="recipient_teacher" class="form-control">
                            <?php
                            $staff_res = mysqli_query($connection, "SELECT id, name FROM staff ORDER BY name");
                            if ($staff_res && ($staff_res instanceof mysqli_result)) {
                                while ($s = mysqli_fetch_assoc($staff_res)) {
                                    echo "<option value='" . htmlspecialchars($s['id']) . "'>" . htmlspecialchars($s['name']) . "</option>";
                                }
                            }
                            ?>
                        </select>
                    </div>
                    <div id="studentSelect" style="display:none" class="form-group">
                        <label>Select Student (Reg No)</label>
                        <select name="recipient_student" class="form-control">
                            <?php
                            $stu_res = mysqli_query($connection, "SELECT reg_number, CONCAT_WS(' ', firstname, othername, lastname) AS name FROM students ORDER BY firstname, lastname");
                            if ($stu_res && ($stu_res instanceof mysqli_result)) {
                                while ($s = mysqli_fetch_assoc($stu_res)) {
                                    echo "<option value='" . htmlspecialchars($s['reg_number']) . "'>" . htmlspecialchars($s['name']) . " (" . htmlspecialchars($s['reg_number']) . ")</option>";
                                }
                            }
                            ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Subject</label>
                        <input type="text" name="subject" class="form-control" placeholder="Message subject..." required>
                    </div>
                    <div class="form-group">
                        <label>Message</label>
                        <textarea name="message" class="form-control" rows="6" placeholder="Type your message..." required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="send_mail_btn" class="btn btn-primary">
                        <i class="fa fa-paper-plane mr-1"></i> Send Message
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function toggleRecipient(type) {
    var teacherBox = document.getElementById('teacherSelect');
    var studentBox = document.getElementById('studentSelect');
    if (teacherBox) teacherBox.style.display = (type === 'teacher') ? 'block' : 'none';
    if (studentBox) studentBox.style.display = (type === 'student') ? 'block' : 'none';
}
</script>
