<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';

if (!isLoggedIn() || $_SESSION['user_type'] !== 'seller') {
    redirect('../login.php');
}

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;

// Handle Ticket Creation
if (isset($_POST['create_ticket'])) {
    $subject = sanitize($_POST['subject']);
    $message = sanitize($_POST['message']);
    
    if (!empty($subject) && !empty($message)) {
        // seller_id = 0 means this ticket goes to the Admin
        $db->insert("INSERT INTO support_tickets (user_id, seller_id, subject, message, status) VALUES (?, 0, ?, ?, 'Open')", 
            [$user_id, $subject, $message]);
        $_SESSION['flash_success'] = "Ticket raised successfully! Admin will reply soon.";
    } else {
        $_SESSION['flash_error'] = "Please fill all required fields.";
    }
    redirect('tickets.php');
}

$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$unread_count = count($unread_notifs);
$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($company_logo, 'http') === 0) ? $company_logo : '../' . ltrim($company_logo, '/');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;

// Fetch categories ONLY if Admin allowed them to show (show_to_seller = 1)
$categories = $db->select("SELECT * FROM service_categories WHERE status = 1 AND show_to_seller = 1 ORDER BY display_order ASC");
$sidebar_allowed_cats = [];
$seller_cat_ids = !empty($user['seller_categories']) ? explode(',', $user['seller_categories']) : [1, 5]; 
foreach($categories as $cat) {
    if(in_array($cat['id'], $seller_cat_ids)) {
        $sidebar_allowed_cats[] = $cat;
    }
}

