<?php
session_start();
$db_path = file_exists('includes/db.php') ? 'includes/db.php' : '../includes/db.php';
if (file_exists($db_path)) {
    require $db_path;
} else {
    die("Database file not found.");
}

// Check Login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

// 1. Fetch Settings
$settings = $conn->query("SELECT * FROM settings WHERE id=1")->fetch_assoc();
$primary = $settings['theme_primary'] ?? '#003333';

// --- HANDLE FORM SUBMISSIONS ---

// A. Create New Ticket
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_ticket'])) {
    $subject = $conn->real_escape_string($_POST['subject']);
    $message = $conn->real_escape_string($_POST['message']);
    
    $sql_ticket = "INSERT INTO support_tickets (user_id, subject, status, last_reply_at) VALUES ($user_id, '$subject', 'open', NOW())";
    if ($conn->query($sql_ticket)) {
        $ticket_id = $conn->insert_id;
        $sql_msg = "INSERT INTO support_messages (ticket_id, sender_id, message, created_at) VALUES ($ticket_id, $user_id, '$message', NOW())";
        $conn->query($sql_msg);
        header("Location: support_chat.php?ticket_id=$ticket_id");
        exit();
    }
}

// B. Send Reply & Upload
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_reply'])) {
    $t_id = intval($_POST['ticket_id']);
    $msg = $conn->real_escape_string($_POST['message']);
    $attachment = NULL;

    // Handle File Upload
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
        $file_name = $_FILES['attachment']['name'];
        $file_size = $_FILES['attachment']['size'];
        $file_tmp = $_FILES['attachment']['tmp_name'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'mp4', 'mov', 'webm'];
        
        // Max 30MB (30 * 1024 * 1024)
        if ($file_size <= 31457280 && in_array($file_ext, $allowed)) {
            $upload_dir = '../assets/uploads/support/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            $new_name = uniqid() . '.' . $file_ext;
            if (move_uploaded_file($file_tmp, $upload_dir . $new_name)) {
                $attachment = 'assets/uploads/support/' . $new_name;
            }
        }
    }
    
    // Check if ticket belongs to user
    $check = $conn->query("SELECT id FROM support_tickets WHERE id=$t_id AND user_id=$user_id");
    if ($check->num_rows > 0 && (!empty($msg) || $attachment)) {
        $attach_sql = $attachment ? "'$attachment'" : "NULL";
        $conn->query("INSERT INTO support_messages (ticket_id, sender_id, message, attachment, created_at) VALUES ($t_id, $user_id, '$msg', $attach_sql, NOW())");
        $conn->query("UPDATE support_tickets SET last_reply_at=NOW(), status='open' WHERE id=$t_id");
        header("Location: support_chat.php?ticket_id=$t_id");
        exit();
    }
}

