<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/iscms_layout.php';

$conn = iscms_init();
$pageTitle = 'Messaging';
$activeNav = 'dashboard';

$tab = preg_replace('/[^a-z]/', '', (string) ($_GET['tab'] ?? 'inbox')) ?: 'inbox';
$mid = trim((string) ($_GET['mid'] ?? ''));
$uid = (string) ($_SESSION['user_id'] ?? '');

$errors = [];
$composeOk = false;

if (!iscms_table_exists($conn, 'internal_messages')) {
    iscms_render_head($pageTitle);
    iscms_render_sidebar($activeNav);
    iscms_render_topbar($pageTitle);
    ?>
    <div class="page-header">
        <h1>Messaging</h1>
        <p>Internal messaging requires the database table to be installed.</p>
    </div>
    <div class="section-card">
        <div class="p-3" style="font-size:.9rem">
            <p class="mb-2">Run the SQL script <code class="iscms-mono">install_internal_messaging.sql</code> on your database, then reload this page.</p>
            <div class="quick-actions mt-3">
                <a class="qa-btn" href="notifications.php"><i class="ri-notification-3-line"></i> Notifications</a>
                <a class="qa-btn" href="application_comments.php"><i class="ri-chat-1-line"></i> Application comments</a>
            </div>
        </div>
    </div>
    <?php
    iscms_render_footer();
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'send_message') {
    if (!iscms_csrf_validate($_POST['csrf_token'] ?? null)) {
        $errors[] = 'Invalid security token.';
    } else {
        $to = trim((string) ($_POST['recipient_id'] ?? ''));
        $subj = trim((string) ($_POST['subject'] ?? ''));
        $body = trim((string) ($_POST['body'] ?? ''));
        if ($to === '' || $subj === '' || $body === '') {
            $errors[] = 'Recipient, subject, and message are required.';
        } elseif ($to === $uid) {
            $errors[] = 'You cannot send a message to yourself.';
        } else {
            $chk = $conn->prepare('SELECT id FROM users WHERE id = ? AND status IN (\'active\',\'pending_verification\') LIMIT 1');
            if ($chk) {
                $chk->bind_param('s', $to);
                $chk->execute();
                if ($chk->get_result()->num_rows === 0) {
                    $errors[] = 'Recipient is not valid.';
                }
                $chk->close();
            }
        }
        if ($errors === []) {
            $ins = $conn->prepare(
                'INSERT INTO internal_messages (id, sender_id, recipient_id, subject, body)
                 VALUES (UUID(), ?, ?, ?, ?)'
            );
            if ($ins) {
                $ins->bind_param('ssss', $uid, $to, $subj, $body);
                if ($ins->execute()) {
                    $composeOk = true;
                    $tab = 'sent';
                } else {
                    $errors[] = 'Could not send message.';
                }
                $ins->close();
            }
        }
    }
}

