<?php
// contact-user.php
session_start();
require_once 'config.php';
require_once 'smtp_mailer.php';

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

$sender_id = intval($_SESSION['user_id']);
$recipient_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($recipient_id <= 0 || $sender_id === $recipient_id) {
    header('Location: /explore.php');
    exit;
}

// Fetch sender and recipient
$stmt = $conn->prepare("SELECT email, personal_email, company_email, org_name FROM users WHERE id = ?");
$stmt->bind_param("i", $sender_id);
$stmt->execute();
$sender = $stmt->get_result()->fetch_assoc();
$stmt->close();

$stmt = $conn->prepare("SELECT email, personal_email, company_email, org_name FROM users WHERE id = ?");
$stmt->bind_param("i", $recipient_id);
$stmt->execute();
$recipient = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$recipient || !$sender) {
    header('Location: /explore.php');
    exit;
}

$recipient_email = $recipient['company_email'] ?: ($recipient['personal_email'] ?: $recipient['email']);
$sender_email = $sender['company_email'] ?: ($sender['personal_email'] ?: $sender['email']);
$sender_name = $sender['org_name'];
$recipient_name = $recipient['org_name'];

$status = '';
$status_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_message'])) {
    $subject = trim($_POST['subject']);
    $message = trim($_POST['message']);

    if (empty($subject) || empty($message)) {
        $status = 'error';
        $status_msg = 'Subject and message are required.';
    } else {
        // Build email
        $mail_subject = "New Message from $sender_name via SaniBook Kenya";
        $mail_body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; color: #333;'>
            <h2 style='color: #002855;'>You have a new message on SaniBook Kenya</h2>
            <p><strong>From:</strong> " . htmlspecialchars($sender_name) . " (" . htmlspecialchars($sender_email) . ")</p>
            <p><strong>Subject:</strong> " . htmlspecialchars($subject) . "</p>
            <hr style='border: none; border-top: 1px solid #eee; margin: 20px 0;'>
            <div style='background: #f8fafc; padding: 20px; border-radius: 8px; border-left: 4px solid #00A1E0;'>
                " . nl2br(htmlspecialchars($message)) . "
            </div>
            <hr style='border: none; border-top: 1px solid #eee; margin: 20px 0;'>
            <p style='font-size: 13px; color: #666;'>To reply, you can click 'Reply' in your email client, as the reply-to address is set to the sender's email.</p>
        </div>";

        $mailer = new SmtpMailer(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS);
        try {
            $mail_result = $mailer->send($recipient_email, $mail_subject, $mail_body);
            if ($mail_result) {
                $status = 'success';
                $status_msg = 'Your message has been successfully sent!';
            } else {
                $status = 'error';
                $status_msg = 'Failed to send message: SMTP Error';
            }
        } catch (Exception $e) {
            $status = 'error';
            $status_msg = 'Failed to send message: ' . htmlspecialchars($e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact
        <?= htmlspecialchars($recipient_name) ?> | SaniBook Kenya
    </title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link
        href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700;900&family=Merriweather:wght@400;700&display=swap"
        rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'brand-blue': '#002855',
                        'brand-accent': '#00A1E0',
                    }
                }
            }
        }
    </script>
</head>

<body class="bg-slate-50 min-h-screen flex flex-col font-merriweather selection:bg-brand-accent selection:text-white">
    <?php include 'navbar.php'; ?>

    <main class="flex-grow pt-24 pb-20 flex items-center justify-center px-4">
        <div class="max-w-xl w-full bg-white rounded-2xl shadow-xl overflow-hidden">
            <div class="bg-brand-blue p-8 text-center relative overflow-hidden">
                <div class="absolute inset-0 opacity-10"
                    style="background-image: radial-gradient(circle at 2px 2px, white 1px, transparent 0); background-size: 32px 32px;">
                </div>
                <div
                    class="w-16 h-16 bg-white rounded-full flex items-center justify-center text-brand-blue text-2xl font-bold mx-auto mb-4 relative z-10 shadow-lg">
                    <i class="fa-solid fa-envelope"></i>
                </div>
                <h1 class="text-2xl font-montserrat font-bold text-white relative z-10">Contact
                    <?= htmlspecialchars($recipient_name) ?>
                </h1>
                <p class="text-blue-100 text-sm mt-2 relative z-10">Send a direct message via the SaniBook network.</p>
            </div>

            <div class="p-8">
                <?php if ($status === 'success'): ?>
                    <div class="bg-green-50 text-green-700 p-6 rounded-xl border border-green-200 text-center mb-6">
                        <i class="fa-solid fa-check-circle text-4xl mb-3 text-green-500"></i>
                        <h3 class="text-lg font-bold mb-1">Message Sent!</h3>
                        <p class="text-sm font-medium">
                            <?= $status_msg ?>
                        </p>
                        <a href="/explore.php"
                            class="inline-block mt-4 px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors text-sm font-bold">Back
                            to Explore</a>
                    </div>
                <?php else: ?>
                    <?php if ($status === 'error'): ?>
                        <div
                            class="bg-red-50 text-red-700 p-4 rounded-lg border border-red-200 mb-6 text-sm flex items-center gap-3">
                            <i class="fa-solid fa-circle-exclamation text-lg"></i>
                            <span>
                                <?= $status_msg ?>
                            </span>
                        </div>
                    <?php endif; ?>

                    <form method="POST" action="" class="space-y-5">
                        <div class="bg-slate-50 p-4 rounded-lg border border-slate-100 text-sm mb-6">
                            <p class="text-slate-600 mb-1"><strong>To:</strong>
                                <?= htmlspecialchars($recipient_name) ?>
                            </p>
                            <p class="text-slate-600"><strong>From:</strong>
                                <?= htmlspecialchars($sender_name) ?> (
                                <?= htmlspecialchars($sender_email) ?>)
                            </p>
                            <p class="text-xs text-slate-500 mt-2 italic">* Your email address will be shared with the
                                recipient so they can reply.</p>
                        </div>

                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2">Subject</label>
                            <input type="text" name="subject" required
                                class="w-full px-4 py-3 bg-white border border-slate-300 rounded-xl focus:ring-2 focus:ring-brand-accent focus:border-brand-accent outline-none transition-all placeholder-slate-400"
                                placeholder="E.g. Collaboration Inquiry">
                        </div>

                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2">Message</label>
                            <textarea name="message" rows="6" required
                                class="w-full px-4 py-3 bg-white border border-slate-300 rounded-xl focus:ring-2 focus:ring-brand-accent focus:border-brand-accent outline-none transition-all placeholder-slate-400 resize-none"
                                placeholder="Write your message here..."></textarea>
                        </div>

                        <div class="pt-4 flex gap-3">
                            <a href="/explore.php"
                                class="flex-1 py-3 bg-slate-100 text-slate-700 font-bold rounded-xl hover:bg-slate-200 transition-colors text-center">Cancel</a>
                            <button type="submit" name="send_message"
                                class="flex-1 py-3 bg-brand-accent text-white font-bold rounded-xl hover:bg-blue-500 transition-colors shadow-lg shadow-blue-500/20">
                                Send Message <i class="fa-solid fa-paper-plane ml-1"></i>
                            </button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <?php include 'footer.php'; ?>
</body>

</html>