<?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'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $procedure_code = $_POST['procedure_code'];
    $procedure_name = $_POST['procedure_name'];
    $category = $_POST['category'];
    $subcategory = $_POST['subcategory'] ?? null;
    $description = $_POST['description'] ?? null;
    $standard_cost = $_POST['standard_cost'];
    $duration_minutes = $_POST['duration_minutes'];
    $requires_anesthesia = isset($_POST['requires_anesthesia']) ? 1 : 0;
    $anesthesia_type = $_POST['anesthesia_type'] ?? null;
    $requires_consent = isset($_POST['requires_consent']) ? 1 : 0;
    $pre_procedure_instructions = $_POST['pre_procedure_instructions'] ?? null;
    $post_procedure_instructions = $_POST['post_procedure_instructions'] ?? null;
    $room_type_required = $_POST['room_type_required'] ?? null;
    
    // Check if procedure code already exists
    $check_sql = "SELECT procedure_type_id FROM ent_procedure_types WHERE procedure_code = ?";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param('s', $procedure_code);
    $stmt->execute();
    $check_result = $stmt->get_result();
    
    if ($check_result->num_rows > 0) {
        $error_message = "Procedure code already exists!";
    } else {
        // Insert new procedure type
        $insert_sql = "INSERT INTO ent_procedure_types 
            (procedure_code, procedure_name, category, subcategory, description, 
             standard_cost, duration_minutes, requires_anesthesia, anesthesia_type, 
             requires_consent, pre_procedure_instructions, post_procedure_instructions, 
             room_type_required, is_active, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())";
        
        $stmt = $conn->prepare($insert_sql);
        $stmt->bind_param('ssssdisssssss', 
            $procedure_code, $procedure_name, $category, $subcategory, $description,
            $standard_cost, $duration_minutes, $requires_anesthesia, $anesthesia_type,
            $requires_consent, $pre_procedure_instructions, $post_procedure_instructions,
            $room_type_required
        );
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Procedure type added successfully!";
            header("Location: procedure_types.php");
            exit();
        } else {
            $error_message = "Error adding procedure type: " . $conn->error;
        }
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Procedure Type')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .profile-header {
            background: linear-gradient(135deg, #2d7a2d 0%, #26a69a 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .info-card h5 {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .form-label {
            font-weight: 600;
            color: #475569;
            margin-bottom: 0.5rem;
        }
        
        .required::after {
            content: " *";
            color: #dc2626;
        }
        
        .btn-primary-custom {
            background: #2d7a2d;
            color: white;
            border: none;
        }
        
        .btn-primary-custom:hover {
            background: #245d24;
            color: white;
        }
        
        .form-check-input:checked {
            background-color: #2d7a2d;
            border-color: #2d7a2d;
        }
    </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 Procedure 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="list_procedures.php">Procedures</a></li>
                                        <li class="breadcrumb-item"><a href="procedure_types.php">Procedure Types</a></li>
                                        <li class="breadcrumb-item active">Add New</li>
                                    </ol>
                                </div>
                            </div>
                        </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; ?>

                    <!-- Add Form -->
                    <form method="POST" action="" id="addProcedureTypeForm">
                        <div class="row">
                            <div class="col-lg-8">
                                <!-- Basic Information -->
                                <div class="info-card">
                                    <h5><i class="ri-file-text-line me-2"></i>Basic Information</h5>
                                    
                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label required">Procedure Code</label>
                                            <input type="text" name="procedure_code" class="form-control" 
                                                   placeholder="e.g., DIAG001" required>
                                        </div>
                                        
                                        <div class="col-md-8 mb-3">
                                            <label class="form-label required">Procedure Name</label>
                                            <input type="text" name="procedure_name" class="form-control" 
                                                   placeholder="e.g., Otoscopy Examination" required>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label required">Category</label>
                                            <select name="category" class="form-select" required>
                                                <option value="">Select Category</option>
                                                <option value="DIAGNOSTIC">Diagnostic</option>
                                                <option value="THERAPEUTIC">Therapeutic</option>
                                                <option value="SURGICAL">Surgical</option>
                                                <option value="AUDIOLOGICAL">Audiological</option>
                                                <option value="ENDOSCOPIC">Endoscopic</option>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Subcategory</label>
                                            <input type="text" name="subcategory" class="form-control" 
                                                   placeholder="e.g., Otology, Rhinology, Laryngology">
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Description</label>
                                        <textarea name="description" class="form-control" rows="3" 
                                                  placeholder="Brief description of the procedure..."></textarea>
                                    </div>
                                </div>

                                <!-- Procedure Details -->
                                <div class="info-card">
                                    <h5><i class="ri-information-line me-2"></i>Procedure Details</h5>
                                    
                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label required">Standard Cost (KES)</label>
                                            <input type="number" name="standard_cost" class="form-control" 
                                                   step="0.01" min="0" placeholder="0.00" required>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label required">Duration (Minutes)</label>
                                            <input type="number" name="duration_minutes" class="form-control" 
                                                   min="1" placeholder="30" required>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">Room Type Required</label>
                                            <input type="text" name="room_type_required" class="form-control" 
                                                   placeholder="e.g., Theatre, Consultation Room">
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" 
                                                       name="requires_anesthesia" id="requires_anesthesia">
                                                <label class="form-check-label" for="requires_anesthesia">
                                                    Requires Anesthesia
                                                </label>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6 mb-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" 
                                                       name="requires_consent" id="requires_consent">
                                                <label class="form-check-label" for="requires_consent">
                                                    Requires Patient Consent
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row" id="anesthesia_type_section" style="display: none;">
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Anesthesia Type</label>
                                            <select name="anesthesia_type" class="form-select">
                                                <option value="">Select Anesthesia Type</option>
                                                <option value="LOCAL">Local</option>
                                                <option value="SEDATION">Sedation</option>
                                                <option value="GENERAL">General</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <!-- Instructions -->
                                <div class="info-card">
                                    <h5><i class="ri-file-list-3-line me-2"></i>Procedure Instructions</h5>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Pre-Procedure Instructions</label>
                                        <textarea name="pre_procedure_instructions" class="form-control" rows="4" 
                                                  placeholder="Instructions for patients before the procedure..."></textarea>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Post-Procedure Instructions</label>
                                        <textarea name="post_procedure_instructions" class="form-control" rows="4" 
                                                  placeholder="Instructions for patients after the procedure..."></textarea>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-lg-4">
                                <!-- Help Information -->
                                <div class="info-card">
                                    <h5><i class="ri-information-line me-2"></i>Help & Guidelines</h5>
                                    
                                    <div class="alert alert-info">
                                        <h6 class="alert-heading">Procedure Code</h6>
                                        <p class="mb-0 small">Use a unique code format. Examples: DIAG001, SURG015, THER003</p>
                                    </div>
                                    
                                    <div class="alert alert-warning">
                                        <h6 class="alert-heading">Categories</h6>
                                        <ul class="mb-0 small">
                                            <li><strong>DIAGNOSTIC:</strong> Examination procedures</li>
                                            <li><strong>THERAPEUTIC:</strong> Treatment procedures</li>
                                            <li><strong>SURGICAL:</strong> Surgical operations</li>
                                            <li><strong>AUDIOLOGICAL:</strong> Hearing tests</li>
                                            <li><strong>ENDOSCOPIC:</strong> Scope examinations</li>
                                        </ul>
                                    </div>
                                    
                                    <div class="alert alert-success">
                                        <h6 class="alert-heading">Subcategories</h6>
                                        <p class="mb-0 small">Common ENT subcategories: Otology (ear), Rhinology (nose), Laryngology (throat)</p>
                                    </div>
                                </div>
                                
                                <!-- Action Buttons -->
                                <div class="info-card">
                                    <div class="d-grid gap-2">
                                        <button type="submit" class="btn btn-primary-custom btn-lg">
                                            <i class="ri-save-line me-2"></i>Save Procedure Type
                                        </button>
                                        <a href="procedure_types.php" class="btn btn-light btn-lg">
                                            <i class="ri-close-line me-2"></i>Cancel
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            // Show/hide anesthesia type based on checkbox
            $('#requires_anesthesia').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#anesthesia_type_section').show();
                } else {
                    $('#anesthesia_type_section').hide();
                    $('select[name="anesthesia_type"]').val('');
                }
            });
            
            // Form validation
            $('#addProcedureTypeForm').on('submit', function(e) {
                const cost = $('input[name="standard_cost"]').val();
                const duration = $('input[name="duration_minutes"]').val();
                
                if (parseFloat(cost) <= 0) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid Cost',
                        text: 'Standard cost must be greater than 0'
                    });
                    return false;
                }
                
                if (parseInt(duration) <= 0) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid Duration',
                        text: 'Duration must be greater than 0 minutes'
                    });
                    return false;
                }
            });
        });
    </script>
</body>
</html>
<?php $conn->close(); ?>