<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
session_write_close();
date_default_timezone_set('Africa/Lagos');

require '../config.php';

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

$userRole = strtolower(trim($_SESSION['role'] ?? ''));
if (!in_array($userRole, ['admin', 'superadmin', 'hr'])) {
    die("Access Denied");
}

/*
|--------------------------------------------------------------------------
| HELPERS
|--------------------------------------------------------------------------
*/

function e($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

/*
|--------------------------------------------------------------------------
| AJAX: UPDATE POSITION PARENT (HIERARCHY)
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {

    header('Content-Type: application/json');

    $positionId = intval($_POST['position_id'] ?? 0);
    $parentId   = intval($_POST['parent_id'] ?? 0);

    if ($positionId <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid position selection.']);
        exit;
    }

    $targetParent = $parentId > 0 ? $parentId : null;

    // 1. Cannot report to self
    if ($targetParent !== null && $targetParent === $positionId) {
        echo json_encode(['success' => false, 'message' => 'A position cannot report to itself.']);
        exit;
    }

    // 2. Prevent circular hierarchy (A -> B -> A)
    if ($targetParent !== null) {
        $currentId = $targetParent;
        $visited = [];

        while ($currentId !== null && $currentId > 0) {
            if (isset($visited[$currentId])) {
                echo json_encode(['success' => false, 'message' => 'Circular position relationship detected.']);
                exit;
            }

            $visited[$currentId] = true;

            if ($currentId === $positionId) {
                echo json_encode(['success' => false, 'message' => 'This relationship creates a circular hierarchy loop.']);
                exit;
            }

            $stmt = $conn->prepare("SELECT parent_id FROM positions WHERE id = ? LIMIT 1");
            $stmt->bind_param("i", $currentId);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            $stmt->close();

            if (!$row) break;
            $currentId = intval($row['parent_id'] ?? 0);
        }
    }

    // 3. Save relationship directly to positions table
    if ($targetParent === null) {
        $stmt = $conn->prepare("UPDATE positions SET parent_id = NULL WHERE id = ?");
        $stmt->bind_param("i", $positionId);
    } else {
        $stmt = $conn->prepare("UPDATE positions SET parent_id = ? WHERE id = ?");
        $stmt->bind_param("ii", $targetParent, $positionId);
    }

    if (!$stmt->execute()) {
        $error = $stmt->error;
        $stmt->close();
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $error]);
        exit;
    }

    $stmt->close();
    echo json_encode(['success' => true, 'message' => 'Position hierarchy updated successfully.']);
    exit;
}

/*
|--------------------------------------------------------------------------
| FETCH ALL POSITIONS
|--------------------------------------------------------------------------
*/

$search = trim($_GET['search'] ?? '');

$positions = [];
$sql = "SELECT id, name, parent_id FROM positions WHERE 1";

if ($search !== '') {
    $sql .= " AND name LIKE " . $conn->quote("%{$search}%");
}

$sql .= " ORDER BY name ASC";

$res = $conn->query($sql);
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $positions[$row['id']] = [
            'id' => intval($row['id']),
            'name' => $row['name'],
            'parent_id' => intval($row['parent_id'] ?? 0)
        ];
    }
}

/*
|--------------------------------------------------------------------------
| BUILD POSITION TREE STRUCTURE
|--------------------------------------------------------------------------
*/

$children = [];
foreach ($positions as $pos) {
    $parentId = $pos['parent_id'];

    if ($parentId > 0 && isset($positions[$parentId])) {
        $children[$parentId][] = $pos['id'];
    } else {
        $children[0][] = $pos['id']; // Root level positions
    }
}

/*
|--------------------------------------------------------------------------
| RECURSIVE TREE RENDERER (POSITIONS ONLY)
|--------------------------------------------------------------------------
*/

