<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'LAB_TECHNICIAN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$page_title = "Add Test Type";

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $test_name = mysqli_real_escape_string($conn, $_POST['test_name']);
    $test_code = mysqli_real_escape_string($conn, $_POST['test_code']);

    $category = mysqli_real_escape_string($conn, $_POST['category']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $base_cost = floatval($_POST['cost']);
    $duration_minutes = intval($_POST['turnaround_time_hours']);
    $requires_fasting = isset($_POST['requires_fasting']) ? 1 : 0;
    $requires_appointment = isset($_POST['requires_appointment']) ? 1 : 0;
    $technician_required = isset($_POST['technician_required']) ? 1 : 0;
    $requires_equipment = isset($_POST['requires_equipment']) ? 1 : 0;
    $preparation_instructions = mysqli_real_escape_string($conn, $_POST['preparation_instructions']);
    $sample_type = mysqli_real_escape_string($conn, $_POST['sample_type']);
    $normal_range = mysqli_real_escape_string($conn, $_POST['normal_range']);

    // Equipment array
    $equipment_needed = [];
    if (isset($_POST['equipment_needed']) && is_array($_POST['equipment_needed'])) {
        $equipment_needed = $_POST['equipment_needed'];
    }
    $equipment_json = json_encode($equipment_needed);

    mysqli_begin_transaction($conn);

    try {
        $insert_sql = "INSERT INTO ent_test_types (
                        test_name, test_code, category, description,
                        cost, turnaround_time_hours, requires_fasting, requires_appointment,
                        technician_required, requires_equipment, preparation_instructions,
                        sample_type, normal_range, equipment_needed, is_active, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())";

        $stmt = $conn->prepare($insert_sql);
        $stmt->bind_param(
            'ssssdiiiisssss',
            $test_name,
            $test_code,
            $category,
            $description,
            $base_cost,
            $duration_minutes,
            $requires_fasting,
            $requires_appointment,
            $technician_required,
            $requires_equipment,
            $preparation_instructions,
            $sample_type,
            $normal_range,
            $equipment_json
        );

        if ($stmt->execute()) {
            // Log activity
            $test_type_id = $conn->insert_id;
            $log_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, created_at)
                       VALUES (?, 'CREATE', 'TEST_TYPE', ?, ?, ?, NOW())";
            $log_stmt = $conn->prepare($log_sql);
            $description_log = "Added new test type: " . $test_name;
            $ip_address = $_SERVER['REMOTE_ADDR'];
            $log_stmt->bind_param('iiss', $_SESSION['user_id'], $test_type_id, $description_log, $ip_address);
            $log_stmt->execute();

            mysqli_commit($conn);
            header('Location: test_types.php?success=test_type_added');
            exit();
        } else {
            throw new Exception("Failed to add test type");
        }
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error_message = $e->getMessage();
    }
}

