<?php
/**
 * User Support Page
 */
$pageTitle = 'Support';
require_once 'includes/header.php';

$error = '';
$success = '';

// Handle ticket submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_GET['ticket'])) {
    $subject = trim($_POST['subject'] ?? '');
    $category = $_POST['category'] ?? 'general';
    $message = trim($_POST['message'] ?? '');
    
    if (empty($subject) || empty($message)) {
        $error = 'Subject and message are required';
    } else {
        $ticketId = 'TKT' . strtoupper(substr(md5(uniqid()), 0, 8));
        dbInsert('support_tickets', [
            'ticket_id' => $ticketId,
            'user_id' => $user['id'],
            'subject' => $subject,
            'category' => $category,
            'status' => 'open'
        ]);
        $ticketDbId = db()->lastInsertId();
        dbInsert('ticket_messages', [
            'ticket_id' => $ticketDbId,
            'user_id' => $user['id'],
            'message' => $message,
            'is_admin' => 0
        ]);
        $success = 'Ticket created! ID: ' . $ticketId;
    }
}

$tickets = dbFetchAll("SELECT * FROM support_tickets WHERE user_id = :id ORDER BY created_at DESC", ['id' => $user['id']]);

$viewTicket = null;
$ticketMessages = [];
if (!empty($_GET['ticket'])) {
    $viewTicket = dbFetch("SELECT * FROM support_tickets WHERE ticket_id = :tid AND user_id = :uid", ['tid' => $_GET['ticket'], 'uid' => $user['id']]);
    if ($viewTicket) {
        $ticketMessages = dbFetchAll("SELECT * FROM ticket_messages WHERE ticket_id = :id ORDER BY created_at ASC", ['id' => $viewTicket['id']]);
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['reply'])) {
            dbInsert('ticket_messages', ['ticket_id' => $viewTicket['id'], 'user_id' => $user['id'], 'message' => trim($_POST['reply']), 'is_admin' => 0]);
            header('Location: support.php?ticket=' . $viewTicket['ticket_id']); exit;
        }
    }
}
?>

<style>
.support-grid{display:grid;grid-template-columns:1fr 1fr;gap:1.5rem}
@media(max-width:992px){.support-grid{grid-template-columns:1fr}}
.contact-card{background:var(--bg-tertiary);border-radius:var(--radius-md);padding:1.5rem;text-align:center}
.contact-card i{font-size:2rem;color:var(--accent-green);margin-bottom:.75rem}
.contact-card a{color:var(--accent-green)}
.ticket-item{display:flex;align-items:center;padding:1rem;border-bottom:1px solid var(--border-color);cursor:pointer}
.ticket-item:hover{background:var(--bg-tertiary)}
.ticket-status{width:10px;height:10px;border-radius:50%;margin-right:1rem}
.ticket-status.open{background:var(--accent-green)}
.ticket-status.closed{background:var(--text-muted)}
.chat-container{height:400px;overflow-y:auto;padding:1rem;background:var(--bg-tertiary);border-radius:var(--radius-md);margin-bottom:1rem}
.chat-message{margin-bottom:1rem;max-width:80%}
.chat-message.user{margin-left:auto}
.chat-message.admin{margin-right:auto}
.chat-bubble{padding:.75rem 1rem;border-radius:12px;font-size:.9rem}
.chat-message.user .chat-bubble{background:var(--accent-green);color:#fff}
.chat-message.admin .chat-bubble{background:var(--bg-card)}
.chat-meta{font-size:.7rem;color:var(--text-muted);margin-top:.25rem}
</style>

<?php if($error):?><div class="alert alert-danger"><?=$error?></div><?php endif;?>
<?php if($success):?><div class="alert alert-success"><?=$success?></div><?php endif;?>

<?php if($viewTicket):?>
<div class="card">
    <div class="card-header">
        <a href="support.php" class="text-muted"><i class="fas fa-arrow-left"></i> Back</a>
        <h3 class="card-title" style="margin-top:.5rem"><?=htmlspecialchars($viewTicket['subject'])?></h3>
        <div class="text-muted" style="font-size:.8rem"><?=$viewTicket['ticket_id']?> • <span class="badge badge-<?=$viewTicket['status']==='open'?'success':'secondary'?>"><?=ucfirst($viewTicket['status'])?></span></div>
    </div>
    <div class="card-body">
        <div class="chat-container" id="chatContainer">
            <?php foreach($ticketMessages as $msg):?>
            <div class="chat-message <?=$msg['is_admin']?'admin':'user'?>">
                <div class="chat-bubble"><?=nl2br(htmlspecialchars($msg['message']))?></div>
                <div class="chat-meta"><?=$msg['is_admin']?'Support':'You'?> • <?=formatDateTime($msg['created_at'],'d M, H:i')?></div>
            </div>
            <?php endforeach;?>
        </div>
        <?php if($viewTicket['status']!=='closed'):?>
        <form method="POST"><div class="d-flex gap-2"><input type="text" name="reply" class="form-control" placeholder="Type message..." required><button class="btn btn-primary"><i class="fas fa-paper-plane"></i></button></div></form>
        <?php endif;?>
    </div>
</div>
<script>document.getElementById('chatContainer').scrollTop=document.getElementById('chatContainer').scrollHeight;</script>

<?php else:?>
<div class="support-grid">
    <div>
        <div class="card mb-4">
            <div class="card-header"><h3 class="card-title">Quick Contact</h3></div>
            <div class="card-body">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem">
                    <div class="contact-card" onclick="openLiveChat()" style="cursor:pointer"><i class="fas fa-comments"></i><h4>Live Chat</h4><p>Click to start chat</p></div>
                    <div class="contact-card"><i class="fas fa-envelope"></i><h4>Email</h4><p><a href="mailto:support@example.com">support@example.com</a></p></div>
                </div>
            </div>
        </div>
        <div class="card">
            <div class="card-header"><h3 class="card-title">Create Ticket</h3></div>
            <div class="card-body">
                <form method="POST">
                    <div class="form-group"><label class="form-label">Category</label><select name="category" class="form-control"><option value="general">General</option><option value="deposit">Deposit</option><option value="withdrawal">Withdrawal</option><option value="trading">Trading</option><option value="technical">Technical</option></select></div>
                    <div class="form-group"><label class="form-label">Subject</label><input type="text" name="subject" class="form-control" required></div>
                    <div class="form-group"><label class="form-label">Message</label><textarea name="message" class="form-control" rows="4" required></textarea></div>
                    <button class="btn btn-primary btn-block"><i class="fas fa-paper-plane"></i> Submit Ticket</button>
                </form>
            </div>
        </div>
    </div>
    <div>
        <div class="card">
            <div class="card-header"><h3 class="card-title">Your Tickets</h3></div>
            <div class="card-body p-0">
                <?php foreach($tickets as $t):?>
                <a href="?ticket=<?=$t['ticket_id']?>" class="ticket-item" style="text-decoration:none;color:inherit">
                    <div class="ticket-status <?=$t['status']?>"></div>
                    <div class="flex-1">
                        <div class="font-semibold"><?=htmlspecialchars($t['subject'])?></div>
                        <div class="text-muted" style="font-size:.75rem"><?=$t['ticket_id']?> • <?=timeAgo($t['created_at'])?></div>
                    </div>
                    <span class="badge badge-<?=$t['status']==='open'?'success':'secondary'?>"><?=ucfirst($t['status'])?></span>
                </a>
                <?php endforeach;?>
                <?php if(empty($tickets)):?><div class="p-4 text-center text-muted">No tickets yet</div><?php endif;?>
            </div>
        </div>
    </div>
</div>
<?php endif;?>

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