<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
session_write_close();
require '../config.php';

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

$userId = intval($_SESSION['user_id']);
$username = $_SESSION['username'] ?? 'Staff Member';
$role = $_SESSION['role'] ?? 'Staff';

/*
|--------------------------------------------------------------------------
| FIND EMPLOYEE REFERENCE MATCH
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("SELECT id FROM employees WHERE user_id = ? LIMIT 1");
$stmt->bind_param("i", $userId);
$stmt->execute();
$employee = $stmt->get_result()->fetch_assoc();

if (!$employee) {
    die("Employee record not found.");
}

$employeeId = $employee['id'];

/*
|--------------------------------------------------------------------------
| RETRIEVE ASSET ASSIGNMENT TRACKS DATASETS
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT 
        aa.*,
        a.asset_name,
        a.asset_tag,
        a.category
    FROM asset_assignments aa
    LEFT JOIN assets a ON a.id = aa.asset_id
    WHERE aa.employee_id = ?
    ORDER BY aa.assigned_date DESC
");
$stmt->bind_param("i", $employeeId);
$stmt->execute();
$res = $stmt->get_result();

$rows = [];
while ($row = $res->fetch_assoc()) {
    $rows[] = $row;
}
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Assets - HR System</title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght=0,200..1000;1,200..1000&display=swap" rel="stylesheet">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Mulish', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <link rel="stylesheet" href="../components/sidebar.css">
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased selection:bg-indigo-600 selection:text-white font-sans">

    <div class="flex">
        
        <?php include '../components/sidebar.php'; ?>

        <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300" onclick="toggleSidebar()"></div>

        <div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
            
            <header class="sticky top-0 bg-white/90 backdrop-blur-md border-b border-slate-300/80 h-14 flex items-center justify-between px-4 sm:px-6 z-30 shadow-xs">
                <div class="flex items-center gap-3">
                    <button onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95 md:hidden" aria-label="Toggle Side Area Menu">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"></path>
                        </svg>
                    </button>
                    <div>
                        <h1 class="text-sm font-black tracking-tight text-slate-950">My Assigned Assets</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Custody Logistics Index</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <div class="hidden sm:flex flex-col text-right">
                        <span class="text-[11px] font-extrabold text-slate-950 leading-tight"><?= htmlspecialchars($username); ?></span>
                        <span class="text-[9px] text-indigo-700 uppercase font-black tracking-wider leading-none mt-0.5"><?= htmlspecialchars($role); ?></span>
                    </div>
                    <div class="w-7 h-7 bg-slate-200 border border-slate-300 rounded-lg flex items-center justify-center font-black text-xs text-slate-700 select-none uppercase">
                        <?= strtoupper(substr($username, 0, 1)); ?>
                    </div>
                </div>
            </header>

            <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto space-y-6">

                <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
                    
                    <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80 flex items-center justify-between">
                        <div>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Hardware Custody History</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Realtime asset operational tracking states and assignment frameworks.</p>
                        </div>
                        <span class="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2.5 py-1 rounded-md font-extrabold text-[10px] font-mono shadow-xs">
                            Audit Active
                        </span>
                    </div>

                    <?php if (empty($rows)): ?>
                    <div class="text-center py-16 px-4">
                        <div class="flex flex-col items-center justify-center space-y-2 max-w-md mx-auto">
                            <div class="text-3xl">📭</div>
                            <h4 class="text-xs font-extrabold text-slate-800">No Allocated Assets Found</h4>
                            <p class="text-[10px] text-slate-600">You currently have no hardware peripherals, machinery units, computing electronics, or corporate properties logged under your operational custody framework.</p>
                        </div>
                    </div>
                    <?php else: ?>

                    <!-- Mobile Responsive Layout Card Blocks -->
                    <div class="block md:hidden divide-y divide-slate-200/80 max-h-[600px] overflow-y-auto font-bold">
                        <?php foreach($rows as $row): 
                            $status = $row['status'] ?? 'Unknown';
                            if ($status === 'Assigned' || $status === 'Active') {
                                $badge = 'bg-emerald-50 text-emerald-800 border-emerald-300';
                            } elseif ($status === 'Returned') {
                                $badge = 'bg-stone-100 text-slate-700 border-slate-300';
                            } else {
                                $badge = 'bg-amber-50 text-amber-900 border-amber-300';
                            }
                        ?>
                        <div class="p-4 flex flex-col gap-3 hover:bg-stone-50/50 transition text-slate-800">
                            <div class="flex items-start justify-between gap-4">
                                <div class="space-y-1">
                                    <span class="text-[9px] bg-indigo-50 text-indigo-700 font-black tracking-wider uppercase px-2 py-0.5 rounded border border-indigo-100 inline-block">
                                        <?= htmlspecialchars($row['category'] ?? 'General') ?>
                                    </span>
                                    <h4 class="text-xs font-black text-slate-950 tracking-tight leading-tight">
                                        <?= htmlspecialchars($row['asset_name'] ?? 'Unclassified Device Log') ?>
                                    </h4>
                                    <p class="text-[10px] font-mono font-bold text-slate-500">
                                        Tag ID: <span class="text-slate-900"><?= htmlspecialchars($row['asset_tag'] ?? 'N/A') ?></span>
                                    </p>
                                </div>
                                <span class="px-2 py-0.5 text-[9px] font-black uppercase rounded border tracking-wider shrink-0 <?= $badge ?>">
                                    <?= $status ?>
                                </span>
                            </div>

                            <div class="pt-2 border-t border-dashed border-slate-200 flex items-center justify-between text-[10px]">
                                <span class="font-extrabold uppercase tracking-wider text-slate-500">Assignment Frame</span>
                                <span class="font-mono font-bold text-slate-900">
                                    <?= date('d M Y', strtotime($row['assigned_date'])) ?>
                                </span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Main Desktop Structural Table Framework -->
                    <div class="hidden md:block overflow-x-auto w-full">
                        <table class="w-full border-collapse">
                            <thead>
                                <tr class="bg-stone-50 text-slate-500 uppercase text-[9px] font-black tracking-wider border-b border-slate-300/80">
                                    <th class="p-3 text-left pl-6">Asset Resource Identity</th>
                                    <th class="p-3 text-center">Identifier Tag</th>
                                    <th class="p-3 text-center">Operational Category</th>
                                    <th class="p-3 text-center">Assignment Date</th>
                                    <th class="p-3 pr-6 text-center">Custody Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 text-xs font-bold">
                                <?php foreach($rows as $row): 
                                    $status = $row['status'] ?? 'Unknown';
                                    if ($status === 'Assigned' || $status === 'Active') {
                                        $badge = 'bg-emerald-50 text-emerald-800 border-emerald-300';
                                    } elseif ($status === 'Returned') {
                                        $badge = 'bg-stone-100 text-slate-700 border-slate-300';
                                    } else {
                                        $badge = 'bg-amber-50 text-amber-900 border-amber-300';
                                    }
                                ?>
                                    <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                        <td class="p-3 pl-6 font-black text-slate-950 tracking-tight whitespace-nowrap">
                                            <?= htmlspecialchars($row['asset_name'] ?? 'Unclassified Corporate Item') ?>
                                        </td>
                                        <td class="p-3 text-center font-mono font-black text-indigo-700 whitespace-nowrap text-[10px]">
                                            <?= htmlspecialchars($row['asset_tag'] ?? '—') ?>
                                        </td>
                                        <td class="p-3 text-center whitespace-nowrap">
                                            <span class="bg-stone-100 text-slate-700 px-2.5 py-1 rounded-md border border-slate-300 font-black text-[10px] uppercase tracking-wider">
                                                <?= htmlspecialchars($row['category'] ?? 'General Allocation') ?>
                                            </span>
                                        </td>
                                        <td class="p-3 text-center font-mono font-bold text-slate-600 whitespace-nowrap text-[10px]">
                                            <?= date('d M Y', strtotime($row['assigned_date'])) ?>
                                        </td>
                                        <td class="p-3 pr-6 text-center whitespace-nowrap">
                                            <span class="px-2 py-0.5 text-[10px] font-black tracking-wider uppercase rounded border <?= $badge ?>">
                                                <?= $status ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </main>

            <footer class="mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center">
                <p class="text-[9px] text-slate-500 font-mono tracking-wider">&copy; 2026 Core HR Engine System Platform • Dynamic Secure Architecture Protocol.</p>
            </footer>
        </div>
    </div>

    <script src="../components/sidebar.js"></script>
    <script>
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebar-overlay');
        if(sidebar && overlay) {
            sidebar.classList.toggle('-translate-x-full');
            overlay.classList.toggle('hidden');
        }
    }
    </script>
</body>
</html>