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

require_once __DIR__ . '/../../../dripend/includes/db.php';

$msg = '';
$error = '';

// Check if a specific lab test was passed
$service_id = isset($_GET['service_id']) ? (int)$_GET['service_id'] : 0;

if ($service_id === 0) {
    die("<div style='padding:24px; border-radius:8px; font-family:sans-serif; color:#991b1b; background:#fef2f2; border:1px solid #fecaca; font-weight:600;'>Fatal Error: No Service ID provided. Please return to the Mapping Directory.</div>");
}

// ==============================================================================
// 1. HANDLE SAVING THE NEW ORDER
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_order'])) {
    $ordered_param_ids = $_POST['ordered_params'] ?? [];
    
    if (!empty($ordered_param_ids)) {
        $conn->begin_transaction();
        try {
            $stmt = $conn->prepare("UPDATE lab_test_parameter_mapping SET display_order = ? WHERE service_id = ? AND parameter_id = ?");
            
            // The array comes in exactly the order they were dragged on screen
            $new_order = 1; 
            foreach ($ordered_param_ids as $pid) {
                $pid = (int)$pid;
                $stmt->bind_param("iii", $new_order, $service_id, $pid);
                $stmt->execute();
                $new_order++;
            }
            
            $conn->commit();
            $msg = "Parameter order successfully updated!";
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Failed to update order: " . $e->getMessage();
        }
    }
}

// ==============================================================================
// 2. FETCH DATA FOR UI
// ==============================================================================
// Fetch the Test Name for the Header
$stmtTest = $conn->prepare("SELECT service_name FROM service_catalog WHERE id = ?");
$stmtTest->bind_param("i", $service_id);
$stmtTest->execute();
$testInfo = $stmtTest->get_result()->fetch_assoc();
$stmtTest->close();

if (!$testInfo) {
    die("<div style='padding:24px; border-radius:8px; font-family:sans-serif; color:#991b1b; background:#fef2f2; border:1px solid #fecaca; font-weight:600;'>Fatal Error: Lab test not found in catalog.</div>");
}

// Fetch mapped parameters in their CURRENT display order
$mapped_params = [];
$qParams = "
    SELECT m.parameter_id, p.parameter_name, p.result_type, p.unit_of_measure 
    FROM lab_test_parameter_mapping m
    JOIN lab_parameters p ON m.parameter_id = p.id
    WHERE m.service_id = ?
    ORDER BY m.display_order ASC
";
$stmtParams = $conn->prepare($qParams);
$stmtParams->bind_param("i", $service_id);
$stmtParams->execute();
$resParams = $stmtParams->get_result();
while ($row = $resParams->fetch_assoc()) {
    $mapped_params[] = $row;
}
$stmtParams->close();
?>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

<style>
/* Scoped styles to prevent bleeding into the master dashboard */
.lis-arrange-module {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: flex-start;
    animation: fadeIn 0.3s ease-in-out;
}

.lis-arrange-container {
    width: 100%;
    max-width: 650px;
    background: #ffffff;
    border-radius: 12px;
    padding: 35px;
    border: 1px solid #e2e8f0;
}

