40097-vm/update_marketing_video_image_v3.php
2026-05-19 01:22:09 +00:00

52 lines
2.0 KiB
PHP

<?php
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
include 'db/config.php';
if (!isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], ['Administrador', 'admin'])) {
echo json_encode(['success' => false, 'error' => 'No autorizado']);
exit();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['foto_producto']) && isset($_POST['id'])) {
$db = db();
$id = $_POST['id'];
if ($_FILES['foto_producto']['error'] == 0) {
$target_dir = "assets/uploads/marketing_images/";
if (!is_dir($target_dir)) {
mkdir($target_dir, 0777, true);
}
$file_extension = pathinfo($_FILES["foto_producto"]["name"], PATHINFO_EXTENSION);
$file_name = uniqid() . '_v3.' . $file_extension;
$target_file = $target_dir . $file_name;
if (move_uploaded_file($_FILES["foto_producto"]["tmp_name"], $target_file)) {
try {
// Opcional: borrar imagen anterior si existe
$stmt_old = $db->prepare("SELECT foto_producto FROM marketing_videos_v3 WHERE id = ?");
$stmt_old->execute([$id]);
$old_photo = $stmt_old->fetchColumn();
if ($old_photo && file_exists($old_photo)) {
unlink($old_photo);
}
$stmt = $db->prepare("UPDATE marketing_videos_v3 SET foto_producto = ? WHERE id = ?");
$stmt->execute([$target_file, $id]);
echo json_encode(['success' => true, 'path' => $target_file]);
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
} else {
echo json_encode(['success' => false, 'error' => 'Error al mover el archivo']);
}
} else {
echo json_encode(['success' => false, 'error' => 'Error en la subida: ' . $_FILES['foto_producto']['error']]);
}
} else {
echo json_encode(['success' => false, 'error' => 'Solicitud inválida']);
}
?>