<?php
session_start();
// Connect to database
require_once __DIR__ . '/../../includes/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // 1. Clean and Sanitize Inputs
    $code = isset($_POST['code']) ? strtoupper(trim($conn->real_escape_string($_POST['code']))) : '';
    $description = isset($_POST['description']) ? trim($conn->real_escape_string($_POST['description'])) : '';

    if (!empty($code) && !empty($description)) {
        try {
            // Check if code already exists to prevent fatal primary key errors
            $check_stmt = $conn->prepare("SELECT code FROM icd10_dictionary WHERE code = ?");
            $check_stmt->bind_param("s", $code);
            $check_stmt->execute();
            $check_res = $check_stmt->get_result();

            if ($check_res->num_rows > 0) {
                // Code already exists
                header("Location: ../../../views/system_setup/systemSetup.php?cat=facility&page=gdrg/addIcd.php&status=error");
                exit();
            }

            // Insert into the dictionary
            $stmt = $conn->prepare("INSERT INTO icd10_dictionary (code, description) VALUES (?, ?)");
            $stmt->bind_param("ss", $code, $description);
            
            if ($stmt->execute()) {
                // Success! Redirect to trigger the modal
                header("Location: ../../../views/system_setup/systemSetup.php?cat=facility&page=gdrg/addIcd.php&status=success");
                exit();
            } else {
                throw new Exception("Insert failed");
            }

        } catch (Exception $e) {
            // Fallback error redirection
            header("Location: ../../../views/system_setup/systemSetup.php?cat=facility&page=gdrg/addIcd.php&status=error");
            exit();
        }
    } else {
        // Missing fields
        header("Location: ../../../views/system_setup/systemSetup.php?cat=facility&page=gdrg/addIcd.php&status=error");
        exit();
    }
} else {
    echo "Direct access denied.";
}
?>