<?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 or NOT an admin
if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }

// RBAC Protection
if (!hasPermission('manage_tickets')) { die("Access Denied: You do not have permission to manage tickets."); }

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

// UI Permissions map for Sidebar
$can_users = hasPermission('manage_users');
$can_sellers = hasPermission('manage_sellers');
$can_staff = hasPermission('manage_staff_roles');
$can_services = hasPermission('manage_services');
$can_orders = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets = hasPermission('manage_tickets');
$can_settings = hasPermission('manage_settings');

// 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 UPDATES (REPLY & STATUS)
// ---------------------------------------------------------
if (isset($_POST['update_ticket'])) {
    $ticket_id = intval($_POST['ticket_id']);
    $status = sanitize($_POST['status']);
    $admin_reply = sanitize($_POST['admin_reply']);
    $return_tab = sanitize($_POST['return_tab'] ?? 'customer');

    $db->insert("UPDATE support_tickets SET status = ?, admin_reply = ? WHERE id = ?", [$status, $admin_reply, $ticket_id]);
    
    $_SESSION['flash_success'] = "Ticket updated successfully!";
    redirect('tickets.php#' . $return_tab);
}

// ---------------------------------------------------------
// HANDLE TICKET DELETION
// ---------------------------------------------------------
if (isset($_POST['delete_ticket'])) {
    $ticket_id = intval($_POST['ticket_id']);
    $return_tab = sanitize($_POST['return_tab'] ?? 'customer');
    
    $db->insert("DELETE FROM support_tickets WHERE id = ?", [$ticket_id]);
    
    $_SESSION['flash_success'] = "Ticket deleted successfully!";
    redirect('tickets.php#' . $return_tab);
}

