<?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;

if(isset($_POST['reply_ticket'])) {
    $ticket_id = intval($_POST['ticket_id']);
    $status = sanitize($_POST['status']);
    $reply = sanitize($_POST['seller_reply']);
    
    $db->insert("UPDATE support_tickets SET status = ?, admin_reply = ? WHERE id = ? AND seller_id = ?", [$status, $reply, $ticket_id, $user_id]);
    $_SESSION['flash_success'] = "Reply sent and status updated successfully!";
    redirect('helpdesk.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);

$tickets = $db->select("SELECT st.*, u.name as buyer_name, u.mobile as buyer_mobile FROM support_tickets st JOIN users u ON st.user_id = u.id WHERE st.seller_id = ? ORDER BY st.created_at DESC", [$user_id]);

$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$raw_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($raw_logo, 'http') === 0) ? $raw_logo : '../' . ltrim($raw_logo, '/');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;
?>
<!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>Customer Support - <?php echo $company_name; ?> 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=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; } .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: 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'  => 'Admin Support',
    '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'  => 'replyModal: false, activeTicket: {}',
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8 relative">
                
                <div class="mb-6 flex flex-col md:flex-row md:justify-between md:items-center">
                    <div>
                        <h2 class="text-2xl font-bold text-gray-800 mb-1">Customer Support</h2>
                        <p class="text-gray-500 text-sm">Read and reply to support tickets raised by your customers.</p>
                    </div>
                </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-lg 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 $_SESSION['flash_success']; unset($_SESSION['flash_success']); ?></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 uppercase text-gray-500 tracking-wider border-b border-gray-100">
                                    <th class="p-4 pl-6 font-semibold">Subject</th>
                                    <th class="p-4 font-semibold">Buyer Details</th>
                                    <th class="p-4 font-semibold">Date</th>
                                    <th class="p-4 font-semibold">Status</th>
                                    <th class="p-4 pr-6 font-semibold text-right">Action</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-50">
                                <?php if(!empty($tickets)): ?>
                                    <?php foreach($tickets as $tkt): ?>
                                    <tr class="hover:bg-gray-50 transition">
                                        <td class="p-4 pl-6">
                                            <p class="font-bold text-gray-800 text-sm mb-1"><?php echo htmlspecialchars($tkt['subject']); ?></p>
                                            <p class="text-xs text-gray-400 font-mono">#TKT<?php echo str_pad($tkt['id'], 5, '0', STR_PAD_LEFT); ?></p>
                                        </td>
                                        <td class="p-4">
                                            <p class="font-bold text-gray-800 text-sm"><?php echo htmlspecialchars($tkt['buyer_name']); ?></p>
                                            <p class="text-xs text-gray-500"><i class="fas fa-phone mr-1"></i><?php echo htmlspecialchars($tkt['buyer_mobile']); ?></p>
                                        </td>
                                        <td class="p-4 text-gray-500 text-xs whitespace-nowrap">
                                            <?php echo date('d M Y', strtotime($tkt['created_at'])); ?><br>
                                            <span class="text-[10px]"><?php echo date('h:i A', strtotime($tkt['created_at'])); ?></span>
                                        </td>
                                        <td class="p-4">
                                            <span class="px-2 py-1 rounded text-[10px] font-bold uppercase tracking-wider <?php echo $tkt['status']=='Open'?'bg-rose-100 text-rose-600':($tkt['status']=='Pending'?'bg-yellow-100 text-yellow-600':'bg-emerald-100 text-emerald-600'); ?>">
                                                <?php echo $tkt['status']; ?>
                                            </span>
                                        </td>
                                        <td class="p-4 pr-6 text-right">
                                            <button @click="activeTicket = {
                                                id: '<?php echo $tkt['id']; ?>',
                                                subject: '<?php echo addslashes(htmlspecialchars($tkt['subject'])); ?>',
                                                msg: '<?php echo preg_replace("/\r|\n/", "\\n", addslashes(htmlspecialchars($tkt['message']))); ?>',
                                                reply: '<?php echo preg_replace("/\r|\n/", "\\n", addslashes(htmlspecialchars($tkt['admin_reply'] ?? ''))); ?>',
                                                status: '<?php echo $tkt['status']; ?>'
                                            }; replyModal = true;" class="bg-teal-50 hover:bg-teal-100 text-teal-600 px-3 py-1.5 rounded-lg text-xs font-bold border border-teal-200 transition-colors">
                                                <i class="fas fa-reply mr-1"></i> View / Reply
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php 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-300 text-2xl border border-gray-100">
                                                <i class="fas fa-check-circle"></i>
                                            </div>
                                            <p class="text-lg font-medium">All clear! No support tickets found.</p>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

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

    <div x-show="replyModal" 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="replyModal = false" x-transition.scale.origin.top class="bg-white rounded-2xl shadow-2xl w-full max-w-lg overflow-hidden border border-gray-100">
            <div class="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-slate-50">
                <h3 class="font-bold text-lg text-gray-800">Reply to Customer</h3>
                <button @click="replyModal = false" class="text-gray-400 hover:text-rose-500 bg-white w-8 h-8 rounded-full border border-gray-200 shadow-sm flex items-center justify-center transition-colors"><i class="fas fa-times"></i></button>
            </div>
            <div class="p-6">
                
                <div class="mb-6 bg-slate-50 border border-slate-200 rounded-xl p-4">
                    <p class="font-bold text-slate-800 mb-2 border-b border-slate-200 pb-2" x-text="activeTicket.subject"></p>
                    <p x-text="activeTicket.msg" class="text-sm text-slate-700 whitespace-pre-wrap leading-relaxed"></p>
                </div>

                <form method="POST">
                    <input type="hidden" name="ticket_id" x-model="activeTicket.id">
                    
                    <div class="mb-4">
                        <label class="block text-sm font-bold text-gray-700 mb-2">Your Reply</label>
                        <textarea name="seller_reply" x-model="activeTicket.reply" rows="4" class="w-full px-4 py-3 bg-white border border-gray-300 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-teal-500 transition-all resize-none shadow-sm text-sm text-gray-800" placeholder="Type your response to the customer..."></textarea>
                    </div>

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

                    <button type="submit" name="reply_ticket" class="w-full bg-teal-600 hover:bg-teal-700 text-white font-bold py-3 px-6 rounded-xl shadow-md transition-colors flex items-center justify-center">
                        <i class="fas fa-paper-plane mr-2"></i> Send Reply
                    </button>
                </form>
            </div>
        </div>
    </div>
</body>
</html>