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

// Redirect to login if not logged in
if (!isLoggedIn()) {
    redirect('login.php');
}

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

// PRG Flash Messages Setup
$success_msg = '';
$error_msg = '';
if (isset($_SESSION['flash_success'])) {
    $success_msg = $_SESSION['flash_success'];
    unset($_SESSION['flash_success']);
}
if (isset($_SESSION['flash_error'])) {
    $error_msg = $_SESSION['flash_error'];
    unset($_SESSION['flash_error']);
}

// Handle Ticket Submission
if (isset($_POST['submit_ticket'])) {
    $subject = sanitize($_POST['subject']);
    $message = sanitize($_POST['message']); 
    
    if (empty($subject) || empty($message)) {
        $_SESSION['flash_error'] = $lang->translate('fill_all_fields', 'সব ফিল্ড পূরণ করুন।');
        redirect('helpdesk.php#create');
    } else {
        $query = "INSERT INTO support_tickets (user_id, seller_id, subject, message, status) VALUES (?, 0, ?, ?, 'Open')";
        if ($db->insert($query, [$user_id, $subject, $message])) {
            $_SESSION['flash_success'] = $lang->translate('ticket_submitted', 'Ticket submitted successfully! We will get back to you soon.');
            redirect('helpdesk.php#all');
        } else {
            $_SESSION['flash_error'] = $lang->translate('error', 'একটি ত্রুটি ঘটেছে। আবার চেষ্টা করুন।');
            redirect('helpdesk.php#create');
        }
    }
}

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

// Fetch Unread Notifications for Header
$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, '/');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? 'uploads/profiles/' . $user['profile_pic'] : null;

// Determine dashboard link based on role
$dashboard_link = 'dashboard.php';
if ($user['user_type'] == 'seller') { $dashboard_link = 'seller/index.php'; } 
elseif ($user['user_type'] == 'admin') { $dashboard_link = 'admin/index.php'; }

// Fetch ALL active categories for the Sidebar Dropdown
$all_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$sidebar_subcats = [1 => [], 5 => []];
foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $sidebar_subcats[$__r['category_id']][] = $__r; }

