<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include 'layouts/main.php';
include 'layouts/dbconn.php';

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

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

// Fetch ICD-10 code details
$icd_code = null;
if ($icd10_id > 0) {
    $sql = "SELECT * FROM icd10_codes WHERE icd10_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $icd10_id);
    $stmt->execute();
    $icd_code = $stmt->get_result()->fetch_assoc();
    
    if (!$icd_code) {
        header('Location: manage_icd10_codes.php');
        exit();
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit ICD-10 Code')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .form-section {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
        }
        
        .form-section-title {
            font-weight: 600;
            color: #2d7a2d;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #26a69a;
        }
        
        .badge-custom {
            padding: 0.5rem 1rem;
            font-size: 0.875rem;
        }
    </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 Header -->
                    <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">
                                    <i class="ri-edit-box-line me-2"></i>Edit ICD-10 Code
                                </h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="manage_icd10_codes.php">ICD-10 Codes</a></li>
                                        <li class="breadcrumb-item active">Edit Code</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="mb-0">Edit ICD-10 Code: <?php echo htmlspecialchars($icd_code['code']); ?></h5>
                                        <a href="manage_icd10_codes.php" class="btn btn-outline-secondary btn-sm">
                                            <i class="ri-arrow-left-line me-1"></i>Back to List
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <form id="editICD10Form">
                                        <input type="hidden" name="icd10_id" value="<?php echo $icd10_id; ?>">
                                        
                                        <!-- Basic Information -->
                                        <div class="form-section">
                                            <h6 class="form-section-title">Basic Information</h6>
                                            <div class="row">
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">ICD-10 Code <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" name="code" 
                                                           value="<?php echo htmlspecialchars($icd_code['code']); ?>" 
                                                           required maxlength="10" placeholder="e.g., H65.0">
                                                    <small class="text-muted">Format: H65.0</small>
                                                </div>
                                                
                                                <div class="col-md-9 mb-3">
                                                    <label class="form-label">Short Description <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" name="short_description" 
                                                           value="<?php echo htmlspecialchars($icd_code['short_description']); ?>" 
                                                           required maxlength="255" placeholder="Brief description">
                                                </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($icd_code['full_description']); ?></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Classification -->
                                        <div class="form-section">
                                            <h6 class="form-section-title">Classification</h6>
                                            <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 ($icd_code['category'] == 'Ear Diseases') ? 'selected' : ''; ?>>Ear Diseases</option>
                                                        <option value="Nose Diseases" <?php echo ($icd_code['category'] == 'Nose Diseases') ? 'selected' : ''; ?>>Nose Diseases</option>
                                                        <option value="Throat Diseases" <?php echo ($icd_code['category'] == 'Throat Diseases') ? 'selected' : ''; ?>>Throat Diseases</option>
                                                        <option value="Neck Diseases" <?php echo ($icd_code['category'] == 'Neck Diseases') ? 'selected' : ''; ?>>Neck Diseases</option>
                                                        <option value="Hearing Disorders" <?php echo ($icd_code['category'] == 'Hearing Disorders') ? 'selected' : ''; ?>>Hearing Disorders</option>
                                                        <option value="Balance Disorders" <?php echo ($icd_code['category'] == 'Balance Disorders') ? 'selected' : ''; ?>>Balance Disorders</option>
                                                        <option value="Sleep Disorders" <?php echo ($icd_code['category'] == 'Sleep Disorders') ? 'selected' : ''; ?>>Sleep Disorders</option>
                                                        <option value="Allergy" <?php echo ($icd_code['category'] == 'Allergy') ? 'selected' : ''; ?>>Allergy</option>
                                                        <option value="Oncology" <?php echo ($icd_code['category'] == 'Oncology') ? 'selected' : ''; ?>>Oncology</option>
                                                        <option value="Trauma" <?php echo ($icd_code['category'] == 'Trauma') ? 'selected' : ''; ?>>Trauma</option>
                                                        <option value="Other" <?php echo ($icd_code['category'] == 'Other') ? 'selected' : ''; ?>>Other</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Chapter</label>
                                                    <input type="text" class="form-control" name="chapter" 
                                                           value="<?php echo htmlspecialchars($icd_code['chapter']); ?>" 
                                                           maxlength="200" placeholder="e.g., Diseases of the ear and mastoid process">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Chapter Code</label>
                                                    <input type="text" class="form-control" name="chapter_code" 
                                                           value="<?php echo htmlspecialchars($icd_code['chapter_code']); ?>" 
                                                           maxlength="10" placeholder="e.g., H60-H95">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Additional Information -->
                                        <div class="form-section">
                                            <h6 class="form-section-title">Additional Information</h6>
                                            <div class="row">
                                                <div class="col-md-12 mb-3">
                                                    <label class="form-label">Synonyms / Alternative Terms</label>
                                                    <textarea class="form-control" name="synonyms" rows="2" 
                                                              placeholder="Alternative names or search terms (comma-separated)"><?php echo htmlspecialchars($icd_code['synonyms']); ?></textarea>
                                                    <small class="text-muted">Enter synonyms separated by commas for easier searching</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, guidelines, or coding tips"><?php echo htmlspecialchars($icd_code['notes']); ?></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Flags and Settings -->
                                        <div class="form-section">
                                            <h6 class="form-section-title">Flags & Settings</h6>
                                            <div class="row">
                                                <div class="col-md-3 mb-3">
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" name="is_billable" 
                                                               id="isBillable" value="1" 
                                                               <?php echo ($icd_code['is_billable'] == 1) ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="isBillable">
                                                            <strong>Billable Code</strong>
                                                            <br><small class="text-muted">Can be used for insurance billing</small>
                                                        </label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" name="is_ent_related" 
                                                               id="isENTRelated" value="1" 
                                                               <?php echo ($icd_code['is_ent_related'] == 1) ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="isENTRelated">
                                                            <strong>ENT-Specific</strong>
                                                            <br><small class="text-muted">ENT specialty diagnosis</small>
                                                        </label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" name="commonly_used" 
                                                               id="commonlyUsed" value="1" 
                                                               <?php echo ($icd_code['commonly_used'] == 1) ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="commonlyUsed">
                                                            <strong>Commonly Used</strong>
                                                            <br><small class="text-muted">Frequently used diagnosis</small>
                                                        </label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" name="is_active" 
                                                               id="isActive" value="1" 
                                                               <?php echo ($icd_code['is_active'] == 1) ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="isActive">
                                                            <strong>Active</strong>
                                                            <br><small class="text-muted">Available for use</small>
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Action Buttons -->
                                        <div class="d-flex justify-content-between mt-4">
                                            <button type="button" class="btn btn-outline-danger" onclick="deleteCode()">
                                                <i class="ri-delete-bin-line me-1"></i>Delete Code
                                            </button>
                                            <div>
                                                <a href="manage_icd10_codes.php" class="btn btn-secondary me-2">
                                                    <i class="ri-close-line me-1"></i>Cancel
                                                </a>
                                                <button type="submit" class="btn btn-success">
                                                    <i class="ri-save-line me-1"></i>Update Code
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </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>
        // Form submission
        $('#editICD10Form').on('submit', function(e) {
            e.preventDefault();

            const formData = new FormData(this);

            Swal.fire({
                title: 'Updating...',
                text: 'Please wait while we update the ICD-10 code',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            $.ajax({
                url: 'ajax/update_icd10_code.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Updated!',
                            text: response.message,
                            showCancelButton: true,
                            confirmButtonText: 'Back to List',
                            cancelButtonText: 'Stay Here'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                window.location.href = 'manage_icd10_codes.php';
                            } else {
                                location.reload();
                            }
                        });
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Update error:', error);
                    Swal.fire('Error', 'Failed to update ICD-10 code. Please try again.', 'error');
                }
            });
        });

        // Delete code
        function deleteCode() {
            Swal.fire({
                title: 'Delete ICD-10 Code?',
                text: 'This action cannot be undone. The code will be permanently removed.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete it',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#d33'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/delete_icd10_code.php',
                        type: 'POST',
                        data: { icd10_id: <?php echo $icd10_id; ?> },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Deleted!',
                                    text: response.message,
                                    timer: 2000
                                }).then(() => {
                                    window.location.href = 'manage_icd10_codes.php';
                                });
                            } else {
                                Swal.fire('Error', response.message, 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Failed to delete code', 'error');
                        }
                    });
                }
            });
        }

        // Unsaved changes warning
        let formChanged = false;
        $('#editICD10Form :input').on('change', function() {
            formChanged = true;
        });

        window.addEventListener('beforeunload', function(e) {
            if (formChanged) {
                e.preventDefault();
                e.returnValue = '';
            }
        });

        // Remove unsaved changes warning on form submit
        $('#editICD10Form').on('submit', function() {
            formChanged = false;
        });
    </script>
</body>
</html>