function renderPositionNode($posId, &$positions, &$children, $level = 0, &$rendered = []) {
    if (isset($rendered[$posId])) return;
    $rendered[$posId] = true;

    if (!isset($positions[$posId])) return;

    $pos = $positions[$posId];
    $subPositions = $children[$posId] ?? [];
    ?>

    <div class="org-node-wrap">
        <div class="org-node" data-position-id="<?= $pos['id'] ?>">
            
            <!-- POSITION TITLE HEADER -->
            <div class="org-position-header">
                <div class="org-position-title">
                    <?= e($pos['name']) ?>
                </div>
            </div>

            <!-- PARENT SELECTION DROPDOWN -->
            <div class="org-actions">
                <label class="block text-[8px] font-black uppercase text-slate-400 mb-1">Reports To Position:</label>
                <select
                    class="reports-select"
                    data-position-id="<?= $pos['id'] ?>"
                    onchange="updatePositionParent(this)"
                >
                    <option value="0">-- Top Level Position --</option>
                    <?php foreach ($positions as $optId => $opt): ?>
                        <?php if ($optId !== $pos['id']): ?>
                            <option
                                value="<?= $optId ?>"
                                <?= $pos['parent_id'] === $optId ? 'selected' : '' ?>
                            >
                                <?= e($opt['name']) ?>
                            </option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </div>

            <?php if (!empty($subPositions)): ?>
                <button type="button" class="expand-btn" onclick="toggleBranch(this)">
                    <span>−</span> <?= count($subPositions) ?> <?= count($subPositions) === 1 ? 'sub-position' : 'sub-positions' ?>
                </button>
            <?php endif; ?>
        </div>

        <?php if (!empty($subPositions)): ?>
            <div class="org-children">
                <?php foreach ($subPositions as $childId): ?>
                    <?php renderPositionNode($childId, $positions, $children, $level + 1, $rendered); ?>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <?php
}

