<?php
/**
 * Agentic Square - Client Support Inquiry Center
 * Path: client/contact-us.php
 */

require_once __DIR__ . '/../config/config.php';

// SECURITY ACCESS GUARD: Only allow standard clients (deny admin/seller)
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] === 'admin' || $_SESSION['user_role'] === 'seller') {
    header('Location: ../login.php');
    exit;
}

// MANUALLY INCLUDE PHPMAILER (Exception.php MUST come first)
require_once __DIR__ . '/../includes/PHPMailer/Exception.php';
require_once __DIR__ . '/../includes/PHPMailer/PHPMailer.php';
require_once __DIR__ . '/../includes/PHPMailer/SMTP.php';

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

$success_message = '';
$error_message   = '';

// Fetch Logged-in User details
$stmt = $pdo->prepare("SELECT full_name, email FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Fetch Support Email destination from General Settings
$settings = $pdo->query("SELECT support_email FROM general_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
$support_email = $settings['support_email'] ?? 'support@agentsquare.com';

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subject = filter_var($_POST['subject'], FILTER_SANITIZE_SPECIAL_CHARS);
    $message = filter_var($_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS);

    // Fetch DYNAMIC SMTP Configurations from the database
    $smtp = $pdo->query("SELECT * FROM smtp_settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);

    if (!$smtp) {
        $error_message = "System Delivery Failure: SMTP configurations are uninitialized.";
    } else {
        $mail = new PHPMailer(true);
        try {
            // Dynamic SMTP Configuration
            $mail->isSMTP();
            $mail->Host       = $smtp['smtp_host']; 
            $mail->SMTPAuth   = ((int)$smtp['smtp_auth'] === 1);
            $mail->Username   = $smtp['smtp_username'];
            $mail->Password   = $smtp['smtp_password'];
            $mail->Port       = (int)$smtp['smtp_port'];

            // Map Encryption Type dynamically based on Database Values
            if ($smtp['smtp_secure'] === 'tls') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            } elseif ($smtp['smtp_secure'] === 'ssl') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            } else {
                $mail->SMTPSecure = ''; // Unencrypted plain text transmission
                $mail->SMTPAutoTLS = false;
            }

            // Envelope Header Configuration
            $mail->setFrom($smtp['from_email'], $smtp['from_name']);
            $mail->addReplyTo($user['email'] ?? '', $user['full_name'] ?? '');
            $mail->addAddress($support_email);
            
            // Content Formats
            $mail->isHTML(true);
            $mail->Subject = "Support Inquiry: " . $subject;
            $mail->Body    = "<strong>From:</strong> " . htmlspecialchars($user['full_name'] ?? '') . "<br>" .
                             "<strong>Email:</strong> " . htmlspecialchars($user['email'] ?? '') . "<br><br>" .
                             "<strong>Message:</strong><br>" . nl2br(htmlspecialchars($message));

            $mail->send();
            $success_message = "Your inquiry has been successfully dispatched to our support team.";
        } catch (Exception $e) {
            $error_message = "System Delivery Failure: " . $mail->ErrorInfo;
        }
    }
}

require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">
    <?php include_once __DIR__ . '/client-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-16 px-4 sm:px-6 lg:px-8">
        <div class="max-w-3xl mx-auto space-y-8">
            <div class="border-b border-slate-900/60 pb-6">
                <span class="text-xs font-bold tracking-widest text-nftAccentCyan uppercase block mb-1">// Help & Support</span>
                <h1 class="text-3xl font-extrabold tracking-tight text-white">Contact Support</h1>
            </div>

            <?php if ($success_message): ?>
                <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 p-4 rounded-xl text-xs font-mono">
                    <?= $success_message ?>
                </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
                <div class="bg-rose-500/10 border border-rose-500/20 text-rose-400 p-4 rounded-xl text-xs font-mono">
                    <?= $error_message ?>
                </div>
            <?php endif; ?>

            <form method="POST" class="glass-card p-6 rounded-2xl border border-slate-800/80 bg-slate-950/20 space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="space-y-2">
                        <label class="text-xs font-bold uppercase text-nftTextGray">Your Name</label>
                        <input type="text" readonly value="<?= htmlspecialchars($user['full_name'] ?? '') ?>" class="w-full bg-slate-900/50 p-3 rounded-xl border border-slate-800 text-slate-400 cursor-not-allowed">
                    </div>
                    <div class="space-y-2">
                        <label class="text-xs font-bold uppercase text-nftTextGray">Your Email</label>
                        <input type="email" readonly value="<?= htmlspecialchars($user['email'] ?? '') ?>" class="w-full bg-slate-900/50 p-3 rounded-xl border border-slate-800 text-slate-400 cursor-not-allowed">
                    </div>
                </div>

                <div class="space-y-2">
                    <label class="text-xs font-bold uppercase text-nftTextGray">Subject</label>
                    <input type="text" name="subject" required placeholder="How can we assist you today?" class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none transition-all">
                </div>

                <div class="space-y-2">
                    <label class="text-xs font-bold uppercase text-nftTextGray">Message</label>
                    <textarea name="message" rows="5" required placeholder="Please describe your issue or inquiry..." class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none transition-all resize-none"></textarea>
                </div>

                <button type="submit" class="w-full py-4 rounded-xl bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple font-bold text-white uppercase tracking-widest hover:opacity-90 transition-all shadow-lg">
                    Send Inquiry
                </button>
            </form>
        </div>
    </main>
</body>
</html>