// Fetch Tickets and format data for Alpine.js filtering
$raw_tickets = $db->select("SELECT * FROM support_tickets WHERE user_id = ? ORDER BY created_at DESC", [$user_id]);
$formatted_tickets = [];
foreach($raw_tickets as $t) {
    $t['display_date'] = date('d M Y, h:i A', strtotime($t['created_at']));
    $t['safe_message'] = nl2br(htmlspecialchars($t['message']));
    $t['safe_reply'] = !empty($t['admin_reply']) ? nl2br(htmlspecialchars($t['admin_reply'])) : null;
    $formatted_tickets[] = $t;
}
?>
<!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><?php echo $lang->translate('helpdesk', 'Helpdesk'); ?> - <?php echo htmlspecialchars($company_name); ?></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; scroll-behavior: smooth; } .font-poppins { font-family: 'Poppins', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; } .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } </style>
</head>
<?php
/* ===== Premium shared layout (Navy + Gold) ===== */
require_once __DIR__ . '/includes/theme.php';
$__cats = isset($all_categories) ? $all_categories : $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$__subs = isset($sidebar_subcats) ? $sidebar_subcats : null;
if ($__subs === null) { $__subs = [1=>[],5=>[]]; foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $__subs[$__r['category_id']][] = $__r; } }
$__menu = theme_user_menu($__subs, $__cats);
theme_open([
    'panel'  => 'user',
    'base'   => '',
    'title'  => 'Helpdesk',
    'active' => 'helpdesk',
    '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'  => 'currentTab: (window.location.hash ? window.location.hash.substring(1) : \'create\')',
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8 relative">

                <?php if ($success_msg): ?>
                <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl relative flex items-center shadow-sm" role="alert">
                    <i class="fas fa-check-circle text-xl mr-3"></i>
                    <span class="block sm:inline font-medium"><?php echo $success_msg; ?></span>
                </div>
                <?php endif; ?>

                <?php if ($error_msg): ?>
                <div class="mb-6 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl relative flex items-center shadow-sm" role="alert">
                    <i class="fas fa-exclamation-circle text-xl mr-3"></i>
                    <span class="block sm:inline font-medium"><?php echo $error_msg; ?></span>
                </div>
                <?php endif; ?>

                <div class="max-w-5xl mx-auto pb-20">

                    <div x-show="currentTab === 'create'" style="display:none;" x-transition.opacity>
                        
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800 mb-1">Create Support Ticket</h2>
                            <p class="text-gray-500 text-sm">Facing an issue with an order, wallet, or platform? Let us help you.</p>
                        </div>

                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden max-w-2xl">
                            <div class="p-6 md:p-8 border-t-4 border-indigo-600">
                                <form method="POST" class="space-y-5">
                                    <div>
                                        <label class="block text-sm font-bold text-gray-700 mb-2">Subject <span class="text-rose-500">*</span></label>
                                        <input type="text" name="subject" required placeholder="e.g., Payment deducted but not added to wallet" class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all font-medium text-gray-800">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-bold text-gray-700 mb-2">Issue Description <span class="text-rose-500">*</span></label>
                                        <textarea name="message" rows="5" required placeholder="Please describe your issue in detail..." class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all resize-none text-sm text-gray-800"></textarea>
                                    </div>
                                    <div class="pt-4">
                                        <button type="submit" name="submit_ticket" class="w-full sm:w-auto bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-8 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>

                    <div x-show="currentTab === 'all'" style="display:none;" x-transition.opacity>
                        
                        <div class="mb-6 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                            <div>
                                <h2 class="text-2xl font-bold text-gray-800 mb-1">Your Tickets</h2>
                                <p class="text-gray-500 text-sm">View your previously submitted tickets and admin replies.</p>
                            </div>
                            
                            <div class="flex items-center space-x-3 bg-white p-2 rounded-xl border border-gray-200 shadow-sm">
                                <div class="flex items-center px-2">
                                    <i class="fas fa-filter text-gray-400 mr-2 text-sm"></i>
                                    <select x-model="filterStatus" class="bg-transparent border-none text-sm font-bold text-gray-700 focus:outline-none cursor-pointer">
                                        <option value="All">All Status</option>
                                        <option value="Open">Open</option>
                                        <option value="Pending">Pending</option>
                                        <option value="Resolved">Resolved</option>
                                        <option value="Closed">Closed</option>
                                    </select>
                                </div>
                                <div class="w-px h-6 bg-gray-200"></div>
                                <div class="flex items-center px-2">
                                    <i class="fas fa-sort text-gray-400 mr-2 text-sm"></i>
                                    <select x-model="filterDate" class="bg-transparent border-none text-sm font-bold text-gray-700 focus:outline-none cursor-pointer">
                                        <option value="newest">Newest First</option>
                                        <option value="oldest">Oldest First</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <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-indigo-50/50 text-xs text-gray-500 uppercase tracking-wider border-b border-indigo-100">
                                            <th class="p-4 pl-6 font-semibold w-1/4 border-b border-gray-200">Ticket Info</th>
                                            <th class="p-4 font-semibold w-1/2 border-b border-gray-200">Message & Admin Reply</th>
                                            <th class="p-4 pr-6 font-semibold text-right w-1/4 border-b border-gray-200">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-gray-50">
                                        <template x-if="filteredTickets.length > 0">
                                            <template x-for="t in filteredTickets" :key="t.id">
                                                <tr class="hover:bg-gray-50 transition-colors">
                                                    <td class="p-4 pl-6 align-top">
                                                        <p class="font-bold text-gray-800" x-text="'#TKT-' + String(t.id).padStart(5, '0')"></p>
                                                        <p class="text-xs text-gray-500 mt-1" x-text="t.display_date"></p>
                                                    </td>
                                                    <td class="p-4 align-top">
                                                        <p class="font-bold text-sm text-gray-800 mb-1" x-text="t.subject"></p>
                                                        <p class="text-xs text-gray-600 mb-3" x-html="t.safe_message"></p>
                                                        
                                                        <template x-if="t.safe_reply">
                                                            <div class="bg-indigo-50 border border-indigo-100 p-3 rounded-lg relative mt-2">
                                                                <p class="text-[10px] font-bold text-indigo-800 uppercase tracking-wider mb-1"><i class="fas fa-user-shield mr-1"></i> Admin Reply</p>
                                                                <p class="text-xs text-indigo-900" x-html="t.safe_reply"></p>
                                                            </div>
                                                        </template>
                                                        <template x-if="!t.safe_reply">
                                                            <p class="text-xs text-gray-400 italic">Waiting for admin reply...</p>
                                                        </template>
                                                    </td>
                                                    <td class="p-4 pr-6 text-right align-top">
                                                        <span class="px-3 py-1 text-[10px] font-bold uppercase tracking-wider rounded-full border"
                                                              :class="{
                                                                  'bg-rose-50 text-rose-700 border-rose-200': t.status === 'Open',
                                                                  'bg-yellow-50 text-yellow-700 border-yellow-200': t.status === 'Pending',
                                                                  'bg-emerald-50 text-emerald-700 border-emerald-200': t.status === 'Resolved' || t.status === 'Closed'
                                                              }" x-text="t.status">
                                                        </span>
                                                    </td>
                                                </tr>
                                            </template>
                                        </template>
                                        <template x-if="filteredTickets.length === 0">
                                            <tr>
                                                <td colspan="3" class="p-16 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-ticket-alt"></i>
                                                    </div>
                                                    <p class="text-lg font-medium">No tickets found matching your filter.</p>
                                                </td>
                                            </tr>
                                        </template>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                </div>

            </main>
        </div>
    </div>
</body>
</html>