// Fetch Tickets Raised by Seller to Admin
$my_tickets = $db->select("SELECT * FROM support_tickets WHERE user_id = ? AND seller_id = 0 ORDER BY created_at DESC", [$user_id]);
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Support - WBMCZ Seller</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>body { font-family: 'Inter', sans-serif; } .font-poppins { font-family: 'Poppins', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; }</style>
</head>
<?php
/* ===== Premium shared layout (Navy + Gold) ===== */
require_once __DIR__ . '/../includes/theme.php';
$__scats = [];
if (isset($categories)) { $__ids = isset($seller_cat_ids) ? $seller_cat_ids : null; foreach ($categories as $__c) { if ($__ids === null || in_array($__c['id'], $__ids)) $__scats[] = $__c; } }
$__menu = theme_seller_menu($__scats);
theme_open([
    'panel'  => 'seller',
    'base'   => '../',
    'title'  => 'Customer Support',
    'active' => 'tickets',
    'user'   => isset($user) ? $user : ['name' => 'User', 'mobile' => ''],
    'wallet' => isset($wallet_balance) ? $wallet_balance : 0,
    'notifs' => isset($unread_notifs) ? $unread_notifs : [],
    'logo'   => isset($company_logo) ? $company_logo : '../assets/images/logo.png',
    'brand'  => isset($company_name) ? $company_name : 'WBMCZ',
    'menu'   => $__menu,
    'state'  => 'ticketModal: false',
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-8">
                
                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                    <div>
                        <h2 class="text-2xl font-bold text-gray-800 mb-1">Support Tickets</h2>
                        <p class="text-gray-500 text-sm">Facing an issue? Raise a ticket to the platform administrators.</p>
                    </div>
                    <button @click="ticketModal = true" class="bg-teal-600 hover:bg-teal-700 text-white px-5 py-2.5 rounded-xl font-bold shadow-md transition-colors flex items-center">
                        <i class="fas fa-plus-circle mr-2"></i> Raise New Ticket
                    </button>
                </div>

                <?php if (isset($_SESSION['flash_success'])): ?>
                    <div class="mb-6 bg-teal-50 border border-teal-200 text-teal-700 px-4 py-3 rounded-xl flex items-center shadow-sm" role="alert">
                        <i class="fas fa-check-circle mr-3 text-xl"></i>
                        <span class="font-medium"><?php echo $_SESSION['flash_success']; unset($_SESSION['flash_success']); ?></span>
                    </div>
                <?php endif; ?>
                <?php if (isset($_SESSION['flash_error'])): ?>
                    <div class="mb-6 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl flex items-center shadow-sm" role="alert">
                        <i class="fas fa-exclamation-circle mr-3 text-xl"></i>
                        <span class="font-medium"><?php echo $_SESSION['flash_error']; unset($_SESSION['flash_error']); ?></span>
                    </div>
                <?php endif; ?>

                <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wider border-b border-gray-100">
                                    <th class="p-4 pl-6 font-semibold w-1/4">Ticket Info</th>
                                    <th class="p-4 font-semibold w-1/2">Message & Admin Reply</th>
                                    <th class="p-4 pr-6 font-semibold text-right w-1/4">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-50">
                                <?php if(!empty($my_tickets)): foreach($my_tickets as $ticket): ?>
                                <tr class="hover:bg-gray-50 transition-colors">
                                    <td class="p-4 pl-6 align-top">
                                        <p class="font-bold text-gray-800">#TKT-<?php echo str_pad($ticket['id'], 5, '0', STR_PAD_LEFT); ?></p>
                                        <p class="text-xs text-gray-500 mt-1"><?php echo date('d M Y, h:i A', strtotime($ticket['created_at'])); ?></p>
                                    </td>
                                    <td class="p-4 align-top">
                                        <p class="font-bold text-sm text-gray-800 mb-1"><?php echo htmlspecialchars($ticket['subject']); ?></p>
                                        <p class="text-xs text-gray-600 mb-3"><?php echo nl2br(htmlspecialchars($ticket['message'])); ?></p>
                                        
                                        <?php if(!empty($ticket['admin_reply'])): ?>
                                        <div class="bg-teal-50 border border-teal-100 p-3 rounded-lg relative mt-2">
                                            <p class="text-[10px] font-bold text-teal-800 uppercase tracking-wider mb-1"><i class="fas fa-user-shield mr-1"></i> Admin Reply</p>
                                            <p class="text-xs text-teal-900"><?php echo nl2br(htmlspecialchars($ticket['admin_reply'])); ?></p>
                                        </div>
                                        <?php else: ?>
                                        <p class="text-xs text-gray-400 italic">Waiting for admin reply...</p>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4 pr-6 text-right align-top">
                                        <?php 
                                            $statusClass = 'bg-gray-100 text-gray-700';
                                            if($ticket['status'] == 'Open') $statusClass = 'bg-rose-100 text-rose-700';
                                            elseif($ticket['status'] == 'Pending') $statusClass = 'bg-yellow-100 text-yellow-700';
                                            elseif($ticket['status'] == 'Resolved' || $ticket['status'] == 'Closed') $statusClass = 'bg-emerald-100 text-emerald-700';
                                        ?>
                                        <span class="px-3 py-1 text-[10px] font-bold uppercase tracking-wider rounded-full <?php echo $statusClass; ?>">
                                            <?php echo htmlspecialchars($ticket['status']); ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; else: ?>
                                    <tr>
                                        <td colspan="3" class="p-12 text-center text-gray-500">
                                            <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-300 text-2xl border border-gray-100">
                                                <i class="fas fa-life-ring"></i>
                                            </div>
                                            <p class="text-lg font-medium">You haven't raised any tickets yet.</p>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </main>
        </div>
    </div>

    <div x-show="ticketModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4" style="display:none;">
        <div @click.away="ticketModal = false" x-transition.scale.origin.top class="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col border border-gray-100">
            <div class="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50 flex-shrink-0">
                <h3 class="font-bold text-gray-900 text-lg flex items-center">
                    <i class="fas fa-life-ring text-teal-600 mr-2"></i> Raise New Ticket
                </h3>
                <button @click="ticketModal = false" class="text-gray-400 hover:text-rose-500 transition-colors"><i class="fas fa-times text-xl"></i></button>
            </div>
            
            <div class="p-6">
                <form method="POST" class="space-y-4">
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-1">Subject <span class="text-rose-500">*</span></label>
                        <input type="text" name="subject" required placeholder="Brief description of the issue" class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-teal-500 transition-all">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-1">Detailed Message <span class="text-rose-500">*</span></label>
                        <textarea name="message" rows="4" required placeholder="Please explain the issue clearly..." class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-teal-500 transition-all resize-none"></textarea>
                    </div>
                    
                    <div class="pt-4 flex gap-3">
                        <button type="button" @click="ticketModal = false" class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold py-3.5 rounded-xl transition-colors">Cancel</button>
                        <button type="submit" name="create_ticket" class="flex-[2] bg-teal-600 hover:bg-teal-700 text-white font-bold py-3.5 rounded-xl shadow-md transition-colors flex items-center justify-center">
                            <i class="fas fa-paper-plane mr-2"></i> Submit Ticket
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</body>
</html>