if ($mid !== '' && $tab === 'view') {
    $st = $conn->prepare(
        'SELECT m.*,
                CONCAT(TRIM(s.first_name),\' \',TRIM(s.last_name)) AS sender_name,
                CONCAT(TRIM(r.first_name),\' \',TRIM(r.last_name)) AS recipient_name,
                s.email AS sender_email, r.email AS recipient_email
         FROM internal_messages m
         INNER JOIN users s ON m.sender_id = s.id
         INNER JOIN users r ON m.recipient_id = r.id
         WHERE m.id = ? LIMIT 1'
    );
    $msgRow = null;
    if ($st) {
        $st->bind_param('s', $mid);
        $st->execute();
        $msgRow = $st->get_result()->fetch_assoc();
        $st->close();
    }
    if ($msgRow && ($msgRow['recipient_id'] === $uid || $msgRow['sender_id'] === $uid)) {
        if ($msgRow['recipient_id'] === $uid && empty($msgRow['is_read'])) {
            $up = $conn->prepare('UPDATE internal_messages SET is_read = 1, read_at = NOW() WHERE id = ?');
            if ($up) {
                $up->bind_param('s', $mid);
                $up->execute();
                $up->close();
            }
            $msgRow['is_read'] = 1;
        }
    } else {
        $msgRow = null;
    }
} else {
    $msgRow = null;
}

$inbox = [];
$sent = [];
if ($uid !== '') {
    if ($tab === 'inbox' || $tab === 'view') {
        $st = $conn->prepare(
            "SELECT m.id, m.subject, m.is_read, m.created_at,
                    CONCAT(TRIM(s.first_name),' ',TRIM(s.last_name)) AS other_name
             FROM internal_messages m
             INNER JOIN users s ON m.sender_id = s.id
             WHERE m.recipient_id = ?
             ORDER BY m.created_at DESC
             LIMIT 150"
        );
        if ($st) {
            $st->bind_param('s', $uid);
            $st->execute();
            $inbox = $st->get_result()->fetch_all(MYSQLI_ASSOC);
            $st->close();
        }
    }
    if ($tab === 'sent' || $tab === 'compose') {
        $st = $conn->prepare(
            "SELECT m.id, m.subject, m.created_at,
                    CONCAT(TRIM(r.first_name),' ',TRIM(r.last_name)) AS other_name
             FROM internal_messages m
             INNER JOIN users r ON m.recipient_id = r.id
             WHERE m.sender_id = ?
             ORDER BY m.created_at DESC
             LIMIT 150"
        );
        if ($st) {
            $st->bind_param('s', $uid);
            $st->execute();
            $sent = $st->get_result()->fetch_all(MYSQLI_ASSOC);
            $st->close();
        }
    }
}

$recipients = [];
$rr = $conn->query(
    "SELECT id, first_name, last_name, email FROM users
     WHERE status IN ('active','pending_verification') AND id != '" . $conn->real_escape_string($uid) . "'
     ORDER BY last_name, first_name LIMIT 400"
);
if ($rr) {
    $recipients = $rr->fetch_all(MYSQLI_ASSOC);
}

$csrf = iscms_csrf_token();

iscms_render_head($pageTitle);
iscms_render_sidebar($activeNav);
iscms_render_topbar($pageTitle);
?>
    <div class="page-header">
        <h1>Messaging</h1>
        <p>Secure internal messages between registered users.</p>
    </div>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-links-line"></i> Sections</h2>
        </div>
        <div class="quick-actions">
            <a class="qa-btn" href="messaging.php?tab=inbox"><i class="ri-inbox-line"></i> Inbox</a>
            <a class="qa-btn" href="messaging.php?tab=sent"><i class="ri-send-plane-line"></i> Sent</a>
            <a class="qa-btn" href="messaging.php?tab=compose"><i class="ri-edit-line"></i> Compose</a>
            <a class="qa-btn" href="notifications.php"><i class="ri-notification-3-line"></i> Notifications</a>
        </div>
    </div>

    <?php if ($errors !== []): ?>
    <div class="alert alert-danger mb-4" style="font-size:.88rem">
        <ul class="mb-0 ps-3"><?php foreach ($errors as $e): ?><li><?= iscms_h($e) ?></li><?php endforeach; ?></ul>
    </div>
    <?php endif; ?>
    <?php if ($composeOk): ?>
    <div class="alert alert-success mb-4" style="font-size:.88rem">Message sent.</div>
    <?php endif; ?>

    <?php if ($tab === 'view' && $mid !== '' && !$msgRow): ?>
    <div class="alert alert-warning">Message not found or you do not have access.</div>
    <?php endif; ?>

    <?php if ($tab === 'view' && $msgRow): ?>
    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-mail-open-line"></i> <?= iscms_h((string) ($msgRow['subject'] ?? '')) ?></h2>
            <a href="messaging.php?tab=inbox" class="btn btn-sm btn-outline-secondary">Back</a>
        </div>
        <div class="p-3" style="font-size:.9rem">
            <p class="text-muted small mb-2">
                From <strong><?= iscms_h((string) ($msgRow['sender_name'] ?? '')) ?></strong>
                to <strong><?= iscms_h((string) ($msgRow['recipient_name'] ?? '')) ?></strong>
                &middot; <?= !empty($msgRow['created_at']) ? iscms_h(substr((string) $msgRow['created_at'], 0, 19)) : '' ?>
            </p>
            <div class="border rounded p-3 bg-light" style="white-space:pre-wrap"><?= iscms_h((string) ($msgRow['body'] ?? '')) ?></div>
        </div>
    </div>
    <?php elseif ($tab === 'compose'): ?>
    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-edit-line"></i> Compose</h2>
        </div>
        <div class="p-3">
            <form method="post" action="messaging.php?tab=compose" class="row g-3" style="max-width:40rem">
                <input type="hidden" name="csrf_token" value="<?= iscms_h($csrf) ?>">
                <input type="hidden" name="action" value="send_message">
                <div class="col-12">
                    <label class="form-label">To</label>
                    <select name="recipient_id" class="form-select form-select-sm" required>
                        <option value="">Select recipient</option>
                        <?php foreach ($recipients as $rp): ?>
                        <option value="<?= iscms_h($rp['id']) ?>">
                            <?= iscms_h(trim((string) $rp['first_name'] . ' ' . (string) $rp['last_name'])) ?> - <?= iscms_h((string) $rp['email']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Subject</label>
                    <input type="text" name="subject" class="form-control form-control-sm" required maxlength="255">
                </div>
                <div class="col-12">
                    <label class="form-label">Message</label>
                    <textarea name="body" class="form-control form-control-sm" rows="6" required></textarea>
                </div>
                <div class="col-12">
                    <button type="submit" class="btn btn-primary btn-sm"><i class="ri-send-plane-line me-1"></i>Send</button>
                </div>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($tab === 'inbox' && $mid === ''): ?>
    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-inbox-line"></i> Inbox</h2>
            <span class="text-muted" style="font-size:.75rem"><?= count($inbox) ?> shown</span>
        </div>
        <div class="table-responsive">
            <table class="ssbs-table">
                <thead>
                    <tr>
                        <th>From</th>
                        <th>Subject</th>
                        <th>Read</th>
                        <th>Received</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($inbox)): ?>
                    <tr class="empty-row"><td colspan="4"><i class="ri-inbox-line me-2"></i>No messages</td></tr>
                    <?php else: ?>
                        <?php foreach ($inbox as $r): ?>
                        <tr>
                            <td><small><?= iscms_h((string) ($r['other_name'] ?? '')) ?></small></td>
                            <td><a href="messaging.php?tab=view&amp;mid=<?= iscms_h($r['id']) ?>" class="text-decoration-none fw-semibold" style="color:var(--ssbs-blue)"><?= iscms_h((string) ($r['subject'] ?? '')) ?></a></td>
                            <td><?= !empty($r['is_read']) ? '<span class="badge bg-secondary-subtle text-secondary" style="font-size:.65rem">Read</span>' : '<span class="badge bg-primary-subtle text-primary" style="font-size:.65rem">New</span>' ?></td>
                            <td><small class="text-muted"><?= !empty($r['created_at']) ? iscms_h(substr((string) $r['created_at'], 0, 19)) : '-' ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($tab === 'sent'): ?>
    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-send-plane-line"></i> Sent</h2>
            <span class="text-muted" style="font-size:.75rem"><?= count($sent) ?> shown</span>
        </div>
        <div class="table-responsive">
            <table class="ssbs-table">
                <thead>
                    <tr>
                        <th>To</th>
                        <th>Subject</th>
                        <th>Sent</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($sent)): ?>
                    <tr class="empty-row"><td colspan="3"><i class="ri-inbox-line me-2"></i>No sent messages</td></tr>
                    <?php else: ?>
                        <?php foreach ($sent as $r): ?>
                        <tr>
                            <td><small><?= iscms_h((string) ($r['other_name'] ?? '')) ?></small></td>
                            <td><a href="messaging.php?tab=view&amp;mid=<?= iscms_h($r['id']) ?>" class="text-decoration-none fw-semibold" style="color:var(--ssbs-blue)"><?= iscms_h((string) ($r['subject'] ?? '')) ?></a></td>
                            <td><small class="text-muted"><?= !empty($r['created_at']) ? iscms_h(substr((string) $r['created_at'], 0, 19)) : '-' ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
<?php
iscms_render_footer();
