<?php
include(__DIR__ . '/../includes/db.php');
include(__DIR__ . '/../includes/header.php');
include(__DIR__ . '/../includes/navbar.php');

// Handle email ticket submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message_type'])) {
    $user_name  = 'Guest'; // replace with session username if logged in
    $user_email = 'guest@example.com'; // replace with session email
    $message    = mysqli_real_escape_string($conn, $_POST['message']);
    $type       = $_POST['message_type'];

    mysqli_query($conn, "INSERT INTO support_tickets 
        (user_name,user_email,message_type,message,status,created_at)
        VALUES ('$user_name','$user_email','$type','$message','Open',NOW())");
}
?>

<style>
.support-page{max-width:1100px;margin:auto;padding:30px 15px}
.page-title{text-align:center;font-weight:700;margin-bottom:25px}
.ticket-tabs{display:flex;justify-content:center;gap:10px;margin-bottom:25px}
.ticket-tabs button{border:none;padding:10px 26px;border-radius:25px;background:#e9ecef;font-weight:600;cursor:pointer;transition:.3s}
.ticket-tabs button.active,.ticket-tabs button:hover{background:#0d6efd;color:#fff}
.ticket-section{margin-top:25px}
.ticket-card{background:#fff;border-radius:14px;padding:18px 22px;margin-bottom:15px;box-shadow:0 10px 30px rgba(0,0,0,0.06)}
.ticket-card h6{font-weight:600;margin-bottom:5px}
.ticket-card p{font-size:13px;color:#6c757d}
.ticket-status{padding:6px 15px;border-radius:20px;font-size:13px;font-weight:600}
.ticket-status.open{background:#e7f1ff;color:#0d6efd}
.ticket-status.closed{background:#e6f7ef;color:#198754}
.support-box{background:#fff;border-radius:16px;padding:22px;margin-top:30px;box-shadow:0 12px 35px rgba(0,0,0,.08)}
.support-box h5{font-weight:700;margin-bottom:12px}
.support-box textarea{width:100%;min-height:90px;border-radius:12px;padding:12px;border:1px solid #ddd;resize:none}
.support-box button{margin-top:10px;background:#0d6efd;color:#fff;border:none;padding:10px 28px;border-radius:25px;font-weight:600;cursor:pointer}
.chat-window{background:#f8f9fa;border-radius:12px;padding:15px;height:260px;overflow-y:auto;margin-bottom:10px}
.chat-msg{max-width:75%;padding:10px 14px;border-radius:16px;font-size:14px;margin-bottom:10px}
.chat-msg.user{background:#0d6efd;color:#fff;margin-left:auto}
.chat-msg.bot{background:#e9ecef}
.admin-reply{background:#f1f3f5;padding:12px;border-radius:10px;margin-top:10px;font-size:14px}
</style>

<div class="container support-page">
<h2 class="page-title">Support Tickets</h2>

<!-- Tabs -->
<div class="ticket-tabs">
    <button class="active" onclick="showTab('open',this)">Open Tickets</button>
    <button onclick="showTab('closed',this)">Closed Tickets</button>
</div>

<!-- Open Tickets -->
<div id="open" class="ticket-section">
<?php
$open = mysqli_query($conn,"SELECT * FROM support_tickets WHERE status='Open' AND user_email='guest@example.com' ORDER BY created_at DESC");
if(mysqli_num_rows($open)){
    while($t = mysqli_fetch_assoc($open)){
        echo '<div class="ticket-card">
            <h6>'.htmlspecialchars($t['message']).'</h6>
            <p>'.htmlspecialchars($t['user_name']).' • '.date('d M Y',strtotime($t['created_at'])).'</p>';
        if(!empty($t['admin_reply'])){
            echo '<div class="admin-reply"><strong>Admin Reply:</strong><p>'.htmlspecialchars($t['admin_reply']).'</p></div>';
        }
        echo '<span class="ticket-status open">Open</span></div>';
    }
}else{
    echo '<p class="text-center mt-3">No open tickets.</p>';
}
?>
</div>

<!-- Closed Tickets -->
<div id="closed" class="ticket-section" style="display:none;">
<?php
$closed = mysqli_query($conn,"SELECT * FROM support_tickets WHERE status='Closed' AND user_email='guest@example.com' ORDER BY created_at DESC");
if(mysqli_num_rows($closed)){
    while($t = mysqli_fetch_assoc($closed)){
        echo '<div class="ticket-card">
            <h6>'.htmlspecialchars($t['message']).'</h6>
            <p>'.htmlspecialchars($t['user_name']).' • '.date('d M Y',strtotime($t['created_at'])).'</p>';
        if(!empty($t['admin_reply'])){
            echo '<div class="admin-reply"><strong>Admin Reply:</strong><p>'.htmlspecialchars($t['admin_reply']).'</p></div>';
        }
        echo '<span class="ticket-status closed">Closed</span></div>';
    }
}else{
    echo '<p class="text-center mt-3">No closed tickets.</p>';
}
?>
</div>

<!-- Live Chat -->
<div class="support-box">
<h5>Live Chat Support</h5>
<div class="chat-window" id="chatWindow"></div>
<form onsubmit="return sendChat();">
    <textarea id="chatInput" placeholder="Type your message..." required></textarea>
    <button type="submit">Send</button>
</form>
</div>

<!-- Email Ticket -->
<div class="support-box">
<h5>Email Support</h5>
<form method="POST">
    <textarea name="message" placeholder="Write your issue..." required></textarea>
    <input type="hidden" name="message_type" value="email">
    <button type="submit">Submit Ticket</button>
</form>
</div>
</div>

<script>
function showTab(id,btn){
    document.getElementById('open').style.display='none';
    document.getElementById('closed').style.display='none';
    document.getElementById(id).style.display='block';
    document.querySelectorAll('.ticket-tabs button').forEach(b=>b.classList.remove('active'));
    btn.classList.add('active');
}

/* Live Chat Send */
function sendChat(){
    let input=document.getElementById('chatInput');
    let msg=input.value.trim();
    if(!msg) return false;

    let chat=document.getElementById('chatWindow');
    chat.innerHTML += `<div class="chat-msg user">${msg}</div>`;
    input.value='';
    chat.scrollTop=chat.scrollHeight;

    /* Send to server via AJAX */
    fetch('ajax_support_chat.php',{
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'message='+encodeURIComponent(msg)+'&type=chat'
    });

    setTimeout(()=>{ // simulated admin reply
        fetch('ajax_support_chat.php?get=1')
        .then(res=>res.json())
        .then(data=>{
            if(data.reply){
                chat.innerHTML += `<div class="chat-msg bot">${data.reply}</div>`;
                chat.scrollTop=chat.scrollHeight;
            }
        });
    },500);

    return false;
}
</script>

<?php
include(__DIR__ . '/../includes/footer.php');
include(__DIR__ . '/../includes/scripts.php');
?>
