<?php
// messages.php - سیستم پیام‌رسانی

session_start();
require_once 'config/database.php';
require_once 'includes/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

if (!isLoggedIn()) {
    header('Location: login.php');
    exit;
}

$user = getCurrentUser();
$pageTitle = 'پیام‌ها';
$pageSubtitle = 'سیستم پیام‌رسانی داخلی';

$messages = fetchAll(
    "SELECT m.*, 
            u1.name as sender_name, u1.family as sender_family,
            u2.name as receiver_name, u2.family as receiver_family,
            r.name as receiver_role_name
     FROM messages m
     LEFT JOIN users u1 ON m.sender_id = u1.id
     LEFT JOIN users u2 ON m.receiver_id = u2.id
     LEFT JOIN roles r ON m.receiver_role_id = r.id
     WHERE m.receiver_id = ? OR m.receiver_role_id = ?
     ORDER BY m.created_at DESC",
    [$user['id'], $user['role_id']]
);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subject = $_POST['subject'] ?? '';
    $body = $_POST['body'] ?? '';
    $receiver_type = $_POST['receiver_type'] ?? 'role';
    $receiver_role_id = $_POST['receiver_role_id'] ?? 0;
    $receiver_id = $_POST['receiver_id'] ?? 0;
    
    if (!empty($subject) && !empty($body)) {
        $data = [
            'sender_id' => $user['id'],
            'subject' => $subject,
            'body' => $body
        ];
        
        if ($receiver_type == 'role') {
            $data['receiver_role_id'] = $receiver_role_id;
        } elseif ($receiver_type == 'user') {
            $data['receiver_id'] = $receiver_id;
        } else {
            // ارسال به همه (all roles)
            // می‌توانید اینجا برای همه نقش‌ها پیام بفرستید
        }
        
        $result = insertData('messages', $data);
        if ($result) {
            $message = 'پیام با موفقیت ارسال شد.';
        } else {
            $message = 'خطا در ارسال پیام.';
        }
    } else {
        $message = 'موضوع و متن پیام را وارد کنید.';
    }
}

$content = 'messages-content.php';
require_once 'includes/layout.php';
?>