$rootPositions = $children[0] ?? [];
$totalPositions = count($positions);
$topLevelCount = count($rootPositions);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Position Structure Organogram</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">

    <style>
        * { box-sizing: border-box; }
        body { font-family: 'Mulish', sans-serif; }

        .org-canvas {
            width: 100%;
            overflow: auto;
            background: linear-gradient(90deg, rgba(148,163,184,.08) 1px, transparent 1px),
                        linear-gradient(rgba(148,163,184,.08) 1px, transparent 1px);
            background-size: 28px 28px;
            border: 1px solid #cbd5e1;
            min-height: 650px;
            padding: 50px;
        }

        .org-root {
            display: flex;
            flex-direction: column;
            align-items: center;
            min-width: max-content;
            transform-origin: top center;
            transition: transform 0.15s ease-out;
        }

        .org-node-wrap {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
        }

        /* POSITION CARD CONTAINER (SCREEN VIEW) */
        .org-node {
            width: 250px;
            background: #ffffff;
            border: 2px solid #0f172a;
            border-radius: 8px;
            padding: 14px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
            position: relative;
            z-index: 2;
            transition: transform .2s ease, box-shadow .2s ease, border-color .2s ease;
            text-align: center;
        }

        .org-node:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            border-color: #4338ca;
        }

        .org-position-header {
            padding-bottom: 4px;
            margin-bottom: 6px;
        }

        .org-position-title {
            font-size: 14px;
            color: #0f172a;
            font-weight: 900;
            text-transform: uppercase;
            letter-spacing: 0.025em;
            line-height: 1.25;
            word-wrap: break-word;
        }

        .reports-select {
            width: 100%;
            background: #ffffff;
            border: 1px solid #cbd5e1;
            border-radius: 6px;
            padding: 6px;
            font-size: 11px;
            font-weight: 800;
            color: #334155;
            outline: none;
        }

        .reports-select:focus {
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79,70,229,.10);
        }

        /* CONNECTING BRANCH LINES */
        .org-children {
            display: flex;
            justify-content: center;
            gap: 48px;
            padding-top: 64px;
            position: relative;
        }

        .org-children::before {
            content: '';
            position: absolute;
            top: 0;
            left: 50%;
            width: 2px;
            height: 64px;
            background: #64748b;
            transform: translateX(-50%);
        }

        .org-children::after {
            content: '';
            position: absolute;
            top: 32px;
            left: 0;
            right: 0;
            height: 2px;
            background: #64748b;
        }

        .org-children > .org-node-wrap::before {
            content: '';
            position: absolute;
            top: -32px;
            left: 50%;
            width: 2px;
            height: 32px;
            background: #64748b;
            transform: translateX(-50%);
        }

        .expand-btn {
            margin-top: 10px;
            border: 1px solid #cbd5e1;
            background: #f8fafc;
            color: #475569;
            border-radius: 6px;
            padding: 4px 8px;
            font-size: 9px;
            font-weight: 900;
            cursor: pointer;
        }

        .expand-btn:hover {
            background: #eef2ff;
            color: #3730a3;
        }

        .org-node-wrap.collapsed > .org-children {
            display: none;
        }

        /* LANDSCAPE PRINT SETUP */
        @page {
            size: landscape;
            margin: 5mm;
        }

        @media print {
            #sidebar, 
            #sidebar-overlay, 
            header, 
            footer, 
            .no-print, 
            .expand-btn, 
            .org-actions {
                display: none !important;
            }

            body, 
            #main-content, 
            main, 
            main > div,
            .bg-white,
            .shadow-xs,
            .rounded-xl,
            .border {
                background: transparent !important;
                border: none !important;
                box-shadow: none !important;
                padding: 0 !important;
                margin: 0 !important;
                max-width: 100% !important;
                width: 100% !important;
                border-radius: 0 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }

            /* PRINT ONLY PAGE HEADER (ALIGNED LEFT) */
            .print-header {
                display: block !important;
                width: 100% !important;
                text-align: left !important;
                margin-bottom: 35px !important;
            }

            .print-header h1 {
                font-size: 18px !important;
                font-weight: 900 !important;
                text-transform: uppercase !important;
                letter-spacing: 0.12em !important;
                color: #000000 !important;
                border-bottom: 2px solid #000000 !important;
                padding-bottom: 6px !important;
                display: block !important;
                text-align: left !important;
            }

            .org-canvas {
                border: none !important;
                background: none !important;
                overflow: visible !important;
                padding: 0 !important;
                width: 100% !important;
                min-height: auto !important;
            }

            /* SET TO 58% SCALE FOR PRINTING */
            .org-root {
                min-width: 0 !important;
                width: 100% !important;
                zoom: 58% !important;
                margin-top: 0 !important;
            }

            /* COMPACT NARROW PORTRAIT BOXES */
            .org-node {
                width: 45px !important;            
                min-height: 160px !important;      
                display: flex !important;
                flex-direction: column !important;
                justify-content: center !important;
                align-items: center !important;
                border: 1.5px solid #000000 !important;
                border-radius: 4px !important;
                box-shadow: none !important;
                padding: 8px 2px !important;
                background: #ffffff !important;
                overflow: hidden !important;
            }

            .org-position-header {
                border: none !important;
                margin: 0 !important;
                padding: 0 !important;
                width: 100% !important;
                height: 100% !important;
                display: flex !important;
                align-items: center !important;
                justify-content: center !important;
            }

            /* VERTICAL TITLE (TOP TO BOTTOM) WITH TEXT WRAPPING */
            .org-position-title {
                font-size: 9.5px !important;
                line-height: 1.15 !important;
                color: #000000 !important;
                text-align: center !important;
                
                /* VERTICAL TEXT ORIENTATION FROM TOP TO BOTTOM */
                writing-mode: vertical-rl !important;
                text-orientation: mixed !important;

                /* COMPACT WRAPPING FOR LONG TITLES */
                white-space: normal !important;
                word-break: break-word !important;
                overflow-wrap: anywhere !important;
                hyphens: auto !important;
                max-height: 145px !important;
            }

            /* INCREASED SPACING BETWEEN BOXES IN PRINT MODE */
            .org-children {
                gap: 55px !important;
                padding-top: 50px !important;
            }

            .org-children::before {
                height: 50px !important;
                background: #000000 !important;
            }

            .org-children::after {
                top: 25px !important;
                background: #000000 !important;
            }

            .org-children > .org-node-wrap::before {
                top: -25px !important;
                height: 25px !important;
                background: #000000 !important;
            }
        }
    </style>
