<?php
// support.php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config.php'; // adjust if needed

// determine logged-in user id
$user_id = $_SESSION['SESS_USERID'] ?? $_SESSION['user_id'] ?? null;
if (!$user_id && !empty($_SESSION['user'])) {
    $tmp = $pdo->prepare("SELECT id FROM logins WHERE email = ? LIMIT 1");
    $tmp->execute([$_SESSION['user']]);
    if ($r = $tmp->fetch(PDO::FETCH_ASSOC)) {
        $user_id = $r['id'];
    }
}
if (!$user_id) {
    header('Location: login.php');
    exit;
}

// get current user info including app_id
$userRowStmt = $pdo->prepare("SELECT id, fullname, username, email, phone, app_id 
                              FROM logins WHERE id = ? LIMIT 1");
$userRowStmt->execute([$user_id]);
$userRow = $userRowStmt->fetch(PDO::FETCH_ASSOC);

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subject  = trim($_POST['subject'] ?? '');
    $message  = trim($_POST['message'] ?? '');
    $reply_to = intval($_POST['reply_to'] ?? 0);

    if ($subject === '' || $message === '') {
        $error = "Please fill in both subject and message.";
    } else {
        try {
            // determine ticket_id
            $ticket_id = null;
            if ($reply_to > 0) {
                $t = $pdo->prepare("SELECT ticket_id FROM message WHERE id = ? AND log_id = ? LIMIT 1");
                $t->execute([$reply_to, $user_id]);
                $trow = $t->fetch(PDO::FETCH_ASSOC);
                $ticket_id = $trow['ticket_id'] ?? $reply_to;
            }

            // insert message
            $ins = $pdo->prepare("INSERT INTO message
                (log_id, name, username, email, phone, title, note, status, marked, date, ticket_id, app_id, ip)
                VALUES (:log_id, :name, :username, :email, :phone, :title, :note, :status, :marked, NOW(), :ticket_id, :app_id, :ip)
            ");
            $ins->execute([
                ':log_id'   => $user_id,
                ':name'     => $userRow['fullname'] ?? $userRow['username'] ?? '',
                ':username' => $userRow['username'] ?? '',
                ':email'    => $userRow['email'] ?? '',
                ':phone'    => $userRow['phone'] ?? '',
                ':title'    => $subject,
                ':note'     => $message,
                ':status'   => 1, // outgoing
                ':marked'   => 0,
                ':ticket_id'=> $ticket_id ?? 0,
                ':app_id'   => $userRow['app_id'] ?? 0,
                ':ip'       => $_SERVER['REMOTE_ADDR'] ?? ''
            ]);

            $new_id = $pdo->lastInsertId();

            // if new thread, update ticket_id
            if (empty($ticket_id)) {
                $u = $pdo->prepare("UPDATE message SET ticket_id = ? WHERE id = ?");
                $u->execute([$new_id, $new_id]);
            }

            // if replying, update original message status -> 1
            if ($reply_to > 0) {
                $upd = $pdo->prepare("UPDATE message SET status = 1 WHERE id = ? AND log_id = ?");
                $upd->execute([$reply_to, $user_id]);
            }

            header("Location: outbox.php?sent=1");
            exit;
        } catch (PDOException $e) {
            error_log("Support insert error: " . $e->getMessage());
            $error = "Database error: could not send message.";
        }
    }
}

require_once __DIR__ . '/header_cur.php';

// if replying
$original = null;
if (isset($_GET['id'])) {
    $orig_id = intval($_GET['id']);
    $s = $pdo->prepare("SELECT * FROM message WHERE id = ? AND log_id = ? LIMIT 1");
    $s->execute([$orig_id, $user_id]);
    $original = $s->fetch(PDO::FETCH_ASSOC) ?: null;
}
?>

<main class="flex-1 px-2 py-2 md:p-4 pb-20 md:pb-6 overflow-hidden">
  <div class="space-y-6 mb-5 md:mb-1">
    <div class="pb-4 border-b border-gray-800/50">
      <h1 class="text-2xl md:text-3xl font-bold text-white">
        <?= $original ? "📨 Reply to Message" : "✉️ Contact Support" ?>
      </h1>
      <p class="text-gray-400 text-sm mt-1">
        <?= $original ? "You are replying to the message below." : "Send a message to our support team." ?>
      </p>
    </div>

    <?php if ($error): ?>
      <div class="p-4 mb-4 text-red-400 bg-red-900/20 rounded-lg"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="grid lg:grid-cols-3 gap-6">
      <div class="lg:col-span-2">
        <div class="bg-[#0F0A1F] rounded-2xl">
          <div class="p-6 border-b border-gray-800/50">
            <h2 class="text-lg font-medium"><?= $original ? "Reply Form" : "Write a Message" ?></h2>
          </div>

          <div class="p-6">
            <form method="POST" class="space-y-6">
              <input type="hidden" name="reply_to" value="<?= (int)($original['id'] ?? 0) ?>">
              <input type="hidden" name="app_id" value="<?= htmlspecialchars($userRow['app_id'] ?? 0) ?>">

              <div class="space-y-2">
                <label class="text-sm text-gray-400">Subject</label>
                <div class="relative">
                  <div class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400">
                    <i class="fas fa-heading"></i>
                  </div>
                  <input type="text" name="subject"
                         value="<?= $original ? "Re: ".htmlspecialchars($original['title']) : '' ?>"
                         class="w-full bg-[#1A1428] border border-gray-800 rounded-xl pl-10 pr-4 py-3 focus:outline-none focus:border-[#2FE6DE]"
                         required>
                </div>
              </div>

              <div class="space-y-2">
                <label class="text-sm text-gray-400">Message</label>
                <textarea name="message" rows="6"
                          class="w-full bg-[#1A1428] border border-gray-800 rounded-xl px-4 py-3 focus:outline-none focus:border-[#2FE6DE]"
                          placeholder="<?= $original ? 'Type your reply...' : 'Type your message...' ?>" required></textarea>
              </div>

              <button type="submit"
                      class="w-full bg-gradient-to-r from-[#2FE6DE] to-[#2FE6DE]/80 text-black font-medium px-6 py-4 rounded-xl">
                <i class="fas fa-paper-plane"></i> <?= $original ? 'Send Reply' : 'Send Message' ?>
              </button>
            </form>
          </div>
        </div>

        <?php if ($original): ?>
          <div class="bg-[#1A1428] rounded-xl p-6 mt-6 border border-gray-800/50">
            <h3 class="text-lg font-semibold text-[#2FE6DE] mb-2"><?= htmlspecialchars($original['title']) ?></h3>
            <p class="text-gray-300 whitespace-pre-line"><?= nl2br(htmlspecialchars($original['note'])) ?></p>
            <div class="text-xs text-gray-500 mt-3">Sent on <?= date("M d, Y H:i", strtotime($original['date'])) ?></div>
          </div>
        <?php endif; ?>
      </div>

      <div class="lg:col-span-1">
        <div class="bg-[#0F0A1F] rounded-2xl">
          <div class="p-6 border-b border-gray-800/50">
            <h3 class="text-lg font-medium">Contact Information</h3>
          </div>
          <div class="p-6 space-y-6">
            <div class="bg-[#1A1428] rounded-xl p-4">
              <div class="flex items-start gap-4">
                <div class="w-10 h-10 bg-[#2FE6DE]/10 rounded-lg flex items-center justify-center">
                  <i class="fas fa-envelope text-[#2FE6DE]"></i>
                </div>
                <div>
                  <h4 class="font-medium mb-1">Email Support</h4>
                  <a href="mailto:<?php echo $email2 ?>" class="text-[#2FE6DE]"><?php echo $email2 ?></a>
                </div>
              </div>
            </div>
            <div class="bg-[#1A1428] rounded-xl p-4">
              <div class="flex items-start gap-4">
                <div class="w-10 h-10 bg-[#2FE6DE]/10 rounded-lg flex items-center justify-center">
                  <i class="fas fa-clock text-[#2FE6DE]"></i>
                </div>
                <div>
                  <h4 class="font-medium mb-1">Support Hours</h4>
                  <p class="text-sm text-gray-400">24/7 Support Available</p>
                </div>
              </div>
            </div>
            <div class="bg-[#1A1428] rounded-xl p-4">
              <div class="flex items-start gap-4">
                <div class="w-10 h-10 bg-[#2FE6DE]/10 rounded-lg flex items-center justify-center">
                  <i class="fas fa-history text-[#2FE6DE]"></i>
                </div>
                <div>
                  <h4 class="font-medium mb-1">Response Time</h4>
                  <p class="text-sm text-gray-400">We typically respond within 24 hours</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<?php require_once __DIR__ . '/footer.php'; ?>
