<?php
session_start();
require_once __DIR__ . '/../../includes/db.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // 1. Sanitize Core Service Data
    $service_name = $conn->real_escape_string($_POST['service_name']);
    $department_id = (int)$_POST['department_id'];
    $cash_price_adult = (float)$_POST['cash_price_adult'];
    $cash_price_child = (float)$_POST['cash_price_child'];
    
    $target_age_group = $conn->real_escape_string($_POST['target_age_group']);
    $applicable_gender = $conn->real_escape_string($_POST['applicable_gender']);
    $is_consultation = isset($_POST['is_consultation']) ? 1 : 0;
    
    // 2. Sanitize NHIS Data
    $nhis_covered = isset($_POST['nhis_covered']) ? 1 : 0;
    $gdrg_adult = $conn->real_escape_string($_POST['gdrg_adult_code'] ?? '');
    $tariff_adult = (float)($_POST['tariff_adult'] ?? 0.00);
    $gdrg_child = $conn->real_escape_string($_POST['gdrg_child_code'] ?? '');
    $tariff_child = (float)($_POST['tariff_child'] ?? 0.00);
    
    $is_copay = isset($_POST['is_copay_required']) ? 1 : 0;
    $nhis_copay_adult = (float)($_POST['nhis_copay_adult'] ?? 0.00);
    $nhis_copay_child = (float)($_POST['nhis_copay_child'] ?? 0.00);

    // If no copay is required, zero out the amounts
    if (!$is_copay) {
        $nhis_copay_adult = 0.00;
        $nhis_copay_child = 0.00;
    }

    $conn->begin_transaction();

    try {
        // Insert into service_catalog table
        $insert_service = "INSERT INTO service_catalog (
            department_id, service_name, service_type, is_consultation, 
            target_age_group, applicable_gender, 
            cash_price_adult, cash_price_child, 
            nhis_covered, gdrg_adult_code, tariff_adult, 
            gdrg_child_code, tariff_child, 
            is_copay_required, nhis_copay_adult, nhis_copay_child
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $service_type = $is_consultation ? 'Consultation' : 'Procedure';
        
        $stmt = $conn->prepare($insert_service);
        if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);

        $stmt->bind_param("ississddisdsdidd", 
            $department_id, $service_name, $service_type, $is_consultation, 
            $target_age_group, $applicable_gender, 
            $cash_price_adult, $cash_price_child, 
            $nhis_covered, $gdrg_adult, $tariff_adult, 
            $gdrg_child, $tariff_child, 
            $is_copay, $nhis_copay_adult, $nhis_copay_child
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Error inserting service: " . $stmt->error);
        }
        
        $new_service_id = $stmt->insert_id;

        // 3. Process Corporate Tariffs
        if (isset($_POST['corp_covered']) && is_array($_POST['corp_covered'])) {
            $insert_corp = "INSERT INTO service_corporate_tariffs 
                (service_id, insurance_type_id, tariff_amount, is_copay_required, copay_amount_adult, copay_amount_child) 
                VALUES (?, ?, ?, ?, ?, ?)";
            $stmt_corp = $conn->prepare($insert_corp);
            if (!$stmt_corp) throw new Exception("Prepare corp failed: " . $conn->error);

            foreach ($_POST['corp_covered'] as $ins_id => $value) {
                if ($value == 1) {
                    $ins_id = (int)$ins_id;
                    $tariff = (float)($_POST['corp_tariff'][$ins_id] ?? 0.00);
                    $corp_copay_req = isset($_POST['corp_copay_req'][$ins_id]) ? 1 : 0;
                    $corp_copay_adult = (float)($_POST['corp_copay_adult'][$ins_id] ?? 0.00);
                    $corp_copay_child = (float)($_POST['corp_copay_child'][$ins_id] ?? 0.00);

                    if (!$corp_copay_req) {
                        $corp_copay_adult = 0.00;
                        $corp_copay_child = 0.00;
                    }

                    $stmt_corp->bind_param("iididd", $new_service_id, $ins_id, $tariff, $corp_copay_req, $corp_copay_adult, $corp_copay_child);
                    if(!$stmt_corp->execute()) {
                        throw new Exception("Error inserting corporate tariff: " . $stmt_corp->error);
                    }
                }
            }
        }

        $conn->commit();
        
        // Exact SPA Return Path for Success
        header("Location: ../../../views/system_setup/systemSetup.php?cat=system_setup&page=gdrg/addNewGdrg.php&status=success");
        exit();

    } catch (Exception $e) {
        $conn->rollback();
        // Exact SPA Return Path for Error (Passes the exact message back to the UI)
        $msg = urlencode($e->getMessage());
        header("Location: ../../../views/system_setup/systemSetup.php?cat=system_setup&page=gdrg/addNewGdrg.php&status=error&msg=$msg");
        exit();
    }
} else {
    echo "Invalid Request";
}
?>