<?php
require_once '../includes/db.php';
require_once '../includes/mailer.php';
require_once '../includes/functions.php';

// Ensure only admin can access this page
redirectIfNotAdmin();

// Handle message deletion
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    try {
        $stmt = $pdo->prepare("DELETE FROM contact_messages WHERE id = ?");
        $stmt->execute([$_GET['delete']]);
        $_SESSION['success'] = "Message deleted successfully.";
        header("Location: manage-messages.php");
        exit();
    } catch (PDOException $e) {
        error_log("Error deleting message: " . $e->getMessage());
        $_SESSION['error'] = "Failed to delete message.";
    }
}

// Check if message ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: manage-messages.php');
    exit();
}

$message_id = $_GET['id'];
$reply_sent = false;
$reply_error = null;

try {
    // Fetch the message
    $stmt = $pdo->prepare("SELECT * FROM contact_messages WHERE id = ?");
    $stmt->execute([$message_id]);
    $message = $stmt->fetch();

    if (!$message) {
        header('Location: manage-messages.php');
        exit();
    }

    // Update status to 'read' if it's new
    if ($message['status'] === 'new') {
        $updateStmt = $pdo->prepare("UPDATE contact_messages SET status = 'read' WHERE id = ?");
        $updateStmt->execute([$message_id]);
        $message['status'] = 'read'; // Update local variable
    }

    // Handle status update
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['status'])) {
        $newStatus = $_POST['status'];
        if (in_array($newStatus, ['read', 'replied'])) {
            $updateStmt = $pdo->prepare("UPDATE contact_messages SET status = ? WHERE id = ?");
            $updateStmt->execute([$newStatus, $message_id]);
            header("Location: view-message.php?id=" . $message_id);
            exit();
        }
    }

    // Handle reply submission
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_message'])) {
        $reply_message = $_POST['reply_message'];

        // Initialize PHPMailer
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);

        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'nexusbanksystem@gmail.com';
            $mail->Password = 'ntnl ttfo uayi vsxd';
            $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;

            // Recipients
            $mail->setFrom('nexusbanksystem@gmail.com', 'Oakshire Finance');
            $mail->addAddress($message['email'], $message['name']);

            // Content
            $mail->isHTML(true);
            $mail->Subject = 'Re: ' . $message['subject'];
            $mail->Body = nl2br($reply_message);
            $mail->AltBody = strip_tags($reply_message);

            $mail->send();

            // Update message status to replied
            $updateStmt = $pdo->prepare("UPDATE contact_messages SET status = 'replied' WHERE id = ?");
            $updateStmt->execute([$message_id]);
            $message['status'] = 'replied';

            $reply_sent = true;
        } catch (Exception $e) {
            $reply_error = "Failed to send reply: " . $mail->ErrorInfo;
            error_log("Mail Error: " . $mail->ErrorInfo);
        }
    }
} catch (PDOException $e) {
    error_log("Error: " . $e->getMessage());
    die("An error occurred. Please try again later.");
}

