<?php
// ============================================================
//  tickets.php  —  Author: Raise a Support Ticket
//  Shares support_tickets + ticket_messages tables with reviewer
// ============================================================
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set("display_errors", 0);
require_once __DIR__ . '/config/db.php';
startSession();

$user    = getCurrentUser();
$user_id = $user['user_id'];

$pageTitle  = 'Raise a Ticket';
$activePage = 'tickets';

// ── Auto-create tables ────────────────────────────────────────
try {
    db()->exec("CREATE TABLE IF NOT EXISTS support_tickets (
        ticket_id       INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        user_id         INT UNSIGNED NOT NULL,
        user_type       ENUM('author','reviewer') DEFAULT 'author',
        subject         VARCHAR(255) NOT NULL,
        category        VARCHAR(80)  DEFAULT 'General',
        priority        ENUM('low','medium','high') DEFAULT 'medium',
        status          ENUM('open','in_progress','resolved','closed') DEFAULT 'open',
        created_at      DATETIME DEFAULT NOW(),
        updated_at      DATETIME DEFAULT NOW() ON UPDATE NOW()
    )");
    db()->exec("CREATE TABLE IF NOT EXISTS ticket_messages (
        message_id      INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        ticket_id       INT UNSIGNED NOT NULL,
        sender_id       INT UNSIGNED NOT NULL,
        sender_type     ENUM('user','admin') DEFAULT 'user',
        message         TEXT NOT NULL,
        attachment_name VARCHAR(255) DEFAULT NULL,
        attachment_path VARCHAR(500) DEFAULT NULL,
        is_read         TINYINT(1) DEFAULT 0,
        created_at      DATETIME DEFAULT NOW()
    )");
    // Silent column additions for older tables
    foreach ([
        'user_type ENUM(\'author\',\'reviewer\') DEFAULT \'author\'',
        'priority ENUM(\'low\',\'medium\',\'high\') DEFAULT \'medium\'',
        'category VARCHAR(80) DEFAULT \'General\'',
        'submission_id INT UNSIGNED DEFAULT NULL',
    ] as $c) {
        try { db()->exec("ALTER TABLE support_tickets ADD COLUMN $c"); } catch(PDOException $e) {}
    }
} catch(PDOException $e) {}