// ---------------------------------------------------------
// FETCH TICKETS
// ---------------------------------------------------------
// Fetch Customer Tickets
$customer_tickets = $db->select("
    SELECT t.*, u.name as user_name, u.mobile as user_mobile 
    FROM support_tickets t 
    JOIN users u ON t.user_id = u.id 
    WHERE u.user_type = 'customer' 
    ORDER BY CASE WHEN t.status = 'Open' THEN 1 WHEN t.status = 'Pending' THEN 2 ELSE 3 END, t.id DESC
");

// Fetch Seller Tickets
$seller_tickets = $db->select("
    SELECT t.*, u.name as user_name, u.mobile as user_mobile, s.business_name 
    FROM support_tickets t 
    JOIN users u ON t.user_id = u.id 
    LEFT JOIN sellers s ON u.id = s.user_id 
    WHERE u.user_type = 'seller' 
    ORDER BY CASE WHEN t.status = 'Open' THEN 1 WHEN t.status = 'Pending' THEN 2 ELSE 3 END, t.id DESC
");

/* ---------------------------------------------------------------------------
   SIDEBAR ROLE VIEW  —  tickets.php?role=all|free|pro|seller|employee|admin
   ------------------------------------------------------------------------ */
require_once __DIR__ . '/includes/role_filter.php';
$wb_role      = wb_role();
$wb_role_tks  = [];
$wb_start_tab = 'customer';
if ($wb_role !== '') {
    $wb_start_tab = 'role_view';
    $cond = wb_role_sql($wb_role, 'u');
    try {
        $wb_role_tks = $db->select("
            SELECT t.*, u.name AS user_name, u.mobile AS user_mobile, u.user_type,
                   COALESCE(u.is_subscribed,0) AS is_subscribed
            FROM support_tickets t
            JOIN users u ON t.user_id = u.id
            WHERE $cond
            ORDER BY CASE WHEN t.status = 'Open' THEN 1 WHEN t.status = 'Pending' THEN 2 ELSE 3 END, t.id DESC
        ");
    } catch (\Throwable $e) { $wb_role_tks = []; }
}

$company_logo = getSetting('company_logo', '../assets/images/logo.png');

// Helper function for status colors
function getTicketStatusClass($status) {
    switch (strtolower($status)) {
        case 'open': return 'bg-rose-100 text-rose-700 border-rose-200';
        case 'pending': return 'bg-yellow-100 text-yellow-700 border-yellow-200';
        case 'resolved': return 'bg-blue-100 text-blue-700 border-blue-200';
        case 'closed': return 'bg-emerald-100 text-emerald-700 border-emerald-200';
        default: return 'bg-gray-100 text-gray-700 border-gray-200';
    }
}
?>
<!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>Support Tickets - Admin Panel</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=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; } </style>
</head>
<body class="bg-gray-50" x-data="{ 
    sidebarOpen: window.innerWidth >= 768,
    currentTab: window.location.hash ? window.location.hash.substring(1) : '<?php echo $wb_start_tab; ?>',
    ticketModal: false, activeTicket: {}
}" @hashchange.window="currentTab = window.location.hash.substring(1) || '<?php echo $wb_start_tab; ?>'">

    <div class="flex h-screen overflow-hidden">
        
        <?php include __DIR__ . '/includes/sidebar.php'; ?>
        <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
            <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 shadow-sm border-b border-gray-200 z-40 relative">
                <div class="flex items-center"><button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg"><i class="fas fa-bars text-xl"></i></button><h2 class="text-xl font-bold hidden md:block text-slate-800">Support Center</h2></div>
            </header>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">
                
                <?php if (!empty($success_msg)): ?>
                <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                    <i class="fas fa-check-circle mr-2"></i><span class="font-medium"><?php echo $success_msg; ?></span>
                </div>
                <?php endif; ?>

                <?php if (!empty($error_msg)): ?>
                <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">
                    <i class="fas fa-exclamation-circle mr-2"></i><span class="font-medium"><?php echo $error_msg; ?></span>
                </div>
                <?php endif; ?>

                <!-- ============ AUDIENCE (ROLE) VIEW — opened from the sidebar ============ -->
                <div x-show="currentTab === 'role_view'" style="display:none;" x-transition.opacity>
                    <div class="mb-6">
                        <h2 class="text-2xl font-extrabold text-gray-800">
                            <i class="fas <?php echo wb_role_icon($wb_role ?: 'all'); ?> text-emerald-600 mr-2"></i>
                            Helpdesk &mdash; <?php echo htmlspecialchars(wb_role_label($wb_role ?: 'all')); ?>
                        </h2>
                        <p class="text-gray-500 text-sm mt-1">Every ticket raised by this audience, newest and most urgent first.</p>
                    </div>

                    <?php echo wb_role_tabs($wb_role, 'tickets.php'); ?>

                    <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                        <div class="overflow-x-auto">
                            <table class="w-full text-sm">
                                <thead class="bg-slate-50 text-slate-500 text-[11px] uppercase tracking-wider">
                                    <tr>
                                        <th class="px-5 py-3 text-left font-bold">#</th>
                                        <th class="px-5 py-3 text-left font-bold">Member</th>
                                        <th class="px-5 py-3 text-left font-bold">Subject</th>
                                        <th class="px-5 py-3 text-left font-bold">Status</th>
                                        <th class="px-5 py-3 text-left font-bold">Raised</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-100">
                                <?php if (empty($wb_role_tks)): ?>
                                    <tr><td colspan="5" class="px-5 py-14 text-center text-slate-400">
                                        <i class="fas fa-inbox text-3xl mb-3 block text-slate-300"></i>No tickets from this audience.
                                    </td></tr>
                                <?php else: foreach ($wb_role_tks as $t): ?>
                                    <tr class="hover:bg-slate-50/70 transition-colors">
                                        <td class="px-5 py-3 font-mono text-xs text-slate-400">#<?php echo (int)$t['id']; ?></td>
                                        <td class="px-5 py-3">
                                            <p class="font-bold text-slate-800"><?php echo htmlspecialchars($t['user_name'] ?? '—'); ?></p>
                                            <p class="text-[11px] text-slate-400"><?php echo htmlspecialchars($t['user_mobile'] ?? ''); ?></p>
                                        </td>
                                        <td class="px-5 py-3 text-slate-600"><?php echo htmlspecialchars($t['subject'] ?? ($t['title'] ?? '—')); ?></td>
                                        <td class="px-5 py-3">
                                            <span class="px-2.5 py-1 rounded-full text-[10px] font-bold border <?php echo getTicketStatusClass($t['status'] ?? ''); ?>"><?php echo htmlspecialchars($t['status'] ?? ''); ?></span>
                                        </td>
                                        <td class="px-5 py-3 text-slate-500 text-xs whitespace-nowrap"><?php echo date('d M Y', strtotime($t['created_at'])); ?></td>
                                    </tr>
                                <?php endforeach; endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div x-show="currentTab === 'customer'" style="display:none;" x-transition.opacity>
                    <div class="mb-6">
                        <h2 class="text-2xl font-extrabold text-gray-800">Customer Support Tickets</h2>
                        <p class="text-gray-500 text-sm mt-1">Manage issues and inquiries raised by standard customers.</p>
                    </div>

                    <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                        <div class="overflow-x-auto min-h-[500px]">
                            <table class="w-full text-left">
                                <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wider border-b border-gray-100">
                                    <tr>
                                        <th class="p-4 pl-6 font-semibold">Ticket ID & Date</th>
                                        <th class="p-4 font-semibold">Customer Info</th>
                                        <th class="p-4 font-semibold">Subject / Issue</th>
                                        <th class="p-4 font-semibold text-center">Status</th>
                                        <th class="p-4 pr-6 font-semibold text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-50 text-sm">
                                    <?php if(!empty($customer_tickets)): foreach($customer_tickets as $tkt): ?>
                                    <tr class="hover:bg-gray-50 transition-colors">
                                        <td class="p-4 pl-6">
                                            <p class="font-bold text-gray-700">#TKT-<?php echo $tkt['id']; ?></p>
                                            <p class="text-[10px] text-gray-500 mt-1"><?php echo date('d M Y, h:i A', strtotime($tkt['created_at'])); ?></p>
                                        </td>
                                        <td class="p-4">
                                            <p class="font-bold text-indigo-700"><?php echo htmlspecialchars($tkt['user_name'] ?? 'Unknown'); ?></p>
                                            <p class="text-xs text-gray-500"><i class="fas fa-phone-alt mr-1 text-[10px]"></i><?php echo htmlspecialchars($tkt['user_mobile'] ?? ''); ?></p>
                                        </td>
                                        <td class="p-4">
                                            <p class="font-semibold text-gray-800 max-w-xs truncate" title="<?php echo htmlspecialchars($tkt['subject'] ?? ''); ?>"><?php echo htmlspecialchars($tkt['subject'] ?? ''); ?></p>
                                            <p class="text-xs text-gray-500 max-w-xs truncate mt-0.5" title="<?php echo htmlspecialchars($tkt['message'] ?? ''); ?>"><?php echo htmlspecialchars($tkt['message'] ?? ''); ?></p>
                                        </td>
                                        <td class="p-4 text-center">
                                            <span class="px-2 py-1 text-[10px] font-bold uppercase tracking-wider rounded border <?php echo getTicketStatusClass($tkt['status']); ?>">
                                                <?php echo htmlspecialchars($tkt['status']); ?>
                                            </span>
                                        </td>
                                        <td class="p-4 pr-6 text-right whitespace-nowrap">
                                            <button @click="activeTicket = <?php echo htmlspecialchars(json_encode($tkt)); ?>; activeTicket.return_tab = 'customer'; ticketModal = true;" class="w-8 h-8 rounded-lg bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors inline-flex items-center justify-center mr-1" title="View & Reply">
                                                <i class="fas fa-reply"></i>
                                            </button>
                                            <form method="POST" onsubmit="return confirm('Are you sure you want to delete this ticket?');" class="inline-block">
                                                <input type="hidden" name="return_tab" value="customer">
                                                <input type="hidden" name="ticket_id" value="<?php echo $tkt['id']; ?>">
                                                <button type="submit" name="delete_ticket" class="w-8 h-8 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-600 transition-colors inline-flex items-center justify-center" title="Delete Ticket">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; else: ?>
                                    <tr>
                                        <td colspan="5" 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-400 text-2xl border border-gray-100"><i class="fas fa-inbox"></i></div>
                                            <p class="text-lg font-medium">No customer tickets found.</p>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div x-show="currentTab === 'seller'" style="display:none;" x-transition.opacity>
                    <div class="mb-6">
                        <h2 class="text-2xl font-extrabold text-gray-800">Seller Support Tickets</h2>
                        <p class="text-gray-500 text-sm mt-1">Manage issues raised by your B2B partners and merchants.</p>
                    </div>

                    <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                        <div class="overflow-x-auto min-h-[500px]">
                            <table class="w-full text-left">
                                <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wider border-b border-gray-100">
                                    <tr>
                                        <th class="p-4 pl-6 font-semibold">Ticket ID & Date</th>
                                        <th class="p-4 font-semibold">B2B Partner Info</th>
                                        <th class="p-4 font-semibold">Subject / Issue</th>
                                        <th class="p-4 font-semibold text-center">Status</th>
                                        <th class="p-4 pr-6 font-semibold text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-50 text-sm">
                                    <?php if(!empty($seller_tickets)): foreach($seller_tickets as $tkt): ?>
                                    <tr class="hover:bg-gray-50 transition-colors">
                                        <td class="p-4 pl-6">
                                            <p class="font-bold text-gray-700">#TKT-<?php echo $tkt['id']; ?></p>
                                            <p class="text-[10px] text-gray-500 mt-1"><?php echo date('d M Y, h:i A', strtotime($tkt['created_at'])); ?></p>
                                        </td>
                                        <td class="p-4">
                                            <p class="font-bold text-teal-700"><?php echo htmlspecialchars($tkt['business_name'] ?? 'B2B Partner'); ?></p>
                                            <p class="text-xs text-gray-500"><i class="fas fa-user-tie mr-1 text-[10px]"></i><?php echo htmlspecialchars($tkt['user_name'] ?? ''); ?> | <?php echo htmlspecialchars($tkt['user_mobile'] ?? ''); ?></p>
                                        </td>
                                        <td class="p-4">
                                            <p class="font-semibold text-gray-800 max-w-xs truncate" title="<?php echo htmlspecialchars($tkt['subject'] ?? ''); ?>"><?php echo htmlspecialchars($tkt['subject'] ?? ''); ?></p>
                                            <p class="text-xs text-gray-500 max-w-xs truncate mt-0.5" title="<?php echo htmlspecialchars($tkt['message'] ?? ''); ?>"><?php echo htmlspecialchars($tkt['message'] ?? ''); ?></p>
                                        </td>
                                        <td class="p-4 text-center">
                                            <span class="px-2 py-1 text-[10px] font-bold uppercase tracking-wider rounded border <?php echo getTicketStatusClass($tkt['status']); ?>">
                                                <?php echo htmlspecialchars($tkt['status']); ?>
                                            </span>
                                        </td>
                                        <td class="p-4 pr-6 text-right whitespace-nowrap">
                                            <button @click="activeTicket = <?php echo htmlspecialchars(json_encode($tkt)); ?>; activeTicket.return_tab = 'seller'; ticketModal = true;" class="w-8 h-8 rounded-lg bg-teal-50 hover:bg-teal-100 text-teal-600 transition-colors inline-flex items-center justify-center mr-1" title="View & Reply">
                                                <i class="fas fa-reply"></i>
                                            </button>
                                            <form method="POST" onsubmit="return confirm('Are you sure you want to delete this ticket?');" class="inline-block">
                                                <input type="hidden" name="return_tab" value="seller">
                                                <input type="hidden" name="ticket_id" value="<?php echo $tkt['id']; ?>">
                                                <button type="submit" name="delete_ticket" class="w-8 h-8 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-600 transition-colors inline-flex items-center justify-center" title="Delete Ticket">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; else: ?>
                                    <tr>
                                        <td colspan="5" 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-400 text-2xl border border-gray-100"><i class="fas fa-inbox"></i></div>
                                            <p class="text-lg font-medium">No seller tickets found.</p>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

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

    <div x-show="ticketModal" class="fixed inset-0 z-50 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-2xl overflow-hidden flex flex-col max-h-[90vh]">
            <div class="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50">
                <h3 class="font-bold text-gray-900 text-lg">Ticket <span class="text-emerald-600 font-mono text-sm ml-1" x-text="'#TKT-' + activeTicket.id"></span></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 overflow-y-auto flex-1">
                <div class="mb-6 bg-gray-50 rounded-xl p-4 border border-gray-100 shadow-inner">
                    <div class="flex items-center justify-between mb-3 border-b border-gray-200 pb-3">
                        <div class="flex items-center">
                            <div class="w-10 h-10 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center font-bold text-lg mr-3 border border-emerald-200" x-text="activeTicket.user_name ? activeTicket.user_name.charAt(0).toUpperCase() : 'U'"></div>
                            <div>
                                <p class="font-bold text-gray-800 text-sm leading-tight" x-text="activeTicket.user_name"></p>
                                <p class="text-xs text-gray-500" x-text="activeTicket.user_mobile"></p>
                            </div>
                        </div>
                        <div class="text-right">
                            <span class="text-[10px] font-bold uppercase tracking-wider text-gray-400 block mb-1">Status</span>
                            <span class="px-2 py-1 text-[10px] font-bold uppercase rounded border bg-gray-100 text-gray-700" x-text="activeTicket.status"></span>
                        </div>
                    </div>
                    <div>
                        <h4 class="font-bold text-gray-800 mb-2" x-text="activeTicket.subject"></h4>
                        <p class="text-sm text-gray-600 whitespace-pre-wrap leading-relaxed" x-text="activeTicket.message"></p>
                    </div>
                </div>

                <form method="POST">
                    <input type="hidden" name="ticket_id" x-model="activeTicket.id">
                    <input type="hidden" name="return_tab" x-model="activeTicket.return_tab">
                    
                    <div class="mb-5">
                        <label class="block text-sm font-bold text-gray-700 mb-2">Admin Reply <span class="text-xs text-gray-400 font-normal ml-1">(Sent to user)</span></label>
                        <textarea name="admin_reply" x-model="activeTicket.admin_reply" rows="4" 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-emerald-500 transition-all resize-none shadow-sm text-sm text-gray-800" placeholder="Type your response here..."></textarea>
                    </div>

                    <div class="mb-6">
                        <label class="block text-sm font-bold text-gray-700 mb-2">Update Ticket Status</label>
                        <select name="status" x-model="activeTicket.status" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-500 transition-all shadow-sm text-sm font-semibold">
                            <option value="Open">Open (Action Required)</option>
                            <option value="Pending">Pending (Waiting on User)</option>
                            <option value="Resolved">Resolved (Issue Fixed)</option>
                            <option value="Closed">Closed</option>
                        </select>
                    </div>

                    <div class="flex justify-end pt-2">
                        <button type="submit" name="update_ticket" class="bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3 px-8 rounded-xl shadow-md transition-colors flex items-center">
                            <i class="fas fa-paper-plane mr-2"></i> Update & Reply
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</body>
</html>