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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // 1. Grab the single target GDRG code
    $gdrg_code = isset($_POST['target_gdrg']) ? trim($conn->real_escape_string($_POST['target_gdrg'])) : '';
    
    // 2. Grab the array of ICD-10 codes generated by the JS hidden inputs
    $icd_codes = isset($_POST['icd_codes']) && is_array($_POST['icd_codes']) ? $_POST['icd_codes'] : [];

    // Validate
    if (!empty($gdrg_code)) {
        
        $conn->begin_transaction();
        try {
            // Drop existing mappings so unchecking a box deletes the map properly
            $del_stmt = $conn->prepare("DELETE FROM gdrg_icd_mapping WHERE gdrg_code = ?");
            $del_stmt->bind_param("s", $gdrg_code);
            $del_stmt->execute();
            $del_stmt->close();

            // Insert new selected codes
            if (count($icd_codes) > 0) {
                $stmt = $conn->prepare("INSERT IGNORE INTO gdrg_icd_mapping (gdrg_code, icd10_code, is_active) VALUES (?, ?, 1)");
                foreach ($icd_codes as $icd) {
                    $clean_icd = trim($conn->real_escape_string($icd));
                    $stmt->bind_param("ss", $gdrg_code, $clean_icd);
                    $stmt->execute();
                }
                $stmt->close();
            }

            $conn->commit();
            header("Location: ../../../views/system_setup/systemSetup.php?cat=facility&page=gdrg/addMapping.php&status=success");
            exit();

        } catch (Exception $e) {
            $conn->rollback();
            header("Location: ../../../views/system_setup/systemSetup.php?cat=facility&page=gdrg/addMapping.php&status=error");
            exit();
        }
    } else {
        header("Location: ../../../views/system_setup/systemSetup.php?cat=facility&page=gdrg/addMapping.php&status=error");
        exit();
    }
} else {
    echo "Direct access denied.";
}
?>