<?php
session_start();
require 'config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'] ?? 'trainee';
$user_specialization = $_SESSION['user_data']['specialization'] ?? '';

function canMessageUser($conn, $user_role, $user_specialization, $recipient_id) {
    $stmt = $conn->prepare("SELECT role, specialization FROM users WHERE id = ? AND is_active = TRUE");
    $stmt->bind_param("i", $recipient_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $recipient = $result->fetch_assoc();
    $stmt->close();

    if (!$recipient) {
        return false;
    }

    if ($user_role === 'admin') {
        return true;
    }

    if ($user_role === 'dosen') {
        return $recipient['role'] === 'trainee' && $recipient['specialization'] === $user_specialization;
    }

    if ($user_role === 'trainee') {
        return $recipient['role'] === 'dosen' && $recipient['specialization'] === $user_specialization;
    }

    return false;
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

// If action not found and POST request, try to get from JSON body
$json_data = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw_body = file_get_contents('php://input');
    if ($raw_body) {
        $json_data = json_decode($raw_body, true) ?? [];
        if (empty($action)) {
            $action = $json_data['action'] ?? '';
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'create') {
    $recipient_id = intval($_POST['recipient_id'] ?? 0);
    $target_type = sanitize($_POST['target_type'] ?? 'user');
    $target_id = isset($_POST['target_id']) ? intval($_POST['target_id']) : null;
    $message = sanitize($_POST['message'] ?? '');

    if ($recipient_id <= 0 || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'Data tidak lengkap']);
        exit();
    }

    if (!in_array($target_type, ['logbook', 'portfolio', 'user'], true)) {
        echo json_encode(['success' => false, 'message' => 'Target tidak valid']);
        exit();
    }

    if (!canMessageUser($conn, $user_role, $user_specialization, $recipient_id)) {
        echo json_encode(['success' => false, 'message' => 'Akses ditolak']);
        exit();
    }

    $stmt = $conn->prepare("INSERT INTO messages (sender_id, recipient_id, target_type, target_id, message) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("iisis", $user_id, $recipient_id, $target_type, $target_id, $message);

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Pesan berhasil dikirim']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal mengirim pesan']);
    }
    $stmt->close();
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'list') {
    $target_type = sanitize($_GET['target_type'] ?? '');
    $target_id = isset($_GET['target_id']) ? intval($_GET['target_id']) : null;

    $query = "
        SELECT m.id, m.sender_id, u.full_name as sender_name, m.recipient_id, m.target_type, m.target_id, m.message, m.is_read, m.created_at,
               l.title as log_title,
               p.diagnosis as portfolio_diagnosis
        FROM messages m
        JOIN users u ON m.sender_id = u.id
        LEFT JOIN logs l ON m.target_type = 'logbook' AND m.target_id = l.id
        LEFT JOIN portfolio p ON m.target_type = 'portfolio' AND m.target_id = p.id
        WHERE m.recipient_id = ?
    ";
    $params = [$user_id];
    $types = "i";

    if ($target_type) {
        $query .= " AND m.target_type = ?";
        $params[] = $target_type;
        $types .= "s";
    }
    if ($target_id !== null) {
        $query .= " AND m.target_id = ?";
        $params[] = $target_id;
        $types .= "i";
    }

    $query .= " ORDER BY m.created_at DESC";

    $stmt = $conn->prepare($query);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    $messages = [];
    while ($row = $result->fetch_assoc()) {
        $messages[] = $row;
    }

    echo json_encode(['success' => true, 'messages' => $messages]);
    $stmt->close();
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'mark_read') {
    $message_id = intval($json_data['message_id'] ?? 0);

    if ($message_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Message ID tidak valid']);
        exit();
    }

    // Verify the message belongs to the current user
    $stmt = $conn->prepare("UPDATE messages SET is_read = TRUE WHERE id = ? AND recipient_id = ?");
    $stmt->bind_param("ii", $message_id, $user_id);

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Pesan ditandai dibaca']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal menandai pesan']);
    }
    $stmt->close();
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'delete') {
    $message_id = intval($json_data['message_id'] ?? 0);

    if ($message_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Message ID tidak valid']);
        exit();
    }

    // Verify the message belongs to the current user before deleting
    $stmt = $conn->prepare("DELETE FROM messages WHERE id = ? AND recipient_id = ?");
    $stmt->bind_param("ii", $message_id, $user_id);

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Pesan berhasil dihapus']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal menghapus pesan']);
    }
    $stmt->close();
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'delete_all') {
    // Delete all messages for the current user
    $stmt = $conn->prepare("DELETE FROM messages WHERE recipient_id = ?");
    $stmt->bind_param("i", $user_id);

    if ($stmt->execute()) {
        $deleted_count = $stmt->affected_rows;
        echo json_encode(['success' => true, 'message' => "Berhasil menghapus $deleted_count pesan"]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal menghapus pesan']);
    }
    $stmt->close();
    exit();
}

echo json_encode(['success' => false, 'message' => 'Invalid request']);
