<?php
/**
 * Agentic Square - Generate Support Ticket
 * Path: client/create-ticket.php
 */

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

// Access Check: Logged in user required
if (!isset($_SESSION['user_id'])) { header('Location: ../login.php'); exit; }

// INCLUDE PHPMAILER
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;

$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $order_id = filter_var($_POST['order_id'], FILTER_VALIDATE_INT);
    $subject  = filter_var($_POST['subject'], FILTER_SANITIZE_SPECIAL_CHARS);
    $message  = filter_var($_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS);
    $priority = in_array($_POST['priority'] ?? '', ['Low', 'High']) ? $_POST['priority'] : 'Low';

    if (!$order_id || empty($subject) || empty($message)) {
        $error_message = "All fields are required.";
    } else {
        try {
            $pdo->beginTransaction();

            // 1. Insert Ticket
            $stmt = $pdo->prepare("INSERT INTO support_tickets (user_id, order_id, subject, message, priority, ticket_status) VALUES (?, ?, ?, ?, ?, 'Pending')");
            $stmt->execute([$_SESSION['user_id'], $order_id, $subject, $message, $priority]);
            
            // 2. Fetch Emails
            $clientStmt = $pdo->prepare("SELECT full_name, email FROM users WHERE id = ?");
            $clientStmt->execute([$_SESSION['user_id']]);
            $client = $clientStmt->fetch(PDO::FETCH_ASSOC);

            // Fetch Seller email using order_id -> orders.seller_id -> users.id
            $sellerStmt = $pdo->prepare("SELECT u.email, u.full_name, o.item_name FROM orders o INNER JOIN users u ON o.seller_id = u.id WHERE o.id = ?");
            $sellerStmt->execute([$order_id]);
            $seller = $sellerStmt->fetch(PDO::FETCH_ASSOC);

            // 3. Fetch SMTP Settings from table
            $smtp = $pdo->query("SELECT * FROM smtp_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);

            $pdo->commit();

            // 4. Send Email
            if ($smtp && $client && $seller) {
                $mail = new PHPMailer(true);
                $mail->isSMTP();
                $mail->Host       = $smtp['smtp_host'];
                $mail->SMTPAuth   = ($smtp['smtp_auth'] == 1);
                $mail->Username   = $smtp['smtp_username'];
                $mail->Password   = $smtp['smtp_password'];
                $mail->SMTPSecure = $smtp['smtp_secure']; // 'tls' or 'ssl'
                $mail->Port       = $smtp['smtp_port'];

                $mail->setFrom($smtp['from_email'], $smtp['from_name']);
                $mail->addAddress($client['email'], $client['full_name']); // To Client
                $mail->addCC($seller['email'], $seller['full_name']);     // CC Seller

                $mail->isHTML(true);
                $mail->Subject = "New Ticket: " . $subject;
                $mail->Body    = "Hello,<br><br>A new support ticket has been opened.<br><br>
                                  <strong>Item:</strong> {$seller['item_name']}<br>
                                  <strong>Subject:</strong> {$subject}<br>
                                  <strong>Message:</strong><br>" . nl2br($message);
                $mail->send();
            }

            header('Location: support-tickets.php');
            exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

$orderLines = $pdo->prepare("SELECT id, item_name FROM orders WHERE user_id = ? ORDER BY created_at DESC");
$orderLines->execute([$_SESSION['user_id']]);
$availableOrders = $orderLines->fetchAll(PDO::FETCH_ASSOC);

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">// Open Dialogue Channel</span>
                <h1 class="text-3xl font-extrabold tracking-tight text-white">Create Support Ticket</h1>
            </div>

            <?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">Select Associated Ordered Product</label>
                        <select name="order_id" required class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                            <option value="" disabled selected>-- Choose from registered purchases --</option>
                            <?php foreach ($availableOrders as $order): ?>
                                <option value="<?= $order['id'] ?>"><?= htmlspecialchars($order['item_name']) ?> (Ref ##<?= $order['id'] ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="space-y-2">
                        <label class="text-xs font-bold uppercase text-nftTextGray">Ticket Urgency Matrix</label>
                        <select name="priority" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                            <option value="Low">Low - Structural / General Assistance</option>
                            <option value="High">High - System Processing / Performance Failure</option>
                        </select>
                    </div>
                </div>

                <div class="space-y-2">
                    <label class="text-xs font-bold uppercase text-nftTextGray">Inquiry Subject Line</label>
                    <input type="text" name="subject" required placeholder="Summarize your issue..." class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                </div>

                <div class="space-y-2">
                    <label class="text-xs font-bold uppercase text-nftTextGray">Comprehensive Core Issue Statement</label>
                    <textarea name="message" rows="6" required placeholder="Provide an explicit architectural description of your issue..." class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl p-4 text-sm text-white focus: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">
                    Dispatch Log Matrix
                </button>
            </form>
        </div>
    </main>
</body>
</html>