// ── INLINE AJAX: Submit new ticket ───────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_submit_ticket'])) {
    header('Content-Type: application/json');
    try {
        $subject     = trim($_POST['subject']      ?? '');
        $category    = trim($_POST['category']     ?? 'General');
        $priority    = trim($_POST['priority']     ?? 'medium');
        $message     = trim($_POST['message']      ?? '');
        $submission_id = (int)($_POST['submission_id'] ?? 0) ?: null;

        if (!$subject || !$message) {
            echo json_encode(['success' => false, 'message' => 'Subject and message are required.']);
            exit;
        }

        $priority = in_array($priority, ['low','medium','high']) ? $priority : 'medium';

        // Verify submission belongs to this user (if provided)
        if ($submission_id) {
            $chk = db()->prepare("SELECT submission_id FROM submissions WHERE submission_id=? AND user_id=? AND submission_status != 'draft'");
            $chk->execute([$submission_id, $user_id]);
            if (!$chk->fetch()) $submission_id = null;
        }

        db()->prepare(
            "INSERT INTO support_tickets (user_id, user_type, submission_id, subject, category, priority, status, created_at, updated_at)
             VALUES (?, 'author', ?, ?, ?, ?, 'open', NOW(), NOW())"
        )->execute([$user_id, $submission_id, $subject, $category, $priority]);

        $ticket_id = (int)db()->lastInsertId();

        db()->prepare(
            "INSERT INTO ticket_messages (ticket_id, sender_id, sender_type, message, created_at)
             VALUES (?, ?, 'user', ?, NOW())"
        )->execute([$ticket_id, $user_id, $message]);

        echo json_encode(['success' => true, 'ticket_id' => $ticket_id]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

$categories = ['General', 'Submission Issue', 'Payment Issue', 'Technical Problem', 'Review Process', 'Editorial Query', 'Account Issue', 'Other'];

// Load only FINAL (non-draft) submissions for this author
try {
    $sq = db()->prepare(
        "SELECT s.submission_id, s.tracking_code, s.submission_status,
                mi.article_title,
                j.name AS journal_name
         FROM submissions s
         LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
         LEFT JOIN journals j ON j.journal_id = s.journal_id
         WHERE s.user_id = ?
           AND s.submission_status IN ('submitted','under_review','accepted','rejected')
         ORDER BY s.updated_at DESC"
    );
    $sq->execute([$user_id]);
    $submittedSubs = $sq->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) { $submittedSubs = []; }

require_once __DIR__ . '/_layout.php';
?>

<style>
.au-main { padding: 24px 28px 60px; }

.tk-container { max-width: 700px; margin: 0 auto; }

.tk-info-banner {
  background: #EFF6FF; border: 1px solid #BFDBFE;
  border-radius: 10px; padding: 14px 18px;
  display: flex; align-items: flex-start; gap: 12px;
  margin-bottom: 22px; font-size: 13px; color: #1E40AF; line-height: 1.6;
}
.tk-info-icon { font-size: 18px; flex-shrink: 0; margin-top: 1px; }

.tk-card {
  background: var(--white);
  border: 1px solid var(--border);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0,0,0,.06);
}
.tk-card-header {
  display: flex; align-items: center; gap: 14px;
  padding: 20px 24px; border-bottom: 1px solid var(--border);
}
.tk-card-icon {
  width: 42px; height: 42px; border-radius: 10px;
  background: #FEF3C7;
  display: flex; align-items: center; justify-content: center;
  font-size: 20px; flex-shrink: 0;
}
.tk-card-title { font-size: 16px; font-weight: 700; color: var(--text); }
.tk-card-sub   { font-size: 12.5px; color: var(--muted); margin-top: 2px; }
.tk-card-body  { padding: 24px; }

.tk-group { margin-bottom: 18px; }
.tk-group:last-of-type { margin-bottom: 0; }
.tk-label {
  display: block; font-size: 13px; font-weight: 600;
  color: var(--text); margin-bottom: 6px;
}
.tk-label .req { color: #DC2626; }
.tk-label .opt { font-weight: 400; color: var(--muted); font-size: 11.5px; }
.tk-input, .tk-select, .tk-textarea {
  width: 100%; padding: 9px 13px;
  border: 1.5px solid var(--border); border-radius: 8px;
  font-family: var(--font); font-size: 13.5px;
  color: var(--text); background: var(--white);
  outline: none; transition: border-color .15s;
}
.tk-input:focus, .tk-select:focus, .tk-textarea:focus {
  border-color: var(--blue);
  box-shadow: 0 0 0 3px rgba(27,63,110,.1);
}
.tk-input.err, .tk-textarea.err { border-color: #DC2626 !important; }
.tk-textarea { resize: vertical; min-height: 130px; line-height: 1.6; }

.tk-row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
@media(max-width:560px) { .tk-row2 { grid-template-columns: 1fr; } }

.tk-char-count { font-size: 11.5px; color: var(--muted); text-align: right; margin-top: 4px; }

.tk-priority-row { display: flex; gap: 10px; margin-top: 6px; }
.tk-prio-btn {
  flex: 1; padding: 8px 10px; border-radius: 8px; font-family: var(--font);
  font-size: 12.5px; font-weight: 600; cursor: pointer; text-align: center;
  border: 2px solid var(--border); background: var(--white);
  color: var(--muted); transition: all .15s;
}
.tk-prio-btn:hover { border-color: var(--blue); color: var(--blue); }
.tk-prio-btn.sel-low    { border-color: #22C55E; background: #F0FDF4; color: #16A34A; }
.tk-prio-btn.sel-medium { border-color: #F59E0B; background: #FFFBEB; color: #D97706; }
.tk-prio-btn.sel-high   { border-color: #EF4444; background: #FFF5F5; color: #DC2626; }
input[name="priority"] { display: none; }

.tk-field-err { font-size: 12px; color: #DC2626; margin-top: 4px; display: none; }
.tk-field-err.show { display: block; }

.btn-submit-ticket {
  width: 100%; padding: 13px; border-radius: 8px;
  background: var(--blue); color: #fff; border: none;
  font-family: var(--font); font-size: 14px; font-weight: 700;
  cursor: pointer; transition: background .15s;
  display: flex; align-items: center; justify-content: center; gap: 8px;
  margin-top: 6px;
}
.btn-submit-ticket:hover    { background: #132B50; }
.btn-submit-ticket:disabled { opacity: .6; cursor: not-allowed; }

/* Success screen */
.tk-success {
  display: none; text-align: center; padding: 40px 24px;
}
.tk-success.show { display: block; }
.tk-success-icon { font-size: 52px; margin-bottom: 16px; }
.tk-success-title { font-size: 20px; font-weight: 700; color: var(--text); margin-bottom: 8px; }
.tk-success-sub   { font-size: 14px; color: var(--muted); line-height: 1.7; margin-bottom: 24px; }
.tk-success-id {
  display: inline-flex; align-items: center; gap: 10px;
  background: #F0F9FF; border: 1.5px solid #BAE6FD;
  border-radius: 8px; padding: 10px 20px; font-size: 15px;
  font-weight: 700; color: #0369A1; margin-bottom: 24px;
}
.tk-success-actions { display: flex; gap: 12px; justify-content: center; flex-wrap: wrap; }
.btn-secondary {
  padding: 10px 22px; border-radius: 8px; background: var(--white);
  border: 1.5px solid var(--border); font-family: var(--font);
  font-size: 13.5px; font-weight: 600; color: var(--text);
  cursor: pointer; transition: all .15s; text-decoration: none;
  display: inline-flex; align-items: center; gap: 6px;
}
.btn-secondary:hover { border-color: var(--blue); color: var(--blue); }

/* Toast */
.toast-wrap { position: fixed; bottom: 24px; right: 24px; display: flex; flex-direction: column; gap: 8px; z-index: 9999; }
.toast { padding: 11px 16px; border-radius: 8px; font-size: 13px; font-weight: 500; color: #fff; box-shadow: 0 4px 14px rgba(0,0,0,.18); display: flex; align-items: center; gap: 8px; animation: tup .25s ease; }
.ts { background: #1D8A5E; } .te { background: #DC2626; }
@keyframes tup { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:translateY(0)} }
.spinner { display: inline-block; width: 15px; height: 15px; border: 2px solid rgba(255,255,255,.3); border-top-color: #fff; border-radius: 50%; animation: spin .6s linear infinite; }
@keyframes spin { to{transform:rotate(360deg)} }
</style>

<div class="tk-container">

  <div class="tk-info-banner">
    <span class="tk-info-icon">ℹ️</span>
    <div>Need help with your submission, payment, or account? Submit a ticket below and our support team will respond within 24–48 hours. You can track your tickets under <strong>My Tickets</strong>.</div>
  </div>

  <div class="tk-card">
    <div class="tk-card-header">
      <div class="tk-card-icon">🎫</div>
      <div>
        <div class="tk-card-title">Raise a Support Ticket</div>
        <div class="tk-card-sub">Describe your issue and we'll get back to you</div>
      </div>
    </div>

    <!-- Form -->
    <div class="tk-card-body" id="ticketForm">

      <!-- Subject -->
      <div class="tk-group">
        <label class="tk-label" for="tkSubject">Subject <span class="req">*</span></label>
        <input type="text" class="tk-input" id="tkSubject"
               placeholder="Brief description of your issue"
               maxlength="200" oninput="clearErr('tkSubjectErr', this)">
        <div class="tk-field-err" id="tkSubjectErr">Please enter a subject</div>
      </div>

      <!-- Category + Priority -->
      <div class="tk-row2">
        <div class="tk-group">
          <label class="tk-label" for="tkCategory">Category</label>
          <select class="tk-select" id="tkCategory">
            <?php foreach ($categories as $cat): ?>
            <option value="<?= htmlspecialchars($cat) ?>"><?= htmlspecialchars($cat) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="tk-group">
          <label class="tk-label">Priority</label>
          <div class="tk-priority-row">
            <button type="button" class="tk-prio-btn sel-low" data-val="low"   onclick="setPriority('low')">🟢 Low</button>
            <button type="button" class="tk-prio-btn"         data-val="medium" onclick="setPriority('medium')">🟡 Medium</button>
            <button type="button" class="tk-prio-btn"         data-val="high"  onclick="setPriority('high')">🔴 High</button>
          </div>
          <input type="hidden" id="tkPriority" value="low">
        </div>
      </div>

      <!-- Related Submission -->
      <div class="tk-group">
        <label class="tk-label" for="tkSubmission">
          Related Submission <span class="opt">(optional)</span>
        </label>
        <?php if (empty($submittedSubs)): ?>
        <div style="padding:9px 13px;border:1.5px solid var(--border);border-radius:8px;font-size:13px;color:var(--muted);background:#F9FAFB">
          No submitted manuscripts found
        </div>
        <?php else: ?>
        <select class="tk-select" id="tkSubmission">
          <option value="">— Not related to a specific submission —</option>
          <?php foreach ($submittedSubs as $sub):
            $title = $sub['article_title'] ?? 'Untitled Manuscript';
            if (strlen($title) > 70) $title = substr($title, 0, 70) . '…';
            $statusLabel = ucfirst(str_replace('_', ' ', $sub['submission_status']));
            $code = $sub['tracking_code'] ? '[' . $sub['tracking_code'] . '] ' : '';
          ?>
          <option value="<?= $sub['submission_id'] ?>">
            <?= htmlspecialchars($code . $title) ?> — <?= $statusLabel ?>
          </option>
          <?php endforeach; ?>
        </select>
        <?php endif; ?>
        <div style="font-size:11.5px;color:var(--muted);margin-top:4px">
          Only final submissions (submitted, under review, accepted, rejected) are shown
        </div>
      </div>

      <!-- Message -->
      <div class="tk-group">
        <label class="tk-label" for="tkMessage">Message <span class="req">*</span></label>
        <textarea class="tk-textarea" id="tkMessage"
                  placeholder="Describe your issue in detail. Include any relevant submission IDs, error messages, or screenshots you can describe..."
                  maxlength="3000"
                  oninput="updateCharCount(this, 'tkMsgCount', 3000); clearErr('tkMessageErr', this)"></textarea>
        <div style="display:flex;justify-content:space-between;align-items:center;margin-top:4px">
          <div class="tk-field-err show" id="tkMessageErr" style="display:none!important"></div>
          <div class="tk-char-count" id="tkMsgCount">0 / 3000</div>
        </div>
        <div class="tk-field-err" id="tkMessageErr">Please describe your issue</div>
      </div>

      <button type="button" class="btn-submit-ticket" id="submitTicketBtn" onclick="submitTicket()">
        🎫 Submit Ticket
      </button>

    </div>

    <!-- Success screen (hidden until submitted) -->
    <div class="tk-success" id="ticketSuccess">
      <div class="tk-success-icon">✅</div>
      <div class="tk-success-title">Ticket Submitted!</div>
      <div class="tk-success-sub">
        Your support ticket has been received. Our team will review it and respond within 24–48 hours.<br>
        You will be notified via email.
      </div>
      <div class="tk-success-id" id="successTicketId">🎫 Ticket #—</div>
      <div class="tk-success-actions">
        <a href="my_tickets.php" class="btn-secondary">📋 View My Tickets</a>
        <button type="button" class="btn-secondary" onclick="resetForm()">➕ Submit Another</button>
      </div>
    </div>
  </div>

</div>

<div class="toast-wrap" id="toastWrap"></div>

<script>
let selectedPriority = 'low';

function setPriority(val) {
    selectedPriority = val;
    document.getElementById('tkPriority').value = val;
    document.querySelectorAll('.tk-prio-btn').forEach(btn => {
        btn.className = 'tk-prio-btn';
        if (btn.dataset.val === val) btn.classList.add('sel-' + val);
    });
}

function updateCharCount(ta, countId, max) {
    document.getElementById(countId).textContent = ta.value.length + ' / ' + max;
}

function clearErr(errId, el) {
    const err = document.getElementById(errId);
    if (err) err.classList.remove('show');
    if (el) el.classList.remove('err');
}

function submitTicket() {
    const subject = document.getElementById('tkSubject').value.trim();
    const message = document.getElementById('tkMessage').value.trim();
    let valid = true;

    if (!subject) {
        document.getElementById('tkSubject').classList.add('err');
        document.getElementById('tkSubjectErr').classList.add('show');
        valid = false;
    }
    if (!message) {
        document.getElementById('tkMessage').classList.add('err');
        document.getElementById('tkMessageErr').classList.add('show');
        valid = false;
    }
    if (!valid) return;

    const btn = document.getElementById('submitTicketBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner"></span> Submitting...';

    const fd = new FormData();
    fd.append('ajax_submit_ticket', '1');
    fd.append('subject',       subject);
    fd.append('category',      document.getElementById('tkCategory').value);
    fd.append('priority',      document.getElementById('tkPriority').value);
    fd.append('submission_id', document.getElementById('tkSubmission') ? document.getElementById('tkSubmission').value : '');
    fd.append('message',       message);

    fetch('tickets.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = '🎫 Submit Ticket';
        if (data.success) {
            document.getElementById('ticketForm').style.display = 'none';
            document.getElementById('successTicketId').textContent = '🎫 Ticket CIJSS-TKT-' + String(data.ticket_id).padStart(4,'0');
            document.getElementById('ticketSuccess').classList.add('show');
        } else {
            showToast('❌ ' + (data.message || 'Failed to submit'), 'e');
        }
    })
    .catch(() => {
        btn.disabled = false;
        btn.innerHTML = '🎫 Submit Ticket';
        showToast('❌ Network error — please try again', 'e');
    });
}

function resetForm() {
    document.getElementById('tkSubject').value = '';
    document.getElementById('tkMessage').value = '';
    document.getElementById('tkMsgCount').textContent = '0 / 3000';
    document.getElementById('tkCategory').selectedIndex = 0;
    const subSel = document.getElementById('tkSubmission');
    if (subSel) subSel.selectedIndex = 0;
    setPriority('low');
    document.getElementById('ticketForm').style.display = '';
    document.getElementById('ticketSuccess').classList.remove('show');
    ['tkSubject','tkMessage'].forEach(id => {
        document.getElementById(id).classList.remove('err');
    });
    ['tkSubjectErr','tkMessageErr'].forEach(id => {
        document.getElementById(id).classList.remove('show');
    });
}

function showToast(msg, t = 'i') {
    const w = document.getElementById('toastWrap');
    const d = document.createElement('div');
    d.className = 'toast t' + t;
    d.textContent = msg;
    w.appendChild(d);
    setTimeout(() => d.remove(), 3500);
}
</script>

<?php layoutEnd(); ?>