<?php
session_start();
include "../include/db.php";
include "include/header.php";

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/PHPMailer/src/Exception.php';
require 'vendor/PHPMailer/src/PHPMailer.php';
require 'vendor/PHPMailer/src/SMTP.php';

$contact_id = (int)($_GET['id'] ?? 0);
$contact = null;

if ($contact_id <= 0) {
    $_SESSION['result'] = 'Invalid contact ID.';
    $_SESSION['status'] = 'error';
    header("Location: contacts.php");
    exit;
}

// Fetch contact
$stmt = $conn->prepare("SELECT * FROM contacts WHERE id = ?");
$stmt->bind_param("i", $contact_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    $stmt->close();
    $_SESSION['result'] = 'Contact not found.';
    $_SESSION['status'] = 'error';
    header("Location: contacts.php");
    exit;
}
$contact = $result->fetch_assoc();
$stmt->close();

// Handle Send Reply
if (isset($_POST['send'])) {
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $subject = htmlspecialchars($_POST['subject'] ?? '', ENT_QUOTES, 'UTF-8');
    $message = htmlspecialchars($_POST['message'] ?? '', ENT_QUOTES, 'UTF-8');

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $_SESSION['result'] = 'অবৈধ ইমেইল ঠিকানা';
        $_SESSION['status'] = 'error';
    } else {
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host       = 'mail.itgalaxy.academy';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'support@itgalaxy.academy';
            $mail->Password   = getenv('SMTP_PASSWORD') ?: '*01723624071#'; // Use .env in production
            $mail->SMTPSecure = 'tls';
            $mail->Port       = 587;
            $mail->CharSet    = 'UTF-8';

            $mail->setFrom('support@itgalaxy.academy', 'IT Galaxy Academy');
            $mail->addAddress($email, $contact['name']);
            $mail->addReplyTo('support@itgalaxy.academy', 'IT Galaxy Academy');

            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = "
                <html>
                <body style='font-family: Arial, sans-serif; color: #333;'>
                    <h2 style='color: #1A237E;'>IT Galaxy Academy</h2>
                    <p>প্রিয় <strong>{$contact['name']}</strong>,</p>
                    <p>আপনার প্রশ্নের উত্তর:</p>
                    <div style='background: #f8f9fa; padding: 15px; border-left: 4px solid #FF5722; margin: 15px 0;'>
                        " . nl2br($message) . "
                    </div>
                    <hr>
                    <p><strong>আপনার মূল বার্তা:</strong></p>
                    <blockquote style='color: #666; font-style: italic; border-left: 3px solid #ddd; padding-left: 10px;'>
                        {$contact['message']}
                    </blockquote>
                    <p>ধন্যবাদ,<br><strong>IT Galaxy Academy</strong></p>
                </body>
                </html>
            ";

            $mail->send();

            // Mark as read
            $stmt = $conn->prepare("UPDATE contacts SET status = 'read' WHERE id = ?");
            $stmt->bind_param("i", $contact_id);
            $stmt->execute();
            $stmt->close();

            $_SESSION['result'] = 'মেল সফলভাবে পাঠানো হয়েছে';
            $_SESSION['status'] = 'ok';
        } catch (Exception $e) {
            $_SESSION['result'] = 'মেল পাঠানো যায়নি। ত্রুটি: ' . $mail->ErrorInfo;
            $_SESSION['status'] = 'error';
        }
    }
    header("Location: reply_contact.php?id=$contact_id");
    exit;
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ইমেইল রিপ্লাই - IT Galaxy Academy</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@700&family=Hind+Siliguri:wght@400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background: #f8fafc;
            color: #333;
        }
        .content {
            margin-left: 250px;
            padding: 2rem;
            min-height: 100vh;
        }
        .card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        .card-header {
            background: linear-gradient(135deg, #1E293B 0%, #334155 100%);
            color: white;
            padding: 1.5rem;
        }
        .card-header h2 {
            font-family: 'Roboto', sans-serif;
            font-weight: 700;
        }
        .form-control, .form-select {
            border-radius: 8px;
            padding: 12px;
        }
        .btn-primary {
            background: linear-gradient(45deg, #FF5722, #FF8A65);
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-weight: 600;
        }
        .btn-secondary {
            background: #6c757d;
            padding: 12px 20px;
            border-radius: 8px;
        }
        .quote {
            background: #f1f5f9;
            border-left: 4px solid #94a3b8;
            padding: 15px;
            margin: 20px 0;
            font-style: italic;
            color: #475569;
            border-radius: 0 8px 8px 0;
        }
        .alert {
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        @media (max-width: 768px) {
            .content { margin-left: 0; padding: 1rem; }
            .card-header { padding: 1rem; }
        }
    </style>
</head>
<body>
    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40 backdrop-blur-md bg-white/10">
        <div class="logo text-2xl font-bold">CourseLMS Admin</div>
        <div>
            <a href="contacts.php" class="btn btn-secondary text-white">
                Back to Messages
            </a>
        </div>
    </nav>

    <div class="content">
        <div class="max-w-4xl mx-auto">
            <div class="card">
                <div class="card-header">
                    <h2 class="mb-0">ইমেইল রিপ্লাই পাঠান</h2>
                    <p class="mb-0 opacity-90">প্রফেশনাল উত্তর পাঠান</p>
                </div>

                <div class="card-body p-4">
                    <!-- Session Message -->
                    <?php if (isset($_SESSION['status'])): ?>
                        <div class="alert alert-<?php echo $_SESSION['status'] == 'ok' ? 'success' : 'danger'; ?>">
                            <?php 
                            echo $_SESSION['result']; 
                            unset($_SESSION['result'], $_SESSION['status']);
                            ?>
                        </div>
                    <?php endif; ?>

                    <!-- Contact Info -->
                    <div class="bg-light p-3 rounded mb-4">
                        <p><strong>নাম:</strong> <?php echo htmlspecialchars($contact['name']); ?></p>
                        <p><strong>ইমেইল:</strong> <a href="mailto:<?php echo htmlspecialchars($contact['email']); ?>" class="text-primary"><?php echo htmlspecialchars($contact['email']); ?></a></p>
                        <p><strong>বিষয়:</strong> <?php echo htmlspecialchars($contact['subject']); ?></p>
                        <p><strong>তারিখ:</strong> <?php echo date('d M, Y - h:i A', strtotime($contact['created_at'])); ?></p>
                    </div>

                    <!-- Original Message -->
                    <div class="quote">
                        <strong>মূল বার্তা:</strong><br>
                        <?php echo nl2br(htmlspecialchars($contact['message'])); ?>
                    </div>

                    <!-- Reply Form -->
                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label">প্রাপক ইমেইল</label>
                            <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($contact['email']); ?>" required readonly>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">বিষয়</label>
                            <input type="text" name="subject" class="form-control" value="Re: <?php echo htmlspecialchars($contact['subject']); ?>" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">আপনার উত্তর</label>
                            <textarea name="message" class="form-control" rows="8" placeholder="আপনার উত্তর লিখুন..." required></textarea>
                        </div>

                        <div class="d-flex gap-2">
                            <button type="submit" name="send" class="btn btn-primary">
                                Send Reply
                            </button>
                            <a href="contacts.php" class="btn btn-secondary">
                                Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php include "include/footer.php"; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>