<?php
session_start();
include 'db_config.php';
include 'functions.php';

$hire_id = isset($_GET['hire_id']) ? intval($_GET['hire_id']) : 0;
if(!$hire_id) die("Invalid Chat.");

// Fetch hire details to verify authorization
$stmt = $conn->prepare("SELECT ch.*, c.full_name as customer_name, ed.full_name as worker_name 
                        FROM customer_hires ch 
                        JOIN customers c ON ch.customer_id = c.id 
                        JOIN employee_details ed ON ch.employee_nic = ed.employee_nic 
                        WHERE ch.id = ?");
$stmt->bind_param("i", $hire_id);
$stmt->execute();
$hire = $stmt->get_result()->fetch_assoc();
$stmt->close();

if(!$hire) die("Chat not found.");

// Authentication check
$is_customer = false;
$is_worker = false;

if(isset($_SESSION['role'])) {
    if($_SESSION['role'] === 'customer' && $_SESSION['customer_id'] == $hire['customer_id']) {
        $is_customer = true;
        $sender_type = 'customer';
        $my_name = $hire['customer_name'];
        $other_name = $hire['worker_name'];
    } elseif($_SESSION['role'] === 'employee' && $_SESSION['user_id'] == $hire['employee_nic']) {
        $is_worker = true;
        $sender_type = 'worker';
        $my_name = $hire['worker_name'];
        $other_name = $hire['customer_name'];
    }
}

if(!$is_customer && !$is_worker) {
    die("Access denied. You must be involved in this hire to chat.");
}

// Handle sending message
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['message'])) {
    $msg_text = sanitize_input($_POST['message']);
    if(!empty($msg_text)) {
        $stmt_send = $conn->prepare("INSERT INTO messages (hire_id, sender_type, message) VALUES (?, ?, ?)");
        $stmt_send->bind_param("iss", $hire_id, $sender_type, $msg_text);
        $stmt_send->execute();
        $stmt_send->close();
        
        // Mark as read for the sender? No, but let's refresh.
        header("Location: chat.php?hire_id=$hire_id");
        exit();
    }
}

// Fetch message history
$stmt_msg = $conn->prepare("SELECT * FROM messages WHERE hire_id = ? ORDER BY created_at ASC");
$stmt_msg->bind_param("i", $hire_id);
$stmt_msg->execute();
$messages = $stmt_msg->get_result();
$stmt_msg->close();

// Mark messages from the OTHER party as read
$other_type = ($sender_type == 'customer') ? 'worker' : 'customer';
$stmt_upd = $conn->prepare("UPDATE messages SET is_read = 1 WHERE hire_id = ? AND sender_type = ? AND is_read = 0");
$stmt_upd->bind_param("is", $hire_id, $other_type);
$stmt_upd->execute();
$stmt_upd->close();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat with <?=$other_name?> | Work For Sri Lanka</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        body { font-family: 'Inter', sans-serif; }
        .glass-panel {
            background: rgba(30, 41, 59, 0.4);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        .message-bubble {
            max-width: 80%;
            word-wrap: break-word;
        }
        .chat-container {
            height: calc(100vh - 200px);
            min-height: 400px;
        }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: rgba(71, 85, 105, 0.4); border-radius: 10px; }
    </style>
