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

$user_id = $_SESSION['user_id'];
$is_edit = isset($_GET['id']);
$icd10_id = $is_edit ? (int)$_GET['id'] : 0;

// Fetch existing code if editing
$code_data = null;
if ($is_edit) {
    $sql = "SELECT * FROM icd10_codes WHERE icd10_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $icd10_id);
    $stmt->execute();
    $code_data = $stmt->get_result()->fetch_assoc();
    
    if (!$code_data) {
        $_SESSION['error_message'] = 'ICD-10 code not found';
        header('Location: manage_icd10_codes.php');
        exit();
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $code = strtoupper(trim($_POST['code']));
        $short_description = trim($_POST['short_description']);
        $full_description = trim($_POST['full_description']);
        $category = trim($_POST['category']);
        $chapter = trim($_POST['chapter']);
        $chapter_code = trim($_POST['chapter_code']);
        $is_billable = isset($_POST['is_billable']) ? 1 : 0;
        $is_ent_related = isset($_POST['is_ent_related']) ? 1 : 0;
        $commonly_used = isset($_POST['commonly_used']) ? 1 : 0;
        $synonyms = trim($_POST['synonyms']);
        $notes = trim($_POST['notes']);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if (empty($code) || empty($short_description)) {
            throw new Exception('Code and short description are required');
        }
        
        if ($is_edit) {
            // Update existing code
            $sql = "UPDATE icd10_codes SET 
                    code = ?, short_description = ?, full_description = ?, category = ?,
                    chapter = ?, chapter_code = ?, is_billable = ?, is_ent_related = ?,
                    commonly_used = ?, synonyms = ?, notes = ?, is_active = ?,
                    updated_at = NOW()
                    WHERE icd10_id = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('ssssssiiiisii',
                $code, $short_description, $full_description, $category,
                $chapter, $chapter_code, $is_billable, $is_ent_related,
                $commonly_used, $synonyms, $notes, $is_active, $icd10_id
            );
            
            $success_message = 'ICD-10 code updated successfully';
        } else {
            // Insert new code
            $sql = "INSERT INTO icd10_codes (
                    code, short_description, full_description, category, chapter, chapter_code,
                    is_billable, is_ent_related, commonly_used, synonyms, notes, is_active,
                    created_by, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('ssssssiiiisii',
                $code, $short_description, $full_description, $category, $chapter, $chapter_code,
                $is_billable, $is_ent_related, $commonly_used, $synonyms, $notes, $is_active, $user_id
            );
            
            $success_message = 'ICD-10 code added successfully';
        }
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to save ICD-10 code');
        }
        
        $_SESSION['success_message'] = $success_message;
        header('Location: manage_icd10_codes.php');
        exit();
        
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => ($is_edit ? 'Edit' : 'Add') . ' ICD-10 Code')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .form-section {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .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-label {
            font-weight: 600;
            color: #475569;
            margin-bottom: 0.5rem;
        }
        
        .required::after {
            content: '*';
            color: #ef4444;
            margin-left: 0.25rem;
        }
        
        .form-control, .form-select {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.625rem 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .form-check-input:checked {
            background-color: #3b82f6;
            border-color: #3b82f6;
        }
        
        .checkbox-card {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            border: 2px solid #e2e8f0;
            transition: all 0.2s;
        }
        
        .checkbox-card:hover {
            border-color: #3b82f6;
            background: #f0f9ff;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h4 class="mb-1">
                                        <i class="<?php echo $is_edit ? 'ri-edit-line' : 'ri-add-line'; ?> me-2"></i>
                                        <?php echo $is_edit ? 'Edit' : 'Add'; ?> ICD-10 Code
                                    </h4>
                                    <p class="text-muted mb-0">
                                        <?php echo $is_edit ? 'Update' : 'Create'; ?> diagnosis code information
                                    </p>
                                </div>
                                <a href="manage_icd10_codes.php" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line me-1"></i> Back to Codes
                                </a>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger">
                        <i class="ri-error-warning-line me-2"></i>
                        <?php echo htmlspecialchars($error_message); ?>
                    </div>
                    <?php endif; ?>

                    <form method="POST" id="icd10Form">
                        <!-- Basic Information -->
                        <div class="form-section">
                            <div class="section-title">
                                <i class="ri-information-line"></i>
                                Basic Information
                            </div>
                            
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <label class="form-label required">ICD-10 Code</label>
                                    <input type="text" class="form-control text-uppercase" name="code" 
                                           value="<?php echo $code_data['code'] ?? ''; ?>" 
                                           placeholder="e.g., H65.0" required 
                                           <?php echo $is_edit ? 'readonly' : ''; ?>>
                                    <small class="form-text">Standard ICD-10 format</small>
                                </div>
                                <div class="col-md-9 mb-3">
                                    <label class="form-label required">Short Description</label>
                                    <input type="text" class="form-control" name="short_description" 
                                           value="<?php echo htmlspecialchars($code_data['short_description'] ?? ''); ?>" 
                                           placeholder="Brief description of the diagnosis" required>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Full Description</label>
                                    <textarea class="form-control" name="full_description" rows="3"
                                              placeholder="Complete medical description..."><?php echo htmlspecialchars($code_data['full_description'] ?? ''); ?></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Classification -->
                        <div class="form-section">
                            <div class="section-title">
                                <i class="ri-folders-line"></i>
                                Classification
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Category</label>
                                    <select class="form-select" name="category">
                                        <option value="">Select Category</option>
                                        <option value="Ear Diseases" <?php echo ($code_data['category'] ?? '') == 'Ear Diseases' ? 'selected' : ''; ?>>Ear Diseases</option>
                                        <option value="Nose & Sinus Diseases" <?php echo ($code_data['category'] ?? '') == 'Nose & Sinus Diseases' ? 'selected' : ''; ?>>Nose & Sinus Diseases</option>
                                        <option value="Throat Diseases" <?php echo ($code_data['category'] ?? '') == 'Throat Diseases' ? 'selected' : ''; ?>>Throat Diseases</option>
                                        <option value="Head & Neck" <?php echo ($code_data['category'] ?? '') == 'Head & Neck' ? 'selected' : ''; ?>>Head & Neck</option>
                                        <option value="Respiratory" <?php echo ($code_data['category'] ?? '') == 'Respiratory' ? 'selected' : ''; ?>>Respiratory</option>
                                        <option value="Other" <?php echo ($code_data['category'] ?? '') == 'Other' ? 'selected' : ''; ?>>Other</option>
                                    </select>
                                </div>
                                <div class="col-md-5 mb-3">
                                    <label class="form-label">Chapter</label>
                                    <input type="text" class="form-control" name="chapter" 
                                           value="<?php echo htmlspecialchars($code_data['chapter'] ?? ''); ?>" 
                                           placeholder="e.g., Diseases of the ear and mastoid process">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">Chapter Code</label>
                                    <input type="text" class="form-control" name="chapter_code" 
                                           value="<?php echo htmlspecialchars($code_data['chapter_code'] ?? ''); ?>" 
                                           placeholder="e.g., H60-H95">
                                </div>
                            </div>
                        </div>

                        <!-- Properties -->
                        <div class="form-section">
                            <div class="section-title">
                                <i class="ri-settings-3-line"></i>
                                Code Properties
                            </div>
                            
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <div class="checkbox-card">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="is_billable" 
                                                   <?php echo ($code_data['is_billable'] ?? 1) ? 'checked' : ''; ?>>
                                            <label class="form-check-label">
                                                <strong>Billable</strong>
                                                <small class="d-block text-muted">Can be used for billing</small>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <div class="checkbox-card">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="is_ent_related" 
                                                   <?php echo ($code_data['is_ent_related'] ?? 0) ? 'checked' : ''; ?>>
                                            <label class="form-check-label">
                                                <strong>ENT Specific</strong>
                                                <small class="d-block text-muted">ENT-related diagnosis</small>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <div class="checkbox-card">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="commonly_used" 
                                                   <?php echo ($code_data['commonly_used'] ?? 0) ? 'checked' : ''; ?>>
                                            <label class="form-check-label">
                                                <strong>Commonly Used</strong>
                                                <small class="d-block text-muted">Frequently used code</small>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <div class="checkbox-card">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="is_active" 
                                                   <?php echo ($code_data['is_active'] ?? 1) ? 'checked' : ''; ?>>
                                            <label class="form-check-label">
                                                <strong>Active</strong>
                                                <small class="d-block text-muted">Available for use</small>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Additional Information -->
                        <div class="form-section">
                            <div class="section-title">
                                <i class="ri-file-text-line"></i>
                                Additional Information
                            </div>
                            
                            <div class="row">
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Synonyms</label>
                                    <input type="text" class="form-control" name="synonyms" 
                                           value="<?php echo htmlspecialchars($code_data['synonyms'] ?? ''); ?>" 
                                           placeholder="Alternative names or search terms (comma-separated)">
                                    <small class="form-text">Help improve searchability</small>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Clinical Notes</label>
                                    <textarea class="form-control" name="notes" rows="3"
                                              placeholder="Additional clinical notes, usage guidelines, or important information..."><?php echo htmlspecialchars($code_data['notes'] ?? ''); ?></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Form Actions -->
                        <div class="form-section">
                            <div class="d-flex gap-2">
                                <button type="submit" class="btn btn-success">
                                    <i class="<?php echo $is_edit ? 'ri-save-line' : 'ri-add-line'; ?> me-1"></i>
                                    <?php echo $is_edit ? 'Update' : 'Add'; ?> Code
                                </button>
                                <a href="manage_icd10_codes.php" class="btn btn-secondary">
                                    <i class="ri-close-line me-1"></i> Cancel
                                </a>
                            </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>
    document.getElementById('icd10Form').addEventListener('submit', function(e) {
        const code = document.querySelector('[name="code"]').value.trim();
        const shortDesc = document.querySelector('[name="short_description"]').value.trim();
        
        if (!code || !shortDesc) {
            e.preventDefault();
            Swal.fire('Error', 'Code and short description are required', 'error');
            return false;
        }
        
        Swal.fire({
            title: 'Saving...',
            html: 'Please wait',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
    });
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>