<?php
session_start();
include('../../../includes/config.php');

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../../index.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$reply_to_id = isset($_GET['reply_to']) ? (int)$_GET['reply_to'] : null;
$thread_id = null;
$subject = '';
$receiver_id = null;

// If replying, fetch original message
if ($reply_to_id) {
    $stmt = $conn->prepare("SELECT * FROM messages WHERE id = ?");
    $stmt->bind_param("i", $reply_to_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $original = $result->fetch_assoc();

    if ($original) {
        if ($original['sender_id'] != $user_id && $original['receiver_id'] != $user_id) {
            die("Unauthorized access to reply.");
        }

        $thread_id = $original['thread_id'] ?: $original['id'];
        $subject = $original['subject'];
        if (stripos($subject, 'RE:') !== 0) {
            $subject = 'RE: ' . $subject;
        }

        $receiver_id = ($original['sender_id'] == $user_id) ? $original['receiver_id'] : $original['sender_id'];
    }
}

$users = $conn->query("SELECT id, CONCAT(first_name, ' ', last_name) AS name FROM users WHERE id != {$user_id}");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?= $reply_to_id ? 'Reply to Message' : 'Compose Message' ?></title>
    <link rel="stylesheet" href="/digital_pos/css/messagings" />
    <style>
        /* Gmail-like layout */
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f1f3f4;
            display: flex;
            height: 100vh;
        }

        .sidebar {
            width: 240px;
            background-color: #fff;
            padding: 20px;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
        }

        .sidebar h3 {
            margin-bottom: 20px;
            color: #202124;
        }

        .sidebar a {
            display: block;
            color: #202124;
            padding: 10px 15px;
            margin-bottom: 8px;
            border-radius: 4px;
            text-decoration: none;
        }

        .sidebar a:hover,
        .sidebar a.active {
            background-color: #e8f0fe;
            color: #1a73e8;
        }

        .main-content {
            flex: 1;
            padding: 30px;
            overflow-y: auto;
        }

        form {
            background: #fff;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }

        form label {
            display: block;
            margin-top: 15px;
            font-weight: bold;
        }

        form input[type="text"],
        form select,
        form textarea,
        form input[type="file"] {
            width: 100%;
            padding: 10px;
            margin-top: 5px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .note {
            font-size: 0.85em;
            color: #555;
            margin-top: 5px;
        }

        .error-message {
            color: red;
            font-size: 0.9em;
            display: none;
            margin-top: 5px;
        }

        button {
            margin-top: 20px;
            padding: 10px 25px;
            background-color: #1a73e8;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:disabled {
            background-color: #c6dafc;
        }
    </style>
</head>
<body>

<!-- Sidebar -->
<div class="sidebar">
    <h3>Messaging</h3>
    <a href="inbox.php">Inbox</a>
    <a href="sent.php">Sent</a>
    <a href="compose.php" class="active">Compose</a>
</div>

<!-- Main content -->
<div class="main-content">
    <h2><?= $reply_to_id ? "Reply to Message" : "Compose Message" ?></h2>

    <form id="composeForm" action="send_message.php" method="POST" enctype="multipart/form-data" novalidate>
        <?php if ($reply_to_id): ?>
            <input type="hidden" name="thread_id" value="<?= htmlspecialchars($thread_id) ?>">
            <input type="hidden" name="parent_id" value="<?= htmlspecialchars($reply_to_id) ?>">
        <?php endif; ?>

        <label for="receiver_id">To:</label>
        <select name="receiver_id" id="receiver_id" required <?= $reply_to_id ? 'disabled' : '' ?>>
            <?php if ($users->num_rows > 0): ?>
                <?php while ($row = $users->fetch_assoc()): ?>
                    <option value="<?= htmlspecialchars($row['id']) ?>" <?= $row['id'] == $receiver_id ? 'selected' : '' ?>>
                        <?= htmlspecialchars($row['name']) ?>
                    </option>
                <?php endwhile; ?>
            <?php else: ?>
                <option disabled selected>No users available</option>
            <?php endif; ?>
        </select>
        <?php if ($reply_to_id): ?>
            <input type="hidden" name="receiver_id" value="<?= htmlspecialchars($receiver_id) ?>">
        <?php endif; ?>

        <label for="subject">Subject:</label>
        <input type="text" name="subject" id="subject" required minlength="2" maxlength="255"
               placeholder="Enter message subject" value="<?= htmlspecialchars($subject) ?>">

        <label for="body">Message:</label>
        <textarea name="body" id="body" rows="6" required minlength="5"
                  placeholder="Write your message here..."></textarea>

        <label for="attachment">Attachment (optional):</label>
        <input type="file" name="attachment" id="attachment"
               accept=".jpg,.jpeg,.png,.pdf,.doc,.docx,.xls,.xlsx,.txt,.zip">
        <div class="note">Allowed types: JPG, PNG, PDF, DOC, XLS, TXT, ZIP | Max size: 5MB</div>
        <div id="fileError" class="error-message">Invalid file. Please choose a valid file under 5MB.</div>

        <button type="submit" id="sendBtn" disabled>Send</button>
    </form>
</div>

<script>
    const sendBtn = document.getElementById('sendBtn');
    const form = document.getElementById('composeForm');
    const attachmentInput = document.getElementById('attachment');
    const fileError = document.getElementById('fileError');
    const receiverSelect = document.getElementById('receiver_id');
    const subjectInput = document.getElementById('subject');
    const bodyInput = document.getElementById('body');

    const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf',
        'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/plain', 'application/zip'];
    const maxSize = 5 * 1024 * 1024;

    function validateFile() {
        fileError.style.display = 'none';
        if (attachmentInput.files.length === 0) {
            return true;
        }
        const file = attachmentInput.files[0];
        if (!allowedTypes.includes(file.type)) {
            fileError.textContent = 'Unsupported file type.';
            fileError.style.display = 'block';
            return false;
        }
        if (file.size > maxSize) {
            fileError.textContent = 'File size exceeds 5MB.';
            fileError.style.display = 'block';
            return false;
        }
        return true;
    }

    function validateForm() {
        const isFileValid = validateFile();
        const isReceiverSelected = receiverSelect.value.trim() !== '';
        const isSubjectValid = subjectInput.value.trim().length >= 2 && subjectInput.value.trim().length <= 255;
        const isBodyValid = bodyInput.value.trim().length >= 5;

        sendBtn.disabled = !(isFileValid && isReceiverSelected && isSubjectValid && isBodyValid);
    }

    attachmentInput.addEventListener('change', validateForm);
    receiverSelect.addEventListener('change', validateForm);
    subjectInput.addEventListener('input', validateForm);
    bodyInput.addEventListener('input', validateForm);

    validateForm();

    form.addEventListener('submit', e => {
        if (sendBtn.disabled) {
            e.preventDefault();
            alert('Please fill in all required fields correctly.');
        }
    });
</script>

</body>
</html>
