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

if (!isLoggedIn()) {
    redirectWithMessage(APP_URL . '/login.php', 'Unauthorized', 'error');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirectWithMessage(APP_URL . '/admin/discounts.php', 'Invalid request', 'error');
}

$id = $_POST['id'] ?? null;
$name = escape($_POST['name'] ?? '');
$type = escape($_POST['type'] ?? 'percent');
$value = (float)($_POST['value'] ?? 0);
$valid_from = escape($_POST['valid_from'] ?? '');
$valid_to = escape($_POST['valid_to'] ?? '');
$active = (int)($_POST['active'] ?? 1);

if (empty($name)) {
    redirectWithMessage(APP_URL . '/admin/discounts.php', 'Numele reducerii este obligatoriu', 'error');
}

if ($id) {
    $id = (int)$id;
    $query = "UPDATE discounts SET name='$name', type='$type', value=$value, valid_from='$valid_from', valid_to='$valid_to', active=$active WHERE id=$id";
    
    if ($db->query($query)) {
        auditLog('update', 'discounts', $id, $name, [], ['type' => $type, 'value' => $value]);
        redirectWithMessage(APP_URL . '/admin/discounts.php', 'Reducere actualizată cu succes', 'success');
    } else {
        redirectWithMessage(APP_URL . '/admin/discounts.php', 'Eroare: ' . $db->error, 'error');
    }
} else {
    $query = "INSERT INTO discounts (name, type, value, valid_from, valid_to, active) VALUES ('$name', '$type', $value, '$valid_from', '$valid_to', $active)";
    
    if ($db->query($query)) {
        $discount_id = $db->insert_id;
        auditLog('create', 'discounts', $discount_id, $name, [], ['type' => $type, 'value' => $value]);
        redirectWithMessage(APP_URL . '/admin/discounts.php', 'Reducere adăugată cu succes', 'success');
    } else {
        redirectWithMessage(APP_URL . '/admin/discounts.php', 'Eroare: ' . $db->error, 'error');
    }
}
?>
