<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
include 'db_config.php';
include 'functions.php';

$encrypted_id = isset($_GET['id']) ? sanitize_input($_GET['id']) : '';
$nic = decrypt_id($encrypted_id);

if (!$nic) {
    // If decryption fails, it might be an old direct link or invalid ID. 
    // We could try to see if it's a raw NIC just in case, or just fail.
    // For now, let's treat it as invalid to enforce the new rule.
    // But to be safe during transition, we could check if it looks like a NIC.
    if (strlen($encrypted_id) >= 10 && strlen($encrypted_id) <= 12) {
        $nic = $encrypted_id;
    } else {
        die("Invalid Worker ID.");
    }
}

// 1. Fetch worker first (don't filter by status yet)
$stmt = $conn->prepare("SELECT * FROM employee_details WHERE employee_nic = ?");
$stmt->bind_param("s", $nic);
$stmt->execute();
$worker = $stmt->get_result()->fetch_assoc();

if(!$worker) die("Worker not found.");

// 2. Check permissions if not approved
if ($worker['status'] !== 'Approved') {
    $can_view = false;
    if (isset($_SESSION['role']) && ($_SESSION['role'] === 'dme' || $_SESSION['role'] === 'admin')) {
        $can_view = true;
    }

    if (!$can_view) {
        die("Worker not found or not approved.");
    }
}

// Handle Actions
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_SESSION['customer_id'])) {
    $c_id = $_SESSION['customer_id'];
    
    if (isset($_POST['hire_worker'])) {
        $stmt = $conn->prepare("INSERT INTO customer_hires (customer_id, employee_nic, status) VALUES (?, ?, 'Pending')");
        $stmt->bind_param("is", $c_id, $nic);
        $stmt->execute();
        $hire_id = $stmt->insert_id;
        $stmt->close();

        // Add notification for the worker
        $p = $_SESSION['customer_phone'];
        $c_name = isset($_SESSION['customer_name']) ? $_SESSION['customer_name'] : $p;
        $msg = "A new customer ($c_name) has requested to hire you. Phone: $p";
        $stmt_notif = $conn->prepare("INSERT INTO worker_notifications (employee_nic, customer_id, hire_id, message) VALUES (?, ?, ?, ?)");
        $stmt_notif->bind_param("siis", $nic, $c_id, $hire_id, $msg);
        $stmt_notif->execute();
        $stmt_notif->close();

        $encrypted_nic = encrypt_id($nic);
        header("Location: worker_profile.php?id=$encrypted_nic");
        exit();
    }
    
    if (isset($_POST['complete_hire'])) {
        $stmt = $conn->prepare("UPDATE customer_hires SET status = 'Completed' WHERE customer_id = ? AND employee_nic = ? AND (status = 'Pending' OR status = 'In Progress')");
        $stmt->bind_param("is", $c_id, $nic);
        $stmt->execute();
        $stmt->close();
        $encrypted_nic = encrypt_id($nic);
        header("Location: worker_profile.php?id=$encrypted_nic");
        exit();
    }
    
    if (isset($_POST['submit_review'])) {
        $rating = intval($_POST['rating']);
        $comment = sanitize_input($_POST['comment']);
        $stmt = $conn->prepare("INSERT INTO customer_reviews (customer_id, employee_nic, rating, comment) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("isis", $c_id, $nic, $rating, $comment);
        $stmt->execute();
        $stmt->close();
        $encrypted_nic = encrypt_id($nic);
        header("Location: worker_profile.php?id=$encrypted_nic");
        exit();
    }
}

// Fetch Combined Reviews
$reviews_query = "
    (SELECT r.rating, r.comment, r.created_at, e.company_name as reviewer_name, 'Employer' as reviewer_type 
     FROM reviews r 
     JOIN employer_details e ON r.employer_id = e.user_id 
     WHERE r.employee_nic = '$nic')
    UNION ALL
    (SELECT cr.rating, cr.comment, cr.created_at, cr.customer_id as reviewer_name, 'Customer' as reviewer_type 
     FROM customer_reviews cr 
     WHERE cr.employee_nic = '$nic')
    ORDER BY created_at DESC
";
$reviews = $conn->query($reviews_query);

// Get Customer details for names if needed
$customers_res = $conn->query("SELECT id, phone FROM customers");
$customer_phones = [];
while($crow = $customers_res->fetch_assoc()) {
    $phone = $crow['phone'];
    $customer_phones[$crow['id']] = substr($phone, 0, 3) . '****' . substr($phone, -3);
}

$avg_rating_query = "
    SELECT AVG(all_ratings.rating) as avg FROM (
        SELECT rating FROM reviews WHERE employee_nic = '$nic'
        UNION ALL
        SELECT rating FROM customer_reviews WHERE employee_nic = '$nic'
    ) as all_ratings
";
$avg_rating_res = $conn->query($avg_rating_query);
$avg_rating = $avg_rating_res ? $avg_rating_res->fetch_assoc()['avg'] : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?=$worker['full_name']?> - Profile | 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);
        }
    </style>
