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

$hire_id = isset($_GET['hire_id']) ? intval($_GET['hire_id']) : 0;
if(!$hire_id) exit();

$stmt = $conn->prepare("SELECT * FROM customer_hires WHERE id = ?");
$stmt->bind_param("i", $hire_id);
$stmt->execute();
$hire = $stmt->get_result()->fetch_assoc();

if(!$hire) exit();

// Auth Check
$is_customer = (isset($_SESSION['role']) && $_SESSION['role'] === 'customer' && $_SESSION['customer_id'] == $hire['customer_id']);
$is_worker = (isset($_SESSION['role']) && $_SESSION['role'] === 'employee' && $_SESSION['user_id'] == $hire['employee_nic']);

if(!$is_customer && !$is_worker) exit();

$sender_type = $is_customer ? 'customer' : 'worker';

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

// Mark messages from 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();

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; ?>
<script>lucide.createIcons();</script>
