<?php
include 'auth.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['id'])) {
require_permission('offers_add');
} else {
require_permission('offers_edit');
}
$id = $_POST['id'];
$title = $_POST['title'];
$description = $_POST['description'];
$type = $_POST['type'];
$car_id = !empty($_POST['car_id']) ? $_POST['car_id'] : null;
$discount_price = !empty($_POST['discount_price']) ? $_POST['discount_price'] : null;
$current_image = $_POST['current_image'] ?? '';
$image_name = $current_image;
// Image Upload
if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
$upload_dir = '../uploads/offers/';
$image_name = uniqid() . '-' . basename($_FILES['image']['name']);
$target_file = $upload_dir . $image_name;
if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
if (!empty($current_image) && file_exists($upload_dir . $current_image)) {
unlink($upload_dir . $current_image);
}
} else {
header("Location: offers.php?error=Failed to upload image");
exit();
}
}
if (empty($id)) {
// INSERT
$sql = "INSERT INTO offers (title, description, type, car_id, discount_price, image) VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssids", $title, $description, $type, $car_id, $discount_price, $image_name);
} else {
// UPDATE
$sql = "UPDATE offers SET title=?, description=?, type=?, car_id=?, discount_price=?, image=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssidsi", $title, $description, $type, $car_id, $discount_price, $image_name, $id);
}
if ($stmt->execute()) {
header("Location: offers.php?success=تم حفظ العرض بنجاح");
} else {
header("Location: offers.php?error=حدث خطأ: " . $stmt->error);
}
$stmt->close();
$conn->close();
} else {
header("Location: offers.php");
exit();
}
?>