// --- VIEW LOGIC ---
$active_ticket_id = isset($_GET['ticket_id']) ? intval($_GET['ticket_id']) : 0;
$view_mode = $active_ticket_id > 0 ? 'chat' : 'list';
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>কাস্টমার সার্ভিস</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        body { font-family: 'Segoe UI', sans-serif; background-color: #f0f2f5; height: 100vh; display: flex; flex-direction: column; }
        .header-bg { background-color: <?php echo $primary; ?>; color: white; }
        
        .msg-user { background-color: #d9fdd3; align-self: flex-end; border-radius: 10px 0 10px 10px; }
        .msg-support { background-color: #ffffff; align-self: flex-start; border-radius: 0 10px 10px 10px; }
        
        /* Modal Animation */
        .modal-enter { animation: fadeUp 0.3s ease-out; }
        @keyframes fadeUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
    </style>
</head>
<body>

    <header class="header-bg flex justify-between items-center px-4 py-3 shadow-md sticky top-0 z-50">
        <div class="flex items-center gap-3">
            <button onclick="<?php echo $view_mode=='chat' ? "window.location.href='support_chat.php'" : "window.location.href='account.php'"; ?>" class="text-white text-xl">
                <i class="fas fa-chevron-left"></i>
            </button>
            <h1 class="text-lg font-bold">
                <?php echo $view_mode == 'chat' ? 'কথপোকথন' : 'কাস্টমার সার্ভিস'; ?>
            </h1>
        </div>
        <?php if($view_mode == 'list'): ?>
        <button onclick="document.getElementById('newTicketModal').classList.remove('hidden')" class="bg-white/20 p-2 rounded-full text-sm font-bold">
            <i class="fas fa-plus"></i> নতুন
        </button>
        <?php endif; ?>
    </header>

    <div class="flex-1 overflow-y-auto relative bg-[#e5ddd5]" style="background-image: url('https://user-images.githubusercontent.com/15075759/28719144-86dc0f70-73b1-11e7-911d-60d70fcded21.png');">

        <?php if ($view_mode == 'list'): ?>
            <div class="p-4 space-y-3 bg-[#f0f2f5] h-full">
                <?php 
                $tickets = $conn->query("SELECT * FROM support_tickets WHERE user_id=$user_id ORDER BY last_reply_at DESC");
                if ($tickets->num_rows > 0): 
                    while($t = $tickets->fetch_assoc()): 
                        $status_color = $t['status']=='open' ? 'text-green-600 bg-green-100' : 'text-gray-500 bg-gray-200';
                ?>
                <a href="?ticket_id=<?php echo $t['id']; ?>" class="block bg-white p-4 rounded-xl shadow-sm border border-gray-100 hover:bg-gray-50 transition">
                    <div class="flex justify-between items-start mb-1">
                        <h3 class="font-bold text-gray-800 text-sm truncate w-3/4"><?php echo htmlspecialchars($t['subject']); ?></h3>
                        <span class="text-[10px] <?php echo $status_color; ?> px-2 py-0.5 rounded-full font-bold uppercase"><?php echo $t['status']; ?></span>
                    </div>
                    <div class="flex justify-between items-center text-xs text-gray-500 mt-2">
                        <span>Ticket #<?php echo $t['id']; ?></span>
                        <span><?php echo date('d M, h:i A', strtotime($t['last_reply_at'])); ?></span>
                    </div>
                </a>
                <?php endwhile; 
                else: ?>
                    <div class="flex flex-col items-center justify-center mt-20 text-gray-400">
                        <i class="far fa-comments text-5xl mb-3 opacity-30"></i>
                        <p>কোন টিকিট নেই</p>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>


        <?php if ($view_mode == 'chat'): 
            $msgs = $conn->query("SELECT * FROM support_messages WHERE ticket_id=$active_ticket_id ORDER BY created_at ASC");
            $ticket_info = $conn->query("SELECT subject, status FROM support_tickets WHERE id=$active_ticket_id")->fetch_assoc();
        ?>
            <div class="flex flex-col p-4 space-y-3 pb-24" id="chatContainer">
                <div class="text-center my-2 sticky top-0 z-10">
                    <span class="bg-gray-200/90 text-gray-600 text-[10px] px-3 py-1 rounded-full shadow-sm backdrop-blur">
                        বিষয়: <?php echo htmlspecialchars($ticket_info['subject']); ?>
                    </span>
                </div>

                <?php while($m = $msgs->fetch_assoc()): 
                    $is_me = ($m['sender_id'] == $user_id);
                ?>
                <div class="flex flex-col max-w-[80%] <?php echo $is_me ? 'msg-user' : 'msg-support'; ?> p-2 shadow-sm relative">
                    
                    <?php if(!empty($m['attachment'])): 
                        $ext = pathinfo($m['attachment'], PATHINFO_EXTENSION);
                        if(in_array($ext, ['jpg','jpeg','png','gif'])): ?>
                            <a href="../<?php echo $m['attachment']; ?>" target="_blank">
                                <img src="../<?php echo $m['attachment']; ?>" class="rounded-lg mb-1 max-h-48 object-cover w-full">
                            </a>
                        <?php elseif(in_array($ext, ['mp4','webm'])): ?>
                            <video src="../<?php echo $m['attachment']; ?>" controls class="rounded-lg mb-1 max-h-48 w-full"></video>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php if(!empty($m['message'])): ?>
                        <p class="text-sm text-gray-800 leading-snug px-1"><?php echo nl2br(htmlspecialchars($m['message'])); ?></p>
                    <?php endif; ?>
                    
                    <span class="text-[9px] text-gray-400 mt-1 block text-right px-1">
                        <?php echo date('h:i A', strtotime($m['created_at'])); ?>
                        <?php if($is_me): ?> <i class="fas fa-check-double text-blue-500 ml-1"></i> <?php endif; ?>
                    </span>
                </div>
                <?php endwhile; ?>
            </div>

            <?php if($ticket_info['status'] != 'closed'): ?>
            <div class="fixed bottom-0 left-0 w-full bg-white px-2 py-2 border-t border-gray-200 z-50">
                
                <div id="filePreview" class="hidden absolute -top-12 left-4 bg-gray-800 text-white text-xs px-3 py-2 rounded-lg shadow-lg flex items-center gap-2">
                    <i class="fas fa-file-image"></i> 
                    <span id="fileName" class="truncate max-w-[150px]">file.jpg</span>
                    <button onclick="clearFile()" class="text-red-400 hover:text-red-300 ml-2"><i class="fas fa-times"></i></button>
                </div>

                <form method="POST" enctype="multipart/form-data" class="flex items-center gap-2">
                    <input type="hidden" name="ticket_id" value="<?php echo $active_ticket_id; ?>">
                    <input type="hidden" name="send_reply" value="1">
                    
                    <input type="file" name="attachment" id="fileInput" class="hidden" accept="image/*,video/*" onchange="handleFileSelect(this)">
                    <button type="button" onclick="document.getElementById('fileInput').click()" class="text-gray-500 text-xl px-2 hover:text-gray-700 transition">
                        <i class="fas fa-paperclip"></i>
                    </button>
                    
                    <input type="text" name="message" id="msgInput" placeholder="মেসেজ লিখুন..." 
                           class="flex-1 bg-gray-100 border-none rounded-full px-4 py-2.5 text-sm focus:ring-2 focus:ring-green-500 outline-none">
                    
                    <button type="submit" class="bg-[#005c4b] text-white w-10 h-10 rounded-full flex items-center justify-center shadow-md active:scale-95 transition">
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </form>
            </div>
            <?php endif; ?>

            <script>
                // Auto Scroll
                const container = document.getElementById('chatContainer');
                container.scrollTop = container.scrollHeight;

                // File Handling
                function handleFileSelect(input) {
                    const file = input.files[0];
                    if (file) {
                        if (file.size > 30 * 1024 * 1024) { // 30MB
                            alert("ফাইল সাইজ ৩০ মেগাবাইটের বেশি হতে পারবে না।");
                            input.value = "";
                        } else {
                            document.getElementById('filePreview').classList.remove('hidden');
                            document.getElementById('fileName').innerText = file.name;
                        }
                    }
                }

                function clearFile() {
                    document.getElementById('fileInput').value = "";
                    document.getElementById('filePreview').classList.add('hidden');
                }
            </script>
        <?php endif; ?>

    </div>

    <div id="newTicketModal" class="fixed inset-0 bg-black/50 z-[60] hidden flex items-center justify-center p-4">
        <div class="bg-white w-full max-w-sm rounded-2xl p-5 modal-enter relative">
            <button onclick="document.getElementById('newTicketModal').classList.add('hidden')" class="absolute top-3 right-3 text-gray-400 text-xl">&times;</button>
            <h3 class="text-lg font-bold text-gray-800 mb-4">নতুন টিকিট খুলুন</h3>
            <form method="POST">
                <input type="hidden" name="create_ticket" value="1">
                <div class="mb-3">
                    <label class="block text-xs font-bold text-gray-500 mb-1">বিষয়</label>
                    <select name="subject" class="w-full bg-gray-50 border rounded-lg p-2.5 text-sm outline-none">
                        <option>ডিপোজিট সমস্যা</option>
                        <option>উত্তোলন সমস্যা</option>
                        <option>গেম সমস্যা</option>
                        <option>অন্যান্য</option>
                    </select>
                </div>
                <div class="mb-4">
                    <textarea name="message" rows="4" required class="w-full bg-gray-50 border rounded-lg p-3 text-sm outline-none" placeholder="বিস্তারিত..."></textarea>
                </div>
                <button type="submit" class="w-full bg-[#005c4b] text-white font-bold py-3 rounded-xl shadow-lg">জমা দিন</button>
            </form>
        </div>
    </div>

</body>
</html>