// Get current admin info
$adminId = $_SESSION['user_id'];
$adminInfo = $pdo->prepare("SELECT full_name, email FROM users WHERE user_id = ?");
$adminInfo->execute([$adminId]);
$admin = $adminInfo->fetch();
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Oakshire Finance - View Message</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --accent-blue: #2c7da0;
            --success-green: #2e7d32;
            --warning-orange: #f39c12;
            --error-red: #dc3545;
            --info-blue: #17a2b8;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 12px 28px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: var(--gray-50);
            color: var(--gray-800);
            line-height: 1.5;
            overflow-x: hidden;
        }

        /* Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 280px;
            background: var(--white);
            border-right: 1px solid var(--gray-200);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: var(--transition);
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 20px;
            color: white;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
            letter-spacing: -0.3px;
        }

        .nav-menu {
            padding: 24px 16px;
        }

        .nav-item {
            margin-bottom: 8px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .nav-link.active i {
            color: white;
        }

        .logout-section {
            padding: 24px 16px;
            border-top: 1px solid var(--gray-200);
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            transition: var(--transition);
            font-weight: 500;
        }

        .logout-btn:hover {
            background: rgba(220, 53, 69, 0.1);
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        /* Top Header */
        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-900);
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .notification-btn {
            position: relative;
            background: none;
            border: none;
            font-size: 20px;
            color: var(--gray-600);
            cursor: pointer;
            transition: var(--transition);
        }

        .notification-btn:hover {
            color: var(--primary-blue);
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .user-avatar i {
            font-size: 18px;
            color: white;
        }

        .user-details h4 {
            font-size: 14px;
            font-weight: 600;
            color: var(--gray-900);
        }

        .user-details p {
            font-size: 12px;
            color: var(--gray-600);
        }

        /* Content Area */
        .content-area {
            padding: 32px;
        }

        /* Back Link */
        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: var(--primary-blue);
            text-decoration: none;
            font-weight: 500;
            margin-bottom: 24px;
            transition: var(--transition);
        }

        .back-link:hover {
            gap: 12px;
            color: var(--primary-navy);
        }

        /* Message Container */
        .message-card {
            background: var(--white);
            border-radius: 24px;
            border: 1px solid var(--gray-200);
            overflow: hidden;
            margin-bottom: 24px;
        }

        .message-header {
            padding: 24px 32px;
            background: var(--gray-50);
            border-bottom: 1px solid var(--gray-200);
        }

        .message-subject {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-900);
            margin-bottom: 16px;
        }

        .message-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 24px;
            font-size: 14px;
            color: var(--gray-600);
        }

        .message-meta-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .message-meta-item i {
            width: 16px;
            color: var(--gray-500);
        }

        .message-body {
            padding: 32px;
            font-size: 15px;
            line-height: 1.7;
            color: var(--gray-700);
            background: var(--white);
        }

        .message-body p {
            margin-bottom: 16px;
        }

        .message-body p:last-child {
            margin-bottom: 0;
        }

        /* Action Bar */
        .action-bar {
            padding: 20px 32px;
            border-top: 1px solid var(--gray-200);
            background: var(--white);
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            align-items: center;
            justify-content: space-between;
        }

        .action-buttons {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        /* Buttons */
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: var(--transition);
            border: none;
            text-decoration: none;
        }

        .btn-primary {
            background: var(--primary-navy);
            color: white;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
        }

        .btn-success {
            background: rgba(46, 125, 50, 0.1);
            color: var(--success-green);
        }

        .btn-success:hover {
            background: var(--success-green);
            color: white;
        }

        .btn-danger {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
        }

        .btn-danger:hover {
            background: var(--error-red);
            color: white;
        }

        .btn-outline {
            background: transparent;
            border: 1px solid var(--gray-300);
            color: var(--gray-700);
        }

        .btn-outline:hover {
            border-color: var(--primary-blue);
            color: var(--primary-blue);
        }

        /* Status Badge */
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            border-radius: 30px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-new {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
        }

        .status-read {
            background: rgba(108, 117, 125, 0.1);
            color: var(--gray-600);
        }

        .status-replied {
            background: rgba(26, 77, 140, 0.1);
            color: var(--primary-blue);
        }

        /* Alerts */
        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 24px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: var(--white);
            border-radius: 24px;
            max-width: 600px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            animation: fadeInUp 0.3s ease;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            font-size: 18px;
            font-weight: 600;
            color: var(--gray-900);
        }

        .modal-header p {
            font-size: 13px;
            color: var(--gray-500);
            margin-top: 4px;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--gray-500);
            transition: var(--transition);
        }

        .modal-close:hover {
            color: var(--gray-800);
        }

        .modal-body {
            padding: 24px;
        }

        .reply-textarea {
            width: 100%;
            min-height: 200px;
            padding: 14px;
            font-family: 'Inter', sans-serif;
            font-size: 14px;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            resize: vertical;
            transition: var(--transition);
            outline: none;
        }

        .reply-textarea:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid var(--gray-200);
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }

        /* Hamburger Menu */
        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--gray-700);
        }

        /* Mobile Responsive */
        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .user-details {
                display: none;
            }

            .message-header {
                padding: 20px;
            }

            .message-subject {
                font-size: 20px;
            }

            .message-meta {
                flex-direction: column;
                gap: 8px;
            }

            .message-body {
                padding: 20px;
            }

            .action-bar {
                flex-direction: column;
                align-items: stretch;
                padding: 20px;
            }

            .action-buttons {
                justify-content: center;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <!-- Sidebar Navigation -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon">
                        <i class="fas fa-building-columns"></i>
                    </div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>

            <nav class="nav-menu">
                <div class="nav-item">
                    <a href="dashboard.php" class="nav-link">
                        <i class="fas fa-chart-line"></i>
                        <span>Dashboard</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="manage-users.php" class="nav-link">
                        <i class="fas fa-users"></i>
                        <span>Manage Users</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="manage-loans.php" class="nav-link">
                        <i class="fas fa-hand-holding-usd"></i>
                        <span>Manage Loans</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="manage-investments.php" class="nav-link">
                        <i class="fas fa-chart-pie"></i>
                        <span>Manage Investments</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="track-investments.php" class="nav-link">
                        <i class="fas fa-chart-simple"></i>
                        <span>Users Investments</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="role.php" class="nav-link">
                        <i class="fas fa-user-tag"></i>
                        <span>Roles</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="recent_transactions.php" class="nav-link">
                        <i class="fas fa-exchange-alt"></i>
                        <span>Transactions</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="loan-history.php" class="nav-link">
                        <i class="fas fa-history"></i>
                        <span>Loan History</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="login-records.php" class="nav-link">
                        <i class="fas fa-sign-in-alt"></i>
                        <span>Login Records</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="manage-messages.php" class="nav-link active">
                        <i class="fas fa-envelope"></i>
                        <span>Contact Messages</span>
                    </a>
                </div>
            </nav>

            <div class="logout-section">
                <a href="../logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Header -->
            <header class="top-header">
                <button class="hamburger" id="hamburger">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="page-title">
                    <h1>View Message</h1>
                </div>
                <div class="user-menu">
                    <button class="notification-btn">
                        <i class="fas fa-bell"></i>
                    </button>
                    <div class="user-info">
                        <div class="user-avatar">
                            <i class="fas fa-user-shield"></i>
                        </div>
                        <div class="user-details">
                            <h4><?= htmlspecialchars($admin['full_name'] ?? 'Admin User') ?></h4>
                            <p>System Administrator</p>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Content Area -->
            <div class="content-area">
                <!-- Back Link -->
                <a href="manage-messages.php" class="back-link">
                    <i class="fas fa-arrow-left"></i> Back to Messages
                </a>

                <!-- Alerts -->
                <?php if ($reply_sent): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        <span>Reply sent successfully!</span>
                    </div>
                <?php endif; ?>

                <?php if ($reply_error): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?= htmlspecialchars($reply_error) ?></span>
                    </div>
                <?php endif; ?>

                <!-- Message Card -->
                <div class="message-card">
                    <div class="message-header">
                        <div class="message-subject">
                            <?= htmlspecialchars($message['subject']) ?>
                        </div>
                        <div class="message-meta">
                            <div class="message-meta-item">
                                <i class="fas fa-user"></i>
                                <span><strong><?= htmlspecialchars($message['name']) ?></strong>
                                    (<?= htmlspecialchars($message['email']) ?>)</span>
                            </div>
                            <div class="message-meta-item">
                                <i class="fas fa-calendar"></i>
                                <span><?= date("F j, Y, g:i a", strtotime($message['created_at'])) ?></span>
                            </div>
                            <div class="message-meta-item">
                                <i class="fas fa-tag"></i>
                                <span
                                    class="status-badge <?= $message['status'] === 'new' ? 'status-new' : ($message['status'] === 'read' ? 'status-read' : 'status-replied') ?>">
                                    <i
                                        class="fas <?= $message['status'] === 'new' ? 'fa-envelope' : ($message['status'] === 'read' ? 'fa-check-circle' : 'fa-reply-all') ?>"></i>
                                    <?= ucfirst($message['status']) ?>
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="message-body">
                        <?= nl2br(htmlspecialchars($message['message'])) ?>
                    </div>

                    <div class="action-bar">
                        <div class="action-buttons">
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="status" value="replied">
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-check-double"></i> Mark as Replied
                                </button>
                            </form>
                            <button onclick="openReplyModal()" class="btn btn-primary">
                                <i class="fas fa-reply"></i> Reply via Email
                            </button>
                        </div>
                        <a href="view-message.php?delete=<?= $message['id'] ?>" class="btn btn-danger"
                            onclick="return confirm('Are you sure you want to delete this message? This action cannot be undone.')">
                            <i class="fas fa-trash"></i> Delete Message
                        </a>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Reply Modal -->
    <div id="replyModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h3><i class="fas fa-reply"></i> Reply to <?= htmlspecialchars($message['name']) ?></h3>
                    <p>Re: <?= htmlspecialchars($message['subject']) ?></p>
                </div>
                <button class="modal-close" onclick="closeReplyModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form method="POST" id="replyForm">
                <div class="modal-body">
                    <textarea name="reply_message" class="reply-textarea" placeholder="Type your reply here..."
                        required></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline" onclick="closeReplyModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-paper-plane"></i> Send Reply
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Mobile sidebar toggle
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');

        if (hamburger) {
            hamburger.addEventListener('click', function () {
                sidebar.classList.toggle('mobile-open');
            });
        }

        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function (event) {
            if (window.innerWidth <= 1024) {
                const isClickInside = sidebar.contains(event.target) || hamburger.contains(event.target);
                if (!isClickInside && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });

        // Modal functions
        const replyModal = document.getElementById('replyModal');

        function openReplyModal() {
            replyModal.classList.add('active');
        }

        function closeReplyModal() {
            replyModal.classList.remove('active');
        }

        // Close modal when clicking outside
        window.onclick = function (event) {
            if (event.target === replyModal) {
                closeReplyModal();
            }
        }

        // Auto-dismiss alerts after 5 seconds
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.style.transition = 'opacity 0.3s ease';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 300);
            }, 5000);
        });
    </script>
</body>

</html>