</head>
<body class="bg-slate-950 min-h-screen text-slate-200 selection:bg-indigo-500 selection:text-white">
    
    <!-- Header -->
    <nav class="bg-slate-900 border-b border-slate-800 sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16 items-center">
                <div class="flex items-center gap-4">
                     <button onclick="history.back()" class="p-2 hover:bg-slate-800 rounded-lg text-slate-400 hover:text-white transition">
                        <i data-lucide="arrow-left" class="w-5 h-5"></i>
                     </button>
                     <div>
                         <h1 class="text-sm font-bold text-white"><?=$other_name?></h1>
                         <p class="text-[10px] text-indigo-400 font-bold uppercase tracking-widest">Hire Request #<?=$hire_id?></p>
                     </div>
                </div>
                <div class="flex items-center gap-2">
                    <span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
                    <span class="text-xs font-medium text-slate-400">Online</span>
                </div>
            </div>
        </div>
    </nav>

    <div class="max-w-4xl mx-auto px-4 py-6">
        <div class="glass-panel rounded-3xl overflow-hidden flex flex-col shadow-2xl">
            <!-- Messages Display -->
            <div id="messageDisplay" class="chat-container overflow-y-auto p-6 space-y-4">
                <?php if($messages->num_rows == 0): ?>
                    <div class="h-full flex flex-col items-center justify-center text-slate-600 space-y-4">
                        <div class="w-16 h-16 rounded-3xl bg-slate-900/50 flex items-center justify-center">
                             <i data-lucide="message-square" class="w-8 h-8"></i>
                        </div>
                        <p class="text-sm">Start your conversation about this hire.</p>
                    </div>
                <?php else: ?>
                    <?php while($m = $messages->fetch_assoc()): 
                        $is_me = ($m['sender_type'] == $sender_type);
                    ?>
                        <div class="flex <?=$is_me ? 'justify-end' : 'justify-start'?>">
                            <div class="message-bubble group">
                                <div class="p-4 rounded-2xl shadow-sm <?=$is_me ? 'bg-indigo-600 text-white rounded-br-none' : 'bg-slate-800 text-slate-200 rounded-bl-none'?>">
                                    <p class="text-sm leading-relaxed"><?=$m['message']?></p>
                                </div>
                                <div class="flex items-center gap-2 mt-1 px-1 <?=$is_me ? 'justify-end text-right' : 'justify-start'?>">
                                    <span class="text-[10px] text-slate-500"><?=date('h:i A', strtotime($m['created_at']))?></span>
                                    <?php if($is_me): ?>
                                        <i data-lucide="check-check" class="w-3 h-3 <?=$m['is_read'] ? 'text-emerald-400' : 'text-slate-600'?>"></i>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php endif; ?>
            </div>

            <!-- Message Input -->
            <div class="p-4 bg-slate-900/80 border-t border-slate-800">
                <form method="post" id="chatForm" class="flex items-center gap-4">
                    <div class="relative flex-1">
                        <input type="text" name="message" id="msgInput" required placeholder="Type your message here..." class="w-full bg-slate-800/50 border border-slate-700 focus:border-indigo-500 rounded-2xl py-4 px-6 text-sm outline-none transition-all placeholder:text-slate-600 shadow-inner">
                    </div>
                    <button type="submit" class="bg-indigo-600 hover:bg-indigo-500 text-white p-4 rounded-2xl transition shadow-lg shadow-indigo-600/20 active:scale-95 flex items-center justify-center">
                        <i data-lucide="send" class="w-5 h-5"></i>
                    </button>
                </form>
            </div>
        </div>
    </div>

    <script>
        lucide.createIcons();
        
        const display = document.getElementById('messageDisplay');
        const msgInput = document.getElementById('msgInput');
        
        // Scroll to bottom
        function scrollToBottom() {
            display.scrollTop = display.scrollHeight;
        }
        scrollToBottom();

        // Send message with AJAX
        document.getElementById('chatForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const message = msgInput.value.trim();
            if(!message) return;
            
            const formData = new FormData();
            formData.append('message', message);
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            }).then(() => {
                msgInput.value = '';
                refreshChat();
            });
        });

        // Function to refresh chat
        function refreshChat() {
            const isNearBottom = display.scrollHeight - display.scrollTop - display.clientHeight < 100;
            
            fetch('get_messages.php?hire_id=<?=$hire_id?>')
                .then(r => r.text())
                .then(html => {
                    display.innerHTML = html;
                    if(isNearBottom) scrollToBottom();
                });
        }

        // Auto-refresh every 3 seconds
        setInterval(refreshChat, 3000);
    </script>
</body>
</html>