.lis-page-title { font-size: 22px; font-weight: 800; color: #0f172a; margin-bottom: 6px; display: flex; align-items: center; gap: 10px; }
.lis-page-title i { color: #3b82f6; }
.lis-page-subtitle { font-size: 14px; color: #64748b; margin-bottom: 25px; display: block; border-bottom: 1px solid #e2e8f0; padding-bottom: 16px; line-height: 1.5; }

/* Drag and Drop List Styles */
.lis-sort-list { list-style: none; padding: 0; margin: 0; margin-bottom: 30px; }

.lis-sort-item { 
    display: flex; align-items: center; justify-content: space-between; gap: 15px; 
    background: #f8fafc; border: 1px solid #cbd5e1; border-radius: 8px; 
    padding: 14px 20px; margin-bottom: 10px; transition: all 0.2s ease;
    cursor: grab;
}
.lis-sort-item:hover { background: #f1f5f9; border-color: #94a3b8; }
.lis-sort-item:active { cursor: grabbing; }

/* SortableJS Ghost Class (Visual feedback when dragging) */
.sortable-ghost { opacity: 0.4; background: #e0f2fe; border: 2px dashed #3b82f6; }
.sortable-drag { box-shadow: 0 10px 25px rgba(0,0,0,0.1); cursor: grabbing !important; }

.lis-sort-handle { color: #94a3b8; font-size: 18px; cursor: inherit; display: flex; align-items: center; }

.lis-param-name { font-weight: 700; font-size: 14px; color: #334155; flex: 1; display: flex; align-items: center; gap: 8px;}
.lis-param-unit { font-weight: 400; color: #94a3b8; font-size: 12px; }

.lis-param-meta { font-size: 11px; font-weight: 700; text-transform: uppercase; padding: 4px 10px; border-radius: 6px; letter-spacing: 0.5px; }
.meta-numeric { background: #e0e7ff; color: #3730a3; }
.meta-options { background: #fef3c7; color: #b45309; }
.meta-text { background: #f3f4f6; color: #475569; }

/* Buttons */
.lis-btn-primary { background: #059669; color: #ffffff; border: none; padding: 12px 24px; border-radius: 8px; font-weight: 600; font-size: 14px; cursor: pointer; transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; }
.lis-btn-primary:hover { background: #047857; transform: translateY(-1px); box-shadow: 0 4px 6px rgba(5, 150, 105, 0.2); }

.lis-btn-secondary { background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; padding: 12px 24px; border-radius: 8px; font-weight: 600; font-size: 14px; cursor: pointer; transition: 0.2s; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; }
.lis-btn-secondary:hover { background: #e2e8f0; color: #1e293b; }

/* Alerts */
.lis-alert-success { background: #dcfce7; color: #166534; padding: 16px; border-radius: 8px; border: 1px solid #bbf7d0; margin-bottom: 24px; font-size: 14px; font-weight: 600; display: flex; align-items: center; gap: 10px;}
.lis-alert-error { background: #fef2f2; color: #991b1b; padding: 16px; border-radius: 8px; border: 1px solid #fecaca; margin-bottom: 24px; font-size: 14px; font-weight: 600; display: flex; align-items: center; gap: 10px;}
</style>

<div class="lis-arrange-module">
    <div class="lis-arrange-container">
        <div class="lis-page-title"><i class="fa-solid fa-arrow-down-a-z"></i> Arrange Parameters</div>
        <span class="lis-page-subtitle">Drag and drop the items below to dictate the exact order they will appear on the lab technician's screen for <strong><?php echo htmlspecialchars($testInfo['service_name']); ?></strong>.</span>

        <?php if(!empty($msg)): ?><div class="lis-alert-success"><i class="fa-solid fa-check-circle"></i> <?php echo htmlspecialchars($msg); ?></div><?php endif; ?>
        <?php if(!empty($error)): ?><div class="lis-alert-error"><i class="fa-solid fa-triangle-exclamation"></i> <?php echo htmlspecialchars($error); ?></div><?php endif; ?>

        <?php if(empty($mapped_params)): ?>
            <div style="text-align:center; padding:40px; color:#94a3b8; border: 1px dashed #cbd5e1; border-radius:8px; margin-bottom:24px; background: #f8fafc;">
                <i class="fa-solid fa-ghost" style="font-size:40px; margin-bottom:12px; color: #e2e8f0;"></i><br>
                <span style="font-size: 14px; font-weight: 500;">No parameters have been mapped to this test yet.</span>
            </div>
            <a href="../../views/system_setup/laboratory/mapLabParameters.php" data-title="Map Tests" class="lis-btn-secondary"><i class="fa-solid fa-arrow-left"></i> Return to Mapping</a>
        <?php else: ?>
            <form method="POST" action="" id="sortForm">
                <input type="hidden" name="save_order" value="1">
                
                <ul class="lis-sort-list" id="sortable-list">
                    <?php foreach($mapped_params as $index => $mp): ?>
                        <li class="lis-sort-item">
                            <input type="hidden" name="ordered_params[]" value="<?php echo $mp['parameter_id']; ?>">
                            
                            <div class="lis-sort-handle"><i class="fa-solid fa-grip-vertical"></i></div>
                            
                            <div class="lis-param-name">
                                <?php echo htmlspecialchars($mp['parameter_name']); ?>
                                <?php if(!empty($mp['unit_of_measure'])): ?>
                                    <span class="lis-param-unit">(<?php echo htmlspecialchars($mp['unit_of_measure']); ?>)</span>
                                <?php endif; ?>
                            </div>
                            
                            <?php 
                                $metaClass = 'meta-text';
                                if($mp['result_type'] === 'Numeric') $metaClass = 'meta-numeric';
                                if($mp['result_type'] === 'Options') $metaClass = 'meta-options';
                            ?>
                            <div class="lis-param-meta <?php echo $metaClass; ?>"><?php echo htmlspecialchars($mp['result_type']); ?></div>
                        </li>
                    <?php endforeach; ?>
                </ul>

                <div style="display: flex; justify-content: space-between; align-items: center; padding-top: 24px; border-top: 1px solid #e2e8f0;">
                    <a href="../../views/system_setup/laboratory/mapLabParameters.php" data-title="Map Tests" class="lis-btn-secondary"><i class="fa-solid fa-arrow-left"></i> Go Back</a>
                    <button type="submit" class="lis-btn-primary" id="saveBtn"><i class="fa-solid fa-floppy-disk"></i> Save New Order</button>
                </div>
            </form>
        <?php endif; ?>
    </div>
</div>

<script>
    // SPA-Safe Execution Block
    // Wait slightly to ensure the SortableJS library is loaded and the DOM is painted
    setTimeout(() => {
        const el = document.getElementById('sortable-list');
        if(el && typeof Sortable !== 'undefined') {
            Sortable.create(el, {
                handle: '.lis-sort-item', // Allows clicking anywhere on the item to drag
                animation: 150,           // Butter-smooth animation
                ghostClass: 'sortable-ghost',
                dragClass: 'sortable-drag',
                onEnd: function (evt) {
                    // Visual feedback to let the user know they need to click save
                    const saveBtn = document.getElementById('saveBtn');
                    if(saveBtn) {
                        saveBtn.style.backgroundColor = '#d97706'; // Turn Amber/Orange
                        saveBtn.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i> Unsaved Changes - Click to Save';
                        saveBtn.style.boxShadow = '0 0 0 4px rgba(253, 230, 138, 0.5)';
                    }
                }
            });
        } else if (el) {
            console.warn("SortableJS not detected. Please ensure the CDN is included in your main index.php <head>.");
        }
    }, 100);
</script>