<?php
require_once '../../config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $dnszone = trim($_POST['dnszone']);
    $type = trim($_POST['type']);
    $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 0;
    $last_verified = trim($_POST['last_verified']);

    if (empty($name) || empty($dnszone) || empty($type)) {
        echo json_encode(['success' => 0, 'message' => 'All fields are required.']);
        exit;
    }

    // Validate and format the last_verified date
    $date = DateTime::createFromFormat('m/d/Y', $last_verified);
    if (!$date || $date->format('m/d/Y') !== $last_verified) {
        echo json_encode(['success' => 0, 'message' => 'Invalid date format. Use MM/DD/YYYY.']);
        exit;
    }

    // Convert date to MySQL format (YYYY-MM-DD)
    $last_verified = $date->format('Y-m-d');

    // Sanitize variables to prevent SQL injection
    $name = $db->escape_string($name);
    $dnszone = $db->escape_string($dnszone);
    $type = $db->escape_string($type);
    $is_active = (int)$is_active;
    $last_verified = $db->escape_string($last_verified);

    // Check if the record already exists
    $check_query = "SELECT id FROM evp_dnsbl WHERE dnszone = '$dnszone'";
    $check_result = $db->select($check_query);

    if ($check_result && $check_result->num_rows > 0) {
        // Update existing record
        $update_query = "UPDATE evp_dnsbl SET name = '$name', type = '$type', is_active = $is_active, last_verified = '$last_verified' WHERE dnszone = '$dnszone'";
        $update_result = $db->update($update_query);
        if ($update_result === false) {
            echo json_encode(['success' => 0, 'message' => 'Failed to update DNSBL record.']);
            exit;
        }
        echo json_encode(['success' => 1, 'message' => 'DNSBL record updated successfully.']);
    } else {
        // Insert new record
        $insert_query = "INSERT INTO evp_dnsbl (name, dnszone, type, is_active, last_verified) VALUES ('$name', '$dnszone', '$type', $is_active, '$last_verified')";
        $insert_result = $db->insert($insert_query);
        if ($insert_result === false) {
            echo json_encode(['success' => 0, 'message' => 'Failed to add DNSBL record.']);
            exit;
        }
        echo json_encode(['success' => 1, 'message' => 'DNSBL record added successfully.']);
    }
    exit;
}
?>