</head>
<body class="bg-slate-950 min-h-screen text-slate-200 selection:bg-indigo-500 selection:text-white">
    <!-- Navbar -->
    <nav class="bg-slate-900/50 backdrop-blur-md 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">
                <a href="search.php" class="flex items-center text-slate-400 hover:text-white transition group gap-2">
                    <i data-lucide="arrow-left" class="w-5 h-5 group-hover:-translate-x-1 transition-transform"></i>
                    Back to Search
                </a>
                <div class="text-lg font-bold text-white hidden md:block">Worker Profile</div>
                <div class="w-20 hidden md:block"></div> <!-- Spacer for centering -->
            </div>
        </div>
    </nav>

    <div class="max-w-5xl mx-auto px-4 py-8">
        <!-- Profile Header -->
        <div class="glass-panel rounded-2xl p-6 md:p-8 mb-8 relative overflow-hidden">
            <div class="absolute top-0 left-0 w-full h-32 bg-gradient-to-r from-indigo-900/50 to-slate-900/50"></div>
            
            <div class="relative flex flex-col md:flex-row gap-6 md:gap-8 items-center md:items-end mt-12">
                <img src="uploads/profiles/<?=$worker['profile_pic'] ? $worker['profile_pic'] : 'default.png'?>" 
                     class="w-32 h-32 md:w-40 md:h-40 rounded-2xl border-4 border-slate-800 shadow-2xl object-cover bg-slate-700">
                
                <div class="flex-1 text-center md:text-left mb-2">
                    <h1 class="text-3xl md:text-4xl font-bold text-white mb-2"><?=$worker['full_name']?></h1>
                    <div class="flex flex-wrap gap-2 justify-center md:justify-start items-center text-indigo-400 font-medium text-lg">
                        <i data-lucide="briefcase" class="w-5 h-5"></i>
                        <?=$worker['job_category']?>
                    </div>
                </div>

                <div class="flex flex-col items-center md:items-end bg-slate-800/50 p-4 rounded-xl border border-slate-700/50">
                    <div class="flex items-center gap-1 text-amber-400 mb-1">
                        <i data-lucide="star" class="w-6 h-6 fill-current"></i>
                        <span class="text-2xl font-bold"><?=number_format($avg_rating, 1)?></span>
                    </div>
                    <span class="text-sm text-slate-400"><?= $reviews->num_rows ?> Reviews</span>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
            <!-- Sidebar Info -->
            <div class="space-y-6">
                <div class="glass-panel p-6 rounded-2xl">
                    <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
                        <i data-lucide="user" class="w-5 h-5 text-indigo-400"></i> Personal Info
                    </h3>
                    <div class="space-y-4 text-sm">
                        <div>
                            <span class="block text-slate-500 text-xs uppercase tracking-wider mb-1">Phone Number</span>
                            <?php if($worker['phone']): ?>
                                <button onclick="revealPhone(this, '<?=$worker['phone']?>')" class="flex items-center gap-2 group/phone bg-slate-800/50 hover:bg-indigo-600/20 px-3 py-2 rounded-lg border border-slate-700 hover:border-indigo-500/50 transition w-full text-left">
                                     <i data-lucide="eye" class="w-4 h-4 text-indigo-400 group-hover/phone:scale-110 transition"></i>
                                     <span class="text-slate-300 font-medium tracking-widest"><?= substr($worker['phone'], 0, 3) . '****' . substr($worker['phone'], -3) ?></span>
                                </button>
                                <p class="text-[9px] text-slate-500 mt-1 ml-1 uppercase font-bold tracking-widest">Click to reveal</p>
                            <?php else: ?>
                                 <span class="italic text-slate-600">Private</span>
                            <?php endif; ?>
                        </div>
                        <div>
                            <span class="block text-slate-500 text-xs uppercase tracking-wider">District</span>
                            <span class="text-slate-300"><?=$worker['district'] ? $worker['district'] : 'Not specified'?></span>
                        </div>
                        <div>
                            <span class="block text-slate-500 text-xs uppercase tracking-wider">Address</span>
                            <span class="text-slate-300"><?=$worker['address']?></span>
                        </div>
                    </div>
                </div>

                <?php if(isset($_SESSION['role']) && $_SESSION['role'] === 'customer'): ?>
                    <?php
                    $c_id = $_SESSION['customer_id'];
                    $hire_res = $conn->query("SELECT id, status FROM customer_hires WHERE customer_id = $c_id AND employee_nic = '$nic' ORDER BY created_at DESC LIMIT 1");
                    $hire = $hire_res->fetch_assoc();
                    $h_status = $hire ? $hire['status'] : null;
                    $h_id = $hire ? $hire['id'] : null;
                    
                    $has_rated = $conn->query("SELECT id FROM customer_reviews WHERE customer_id = $c_id AND employee_nic = '$nic'")->num_rows > 0;
                    ?>
                    
                    <div class="glass-panel p-6 rounded-2xl">
                        <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
                             <i data-lucide="check-circle" class="w-5 h-5 text-indigo-400"></i> Actions
                        </h3>
                        <div class="flex flex-col gap-4">
                            <?php if(!$h_status): ?>
                                <form method="post">
                                    <button type="submit" name="hire_worker" class="w-full py-4 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded-xl transition shadow-lg shadow-indigo-600/20 flex items-center justify-center gap-2">
                                        <i data-lucide="user-plus" class="w-5 h-5"></i> Hire This Worker
                                    </button>
                                </form>
                            <?php elseif($h_status == 'Pending'): ?>
                                <div class="p-4 bg-amber-500/10 border border-amber-500/20 rounded-xl text-amber-400 text-center font-medium">
                                    Hiring request sent. Waiting for worker to accept.
                                </div>
                            <?php elseif($h_status == 'In Progress'): ?>
                                <div class="space-y-3">
                                    <div class="p-4 bg-blue-500/10 border border-blue-500/20 rounded-xl text-blue-400 text-center font-medium text-sm">
                                        Hire Accepted! You can now chat.
                                    </div>
                                    <a href="chat.php?hire_id=<?=$h_id?>" class="w-full py-4 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded-xl transition shadow-lg shadow-indigo-600/20 flex items-center justify-center gap-2">
                                        <i data-lucide="message-square" class="w-5 h-5"></i> Chat with Worker
                                    </a>
                                    <form method="post">
                                        <button type="submit" name="complete_hire" class="w-full py-3 bg-slate-800 hover:bg-slate-700 text-white rounded-xl transition text-sm">Mark as Job Completed</button>
                                    </form>
                                </div>
                            <?php elseif($h_status == 'Completed' && !$has_rated): ?>
                                <div class="p-4 bg-emerald-500/10 border border-emerald-500/20 rounded-xl text-emerald-400 text-center font-medium mb-2 text-sm">
                                    Job completed! Rate your experience.
                                </div>
                                <form method="post" class="space-y-4">
                                    <div>
                                        <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1">Rating</label>
                                        <select name="rating" class="w-full bg-slate-800 border border-slate-700 text-white rounded-xl p-3 outline-none focus:border-indigo-500">
                                            <option value="5">5 Stars - Excellent</option>
                                            <option value="4">4 Stars - Very Good</option>
                                            <option value="3">3 Stars - Good</option>
                                            <option value="2">2 Stars - Fair</option>
                                            <option value="1">1 Star - Poor</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1">Comment</label>
                                        <textarea name="comment" required rows="2" class="w-full bg-slate-800 border border-slate-700 text-white rounded-xl p-3 outline-none focus:border-indigo-500 text-sm" placeholder="Review..."></textarea>
                                    </div>
                                    <button type="submit" name="submit_review" class="w-full py-3 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded-xl transition">
                                        Submit Rating
                                    </button>
                                </form>
                            <?php elseif($h_status == 'Completed' && $has_rated): ?>
                                 <div class="p-4 bg-indigo-500/10 border border-indigo-500/20 rounded-xl text-indigo-400 text-center font-medium text-sm">
                                    <i data-lucide="check" class="w-4 h-4 inline mr-1"></i> Job Completed & Reviewed.
                                </div>
                                <a href="chat.php?hire_id=<?=$h_id?>" class="w-full py-3 bg-slate-900 border border-slate-800 text-slate-400 hover:text-white rounded-xl transition text-sm flex items-center justify-center gap-2">
                                    <i data-lucide="message-square" class="w-4 h-4 text-indigo-400"></i> View Chat History
                                </a>
                            <?php elseif($h_status == 'Cancelled'): ?>
                                <div class="p-4 bg-red-500/10 border border-red-500/20 rounded-xl text-red-400 text-center font-medium">
                                    Request declined by worker.
                                </div>
                                <form method="post">
                                    <button type="submit" name="hire_worker" class="w-full py-4 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded-xl transition mt-4">New Hire Request</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php elseif(!isset($_SESSION['role']) || ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'dme' && $_SESSION['role'] !== 'employee' && $_SESSION['role'] !== 'employer')): ?>
                    <div class="glass-panel p-6 rounded-2xl text-center">
                        <p class="text-slate-400 text-sm mb-4">Login as a customer to hire or rate this worker.</p>
                        <a href="customer_login.php" class="relative inline-flex items-center justify-center p-0.5 mb-2 mr-2 overflow-hidden text-sm font-medium text-white rounded-lg group bg-gradient-to-br from-purple-600 to-blue-500 group-hover:from-purple-600 group-hover:to-blue-500 hover:text-white focus:ring-4 focus:outline-none focus:ring-blue-800 w-full transition-all duration-300">
                          <span class="relative px-5 py-2.5 transition-all ease-in duration-75 bg-slate-900 rounded-md group-hover:bg-opacity-0 w-full">
                              Customer Login
                          </span>
                        </a>
                    </div>
                <?php endif; ?>

                <?php if($worker['cv_file']): ?>
                <a href="uploads/cvs/<?=$worker['cv_file']?>" target="_blank" 
                   class="flex items-center justify-center w-full p-4 bg-indigo-600 hover:bg-indigo-500 text-white rounded-xl font-medium transition shadow-lg shadow-indigo-900/20 group">
                    <i data-lucide="file-text" class="w-5 h-5 mr-2 group-hover:scale-110 transition-transform"></i>
                    Download CV
                </a>
                <?php endif; ?>
            </div>

            <!-- Main Content -->
            <div class="md:col-span-2 space-y-8">
                <!-- Experience -->
                <div class="glass-panel p-6 rounded-2xl">
                    <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
                        <i data-lucide="award" class="w-5 h-5 text-indigo-400"></i> Qualification & Experience
                    </h3>
                    <div class="mb-6">
                        <span class="text-indigo-300 bg-indigo-500/10 px-3 py-1 rounded-full text-sm font-medium border border-indigo-500/20">
                            <?=$worker['qualification']?>
                        </span>
                    </div>
                    <div class="prose prose-invert prose-slate max-w-none">
                        <p class="whitespace-pre-line text-slate-300 leading-relaxed">
                            <?=$worker['experience'] ? $worker['experience'] : 'No experience details provided.'?>
                        </p>
                    </div>
                </div>

                <!-- Reviews -->
                <div>
                    <h3 class="text-xl font-bold text-white mb-6 flex items-center gap-2">
                        <i data-lucide="message-square" class="w-6 h-6 text-indigo-400"></i> 
                        Customer Reviews
                    </h3>
                    
                    <?php if($reviews->num_rows > 0): ?>
                        <div class="space-y-4">
                        <?php while($r = $reviews->fetch_assoc()): 
                            $name = $r['reviewer_name'];
                            if ($r['reviewer_type'] === 'Customer' && isset($customer_phones[$name])) {
                                $name = "Customer (" . $customer_phones[$name] . ")";
                            }
                        ?>
                            <div class="glass-panel p-5 rounded-xl border-l-4 <?= $r['reviewer_type'] === 'Customer' ? 'border-l-indigo-500' : 'border-l-emerald-500' ?>">
                                <div class="flex justify-between items-start mb-2">
                                    <div>
                                        <h4 class="font-bold text-white"><?= $name ?></h4>
                                        <span class="text-[10px] uppercase tracking-widest text-slate-500 font-bold"><?= $r['reviewer_type'] ?></span>
                                    </div>
                                    <div class="flex text-amber-400 text-sm gap-0.5">
                                        <?php for($i=1; $i<=5; $i++): ?>
                                            <i data-lucide="star" class="w-4 h-4 <?=$i <= $r['rating'] ? 'fill-current' : 'text-slate-700'?>"></i>
                                        <?php endfor; ?>
                                    </div>
                                </div>
                                <p class="text-slate-300 italic mb-3">"<?=$r['comment']?>"</p>
                                <div class="text-xs text-slate-500 flex items-center gap-1">
                                    <i data-lucide="calendar" class="w-3 h-3"></i>
                                    <?=date('M d, Y', strtotime($r['created_at']))?>
                                </div>
                            </div>
                        <?php endwhile; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-12 glass-panel rounded-xl border-dashed border-2 border-slate-700">
                            <i data-lucide="message-circle" class="w-12 h-12 text-slate-600 mx-auto mb-3"></i>
                            <p class="text-slate-500">No reviews yet.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        lucide.createIcons();

        function revealPhone(btn, fullPhone) {
            const span = btn.querySelector('span');
            const icon = btn.querySelector('i');
            const hint = btn.nextElementSibling;
            
            span.textContent = fullPhone;
            span.classList.remove('tracking-widest');
            btn.onclick = null;
            btn.classList.add('cursor-default');
            btn.classList.remove('hover:bg-indigo-600/20', 'hover:border-indigo-500/50');
            
            // Update icon
            icon.setAttribute('data-lucide', 'phone');
            lucide.createIcons();
            
            if(hint) hint.style.display = 'none';
        }
    </script>
</body>
</html>