</head>

<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased font-sans">

<div class="flex">

    <?php include_once '../components/sidebar.php'; ?>
    <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40" onclick="toggleSidebar()"></div>

    <div id="main-content" class="flex-1 min-w-0 md:pl-60 min-h-screen flex flex-col">

        <!-- HEADER -->
        <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 no-print">
            <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">
                    <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">
                        Position Hierarchy Organogram
                    </h1>
                    <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">
                        Pure Role & Position Relationship Visualizer
                    </p>
                </div>
            </div>

            <div class="flex items-center gap-3">
                <!-- PRINT ZOOM SCALE SLIDER (DEFAULTED TO 58%) -->
                <div class="hidden sm:flex items-center gap-2 bg-slate-100 px-3 py-1.5 rounded-lg border border-slate-300/80">
                    <label for="printScale" class="text-[10px] font-black uppercase text-slate-600">Scale:</label>
                    <input 
                        type="range" 
                        id="printScale" 
                        min="30" 
                        max="100" 
                        value="58" 
                        oninput="adjustPrintScale(this.value)"
                        class="w-20 accent-indigo-600 cursor-pointer"
                    >
                    <span id="scaleVal" class="text-[10px] font-black text-slate-800 w-8">58%</span>
                </div>

                <button onclick="window.print()" class="bg-slate-900 hover:bg-slate-800 text-white px-3 py-2 rounded-md text-[10px] font-black uppercase tracking-wider transition">
                    Print Preview
                </button>
            </div>
        </header>

        <main class="flex-1 p-4 sm:p-6 max-w-[1600px] w-full mx-auto space-y-6">

            <!-- BANNER -->
            <div class="bg-gradient-to-br from-slate-900 to-indigo-950 rounded-xl p-6 text-white shadow-md border border-slate-800 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-5 no-print">
                <div>
                    <div class="flex items-center gap-2 mb-2">
                        <span class="w-2.5 h-2.5 rounded-full bg-emerald-400"></span>
                        <span class="text-[10px] uppercase tracking-widest font-black text-indigo-200">
                            Position Architecture
                        </span>
                    </div>
                    <h2 class="text-xl sm:text-2xl font-black tracking-tight">
                        Organizational Positions Map
                    </h2>
                    <p class="text-[11px] text-slate-300 mt-2 max-w-2xl leading-relaxed">
                        Pure position hierarchy diagram. Select a parent position from any card's dropdown to set which role reports to which.
                    </p>
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div class="bg-white/10 border border-white/10 rounded-lg px-5 py-3 text-center">
                        <div class="text-[9px] uppercase tracking-wider text-indigo-200 font-black">Total Positions</div>
                        <div class="text-xl font-black mt-1"><?= $totalPositions ?></div>
                    </div>
                    <div class="bg-white/10 border border-white/10 rounded-lg px-5 py-3 text-center">
                        <div class="text-[9px] uppercase tracking-wider text-indigo-200 font-black">Top Positions</div>
                        <div class="text-xl font-black mt-1"><?= $topLevelCount ?></div>
                    </div>
                </div>
            </div>

            <!-- SEARCH FILTER -->
            <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-xs no-print">
                <form method="GET" class="flex gap-3">
                    <input
                        type="text"
                        name="search"
                        value="<?= e($search) ?>"
                        placeholder="Search positions..."
                        class="flex-1 bg-stone-50/50 border border-slate-300/80 rounded-lg p-3 text-xs font-bold text-slate-950 focus:outline-none focus:border-indigo-600 focus:bg-white"
                    >
                    <button type="submit" class="bg-slate-900 hover:bg-slate-800 text-white rounded-lg px-6 py-3 text-[10px] font-black uppercase tracking-wider">
                        Filter
                    </button>
                    <a href="organogram.php" class="bg-white hover:bg-stone-50 border border-slate-300 text-slate-700 rounded-lg px-6 py-3 text-[10px] font-black uppercase tracking-wider text-center">
                        Reset
                    </a>
                </form>
            </div>

            <!-- CANVAS CONTAINER -->
            <div class="bg-white border border-slate-300/80 rounded-xl shadow-xs overflow-hidden">
                <div class="px-5 py-4 border-b border-slate-300/80 flex items-center justify-between no-print">
                    <div>
                        <h3 class="text-xs font-black uppercase tracking-tight text-slate-950">
                            Hierarchy Diagram
                        </h3>
                        <p class="text-[10px] text-slate-500 font-semibold mt-1">
                            <?= $totalPositions ?> position records loaded
                        </p>
                    </div>

                    <div id="save-status" class="text-[10px] font-black text-slate-400 uppercase tracking-wider">
                        Ready
                    </div>
                </div>

                <?php if (!empty($rootPositions)): ?>
                    <div class="org-canvas">
                        
                        <!-- PRINT ONLY PAGE HEADER -->
                        <div class="print-header hidden">
                            <h1>Organisational Chart</h1>
                        </div>

                        <!-- INITIAL LOAD SCALE SET TO 58% -->
                        <div class="org-root" id="org-tree-root" style="transform: scale(0.58);">
                            <?php
                            $rendered = [];
                            foreach ($rootPositions as $rootId) {
                                renderPositionNode($rootId, $positions, $children, 0, $rendered);
                            }
                            ?>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="p-12 text-center no-print">
                        <h3 class="text-sm font-black text-slate-900">No Positions Found</h3>
                        <p class="text-xs text-slate-500 mt-1">Ensure positions exist in your database table.</p>
                    </div>
                <?php endif; ?>
            </div>

        </main>

        <footer class="mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center no-print">
            <p class="text-[9px] text-slate-500 font-mono tracking-wider">
                &copy; 2026 Core HR Engine Platform
            </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) sidebar.classList.toggle('-translate-x-full');
    if (overlay) overlay.classList.toggle('hidden');
}