// Fetch equipment list
$equipment_sql = "SELECT equipment_id, equipment_name, equipment_code FROM lab_equipment WHERE status = 'OPERATIONAL' ORDER BY equipment_name";
$equipment_result = mysqli_query($conn, $equipment_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css"
        rel="stylesheet" />

    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }

        .form-section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .form-section-title i {
            color: #667eea;
        }

        .form-label {
            font-weight: 500;
            color: #334155;
            margin-bottom: 0.5rem;
        }

        .required {
            color: #ef4444;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }

        .checkbox-card {
            background: #f8fafc;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            transition: all 0.2s;
            cursor: pointer;
        }

        .checkbox-card:hover {
            border-color: #667eea;
            background: #f0f4ff;
        }

        .checkbox-card input[type="checkbox"]:checked~label {
            font-weight: 600;
            color: #667eea;
        }

        .checkbox-card input[type="checkbox"]:checked {
            background-color: #667eea;
            border-color: #667eea;
        }

        .equipment-item {
            display: flex;
            align-items: center;
            padding: 0.75rem;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            margin-bottom: 0.5rem;
        }

        .equipment-item input[type="checkbox"] {
            width: 1.25rem;
            height: 1.25rem;
            margin-right: 0.75rem;
        }

        .info-box {
            background: #dbeafe;
            border: 1px solid #93c5fd;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }

        .info-box i {
            color: #1e40af;
        }

        .btn-submit {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
            color: white;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Add Test Type</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="test_types.php">Test Types</a></li>
                                        <li class="breadcrumb-item active">Add New</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-test-tube-line me-2"></i>Add New Test Type</h4>
                                <p class="mb-0">Create a new laboratory test type for ENT services</p>
                            </div>
                            <a href="test_types.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-2"></i>Back to List
                            </a>
                        </div>
                    </div>

                    <?php if (isset($error_message)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="ri-error-warning-line me-2"></i><?php echo $error_message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <form method="POST" action="" id="addTestTypeForm">
                        <div class="row">
                            <div class="col-lg-8">
                                <!-- Basic Information -->
                                <div class="form-card">
                                    <div class="form-section-title">
                                        <i class="ri-information-line"></i>
                                        Basic Information
                                    </div>

                                    <div class="row">
                                        <div class="col-md-8 mb-3">
                                            <label class="form-label">Test Name <span class="required">*</span></label>
                                            <input type="text" class="form-control" name="test_name" required
                                                placeholder="e.g., Pure Tone Audiometry">
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">Test Code <span class="required">*</span></label>
                                            <input type="text" class="form-control" name="test_code" required
                                                placeholder="e.g., AUD-PTA">
                                        </div>
                                    </div>

                                    <div class="row">

                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Category <span class="required">*</span></label>
                                            <select class="form-select" name="category" required>
                                                <option value="">Select Category</option>
                                                <option value="HEARING">Hearing Tests</option>
                                                <option value="BALANCE">Balance Tests</option>
                                                <option value="IMAGING">Imaging</option>
                                                <option value="CULTURE">Culture & Sensitivity</option>
                                                <option value="ALLERGY">Allergy Testing</option>
                                                <option value="SLEEP">Sleep Studies</option>
                                                <option value="ENDOSCOPY">Endoscopy</option>
                                                <option value="OTHER">Other</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Description</label>
                                        <textarea class="form-control" name="description" rows="3"
                                            placeholder="Brief description of the test"></textarea>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Base Cost (KES) <span
                                                    class="required">*</span></label>
                                            <input type="number" class="form-control" name="base_cost" required min="0"
                                                step="0.01" placeholder="0.00">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Duration (Minutes) <span
                                                    class="required">*</span></label>
                                            <input type="number" class="form-control" name="duration_minutes" required
                                                min="1" placeholder="30">
                                        </div>
                                    </div>
                                </div>

                                <!-- Test Requirements -->
                                <div class="form-card">
                                    <div class="form-section-title">
                                        <i class="ri-checkbox-line"></i>
                                        Test Requirements
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <div class="checkbox-card">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                        name="requires_fasting" id="requires_fasting">
                                                    <label class="form-check-label" for="requires_fasting">
                                                        <strong>Requires Fasting</strong>
                                                        <small class="d-block text-muted">Patient must fast before
                                                            test</small>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <div class="checkbox-card">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                        name="requires_appointment" id="requires_appointment" checked>
                                                    <label class="form-check-label" for="requires_appointment">
                                                        <strong>Requires Appointment</strong>
                                                        <small class="d-block text-muted">Must be scheduled in
                                                            advance</small>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <div class="checkbox-card">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                        name="technician_required" id="technician_required">
                                                    <label class="form-check-label" for="technician_required">
                                                        <strong>Technician Required</strong>
                                                        <small class="d-block text-muted">Needs trained technician to
                                                            perform</small>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <div class="checkbox-card">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                        name="requires_equipment" id="requires_equipment">
                                                    <label class="form-check-label" for="requires_equipment">
                                                        <strong>Requires Equipment</strong>
                                                        <small class="d-block text-muted">Special equipment
                                                            needed</small>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Technical Details -->
                                <div class="form-card">
                                    <div class="form-section-title">
                                        <i class="ri-file-list-line"></i>
                                        Technical Details
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Sample Type</label>
                                        <input type="text" class="form-control" name="sample_type"
                                            placeholder="e.g., Blood, Swab, N/A">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Normal Range</label>
                                        <input type="text" class="form-control" name="normal_range"
                                            placeholder="e.g., 20-20000 Hz">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Preparation Instructions</label>
                                        <textarea class="form-control" name="preparation_instructions" rows="4"
                                            placeholder="Instructions for patient preparation before the test"></textarea>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-4">
                                <!-- Equipment Needed -->
                                <div class="form-card">
                                    <div class="form-section-title">
                                        <i class="ri-tools-line"></i>
                                        Equipment Needed
                                    </div>

                                    <div class="info-box mb-3">
                                        <i class="ri-information-line me-2"></i>
                                        <small>Select the equipment required for this test</small>
                                    </div>

                                    <div id="equipmentList" style="max-height: 400px; overflow-y: auto;">
                                        <?php while ($equipment = mysqli_fetch_assoc($equipment_result)): ?>
                                            <div class="equipment-item">
                                                <input type="checkbox" name="equipment_needed[]"
                                                    value="<?php echo $equipment['equipment_id']; ?>"
                                                    id="eq_<?php echo $equipment['equipment_id']; ?>">
                                                <label for="eq_<?php echo $equipment['equipment_id']; ?>"
                                                    class="mb-0 flex-grow-1" style="cursor: pointer;">
                                                    <strong><?php echo htmlspecialchars($equipment['equipment_name']); ?></strong>
                                                    <small
                                                        class="d-block text-muted"><?php echo htmlspecialchars($equipment['equipment_code']); ?></small>
                                                </label>
                                            </div>
                                        <?php endwhile; ?>

                                        <?php if (mysqli_num_rows($equipment_result) == 0): ?>
                                            <div class="text-center text-muted py-4">
                                                <i class="ri-tools-line" style="font-size: 2rem; opacity: 0.3;"></i>
                                                <p class="mt-2">No equipment available</p>
                                                <a href="equipment_management.php" class="btn btn-sm btn-outline-primary">
                                                    Add Equipment
                                                </a>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <!-- Action Buttons -->
                                <div class="form-card">
                                    <button type="submit" class="btn btn-submit w-100 mb-2">
                                        <i class="ri-save-line me-2"></i>Save Test Type
                                    </button>
                                    <a href="test_types.php" class="btn btn-outline-secondary w-100">
                                        <i class="ri-close-line me-2"></i>Cancel
                                    </a>
                                </div>
                            </div>
                        </div>
                    </form>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/js/app.js"></script>

    <script>
        // Form validation
        $('#addTestTypeForm').on('submit', function (e) {
            const testName = $('input[name="test_name"]').val().trim();
            const testCode = $('input[name="test_code"]').val().trim();
            const baseCost = parseFloat($('input[name="base_cost"]').val());

            if (!testName || !testCode) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Missing Information',
                    text: 'Please fill in all required fields'
                });
                return false;
            }

            if (baseCost < 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Cost',
                    text: 'Base cost cannot be negative'
                });
                return false;
            }
        });

        // Auto-generate test code from test name
        $('input[name="test_name"]').on('blur', function () {
            const testName = $(this).val().trim();
            const testCodeInput = $('input[name="test_code"]');

            if (testName && !testCodeInput.val()) {
                const words = testName.split(' ');
                let code = '';

                if (words.length === 1) {
                    code = words[0].substring(0, 3).toUpperCase();
                } else {
                    code = words.map(word => word.charAt(0)).join('').toUpperCase();
                }

                testCodeInput.val(code + '-001');
            }
        });

        // Show/hide equipment section based on checkbox
        $('#requires_equipment').on('change', function () {
            if ($(this).is(':checked')) {
                $('#equipmentList').slideDown();
            }
        });
    </script>
</body>

</html>