<?php
session_start();
ini_set('display_errors', 0);
header('Content-Type: application/json');

require_once __DIR__ . '/../../includes/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    $staff_id = isset($_SESSION['staff_id']) ? (int)$_SESSION['staff_id'] : 1; 

    try {
        // 1. Sanitize and Extract Inputs
        $insurance_type_id = isset($_POST['insurance_type_id']) ? (int)$_POST['insurance_type_id'] : 0;
        $service_id = isset($_POST['service_id']) ? (int)$_POST['service_id'] : 0;
        $tariff_amount = isset($_POST['tariff_amount']) ? (float)$_POST['tariff_amount'] : 0.00;
        $is_copay_required = isset($_POST['is_copay_required']) ? (int)$_POST['is_copay_required'] : 0;
        $copay_amount_adult = isset($_POST['copay_amount_adult']) ? (float)$_POST['copay_amount_adult'] : 0.00;
        $copay_amount_child = isset($_POST['copay_amount_child']) ? (float)$_POST['copay_amount_child'] : 0.00;

        // Validation
        if ($insurance_type_id === 0 || $service_id === 0) {
            throw new Exception("Provider and Service are required fields.");
        }

        // If copay is off, force amounts to 0
        if ($is_copay_required === 0) {
            $copay_amount_adult = 0.00;
            $copay_amount_child = 0.00;
        }

        $conn->begin_transaction();

        // 2. Check if mapping already exists
        $check_sql = "SELECT id, tariff_amount, is_copay_required, copay_amount_adult, copay_amount_child 
                      FROM service_corporate_tariffs 
                      WHERE insurance_type_id = ? AND service_id = ?";
        $stmt_check = $conn->prepare($check_sql);
        $stmt_check->bind_param("ii", $insurance_type_id, $service_id);
        $stmt_check->execute();
        $res = $stmt_check->get_result();

        $old_data = null;
        $action_type = '';

        if ($res && $res->num_rows > 0) {
            // MAPPING EXISTS -> UPDATE IT
            $old_data = $res->fetch_assoc();
            $action_type = 'UPDATE_MAPPING';

            $update_sql = "UPDATE service_corporate_tariffs 
                           SET tariff_amount = ?, is_copay_required = ?, copay_amount_adult = ?, copay_amount_child = ? 
                           WHERE insurance_type_id = ? AND service_id = ?";
            $stmt_upd = $conn->prepare($update_sql);
            $stmt_upd->bind_param("diddii", $tariff_amount, $is_copay_required, $copay_amount_adult, $copay_amount_child, $insurance_type_id, $service_id);
            if (!$stmt_upd->execute()) throw new Exception("Update Failed: " . $stmt_upd->error);

        } else {
            // NEW MAPPING -> INSERT IT
            $action_type = 'INSERT_MAPPING';
            $insert_sql = "INSERT INTO service_corporate_tariffs 
                           (insurance_type_id, service_id, tariff_amount, is_copay_required, copay_amount_adult, copay_amount_child) 
                           VALUES (?, ?, ?, ?, ?, ?)";
            $stmt_ins = $conn->prepare($insert_sql);
            $stmt_ins->bind_param("iididd", $insurance_type_id, $service_id, $tariff_amount, $is_copay_required, $copay_amount_adult, $copay_amount_child);
            if (!$stmt_ins->execute()) throw new Exception("Insert Failed: " . $stmt_ins->error);
        }

        // 3. Write to Audit Trail (FIXED: record_id must be an INT, not a string)
        $new_data = [
            'insurance_type_id' => $insurance_type_id,
            'service_id' => $service_id,
            'tariff_amount' => $tariff_amount,
            'is_copay_required' => $is_copay_required,
            'copay_amount_adult' => $copay_amount_adult,
            'copay_amount_child' => $copay_amount_child
        ];

        $old_json = $old_data ? json_encode($old_data) : null;
        $new_json = json_encode($new_data);
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';

        $audit_sql = "INSERT INTO system_audit_logs (staff_id, action_type, table_name, record_id, old_values, new_values, ip_address) 
                      VALUES (?, ?, 'service_corporate_tariffs', ?, ?, ?, ?)";
        
        $audit_stmt = $conn->prepare($audit_sql);
        // 'iissss' -> int, string, int (service_id), string, string, string
        $audit_stmt->bind_param("isisss", $staff_id, $action_type, $service_id, $old_json, $new_json, $ip_address);
        
        // Don't crash the whole save if just the audit log fails, but log it.
        $audit_stmt->execute(); 

        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => 'Tariff mapping saved successfully.']);

    } catch (Throwable $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid Request Method']);
}
?>