function adjustPrintScale(val) {
    document.getElementById('scaleVal').textContent = val + '%';
    const root = document.getElementById('org-tree-root');
    if (root) {
        root.style.transform = `scale(${val / 100})`;
    }
}

function updatePositionParent(select) {
    const positionId = select.dataset.positionId;
    const parentId = select.value;
    const status = document.getElementById('save-status');

    status.textContent = 'Saving...';
    status.className = 'text-[10px] font-black text-amber-600 uppercase tracking-wider';
    select.disabled = true;

    fetch('organogram.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
            ajax: '1',
            position_id: positionId,
            parent_id: parentId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (!data.success) {
            throw new Error(data.message || 'Unable to save relationship.');
        }

        status.textContent = 'Saved';
        status.className = 'text-[10px] font-black text-emerald-600 uppercase tracking-wider';

        setTimeout(() => {
            window.location.reload();
        }, 400);
    })
    .catch(error => {
        console.error(error);
        status.textContent = 'Save Failed';
        status.className = 'text-[10px] font-black text-rose-600 uppercase tracking-wider';
        alert(error.message || 'Unable to update position hierarchy.');
        select.disabled = false;
    });
}

function toggleBranch(button) {
    const wrapper = button.closest('.org-node-wrap');
    if (!wrapper) return;

    const children = wrapper.querySelector(':scope > .org-children');
    if (!children) return;

    wrapper.classList.toggle('collapsed');
    const span = button.querySelector('span');
    span.textContent = wrapper.classList.contains('collapsed') ? '+' : '−';
}
</script>

</body>
</html>