getConnection(); if (empty($_POST['production_id']) || empty($_POST['photo_type'])) { throw new Exception("Dati mancanti"); } $production_id = (int)$_POST['production_id']; $type = $_POST['photo_type']; $param_position = isset($_POST['param_position']) && $_POST['param_position'] !== '' ? (int)$_POST['param_position'] : null; if (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) { throw new Exception("Nessuna foto valida caricata"); } // Estensione $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION)); if ($ext === '') { $ext = "jpg"; } // Directory foto $photosDir = __DIR__ . "/photos/"; if (!is_dir($photosDir)) { mkdir($photosDir, 0777, true); } /** * Se è una foto di parametri macchina con posizione: * - deve esistere UNA sola foto per (production_id, type, param_position) * - quindi prima eliminiamo eventuali foto precedenti (file + record DB) */ if ($type === 'parametri_macchina' && $param_position !== null) { // Leggo eventuali foto già presenti per questa combinazione $stmtOld = $pdo->prepare(" SELECT id, filename FROM production_photos WHERE production_id = :pid AND photo_type = :ptype AND param_position = :pos "); $stmtOld->execute([ ':pid' => $production_id, ':ptype' => $type, ':pos' => $param_position ]); $oldPhotos = $stmtOld->fetchAll(PDO::FETCH_ASSOC); // Cancello i file fisici se esistono foreach ($oldPhotos as $old) { if (!empty($old['filename'])) { $oldPath = $photosDir . $old['filename']; if (is_file($oldPath)) { @unlink($oldPath); } } } // Cancello i record dal DB if (!empty($oldPhotos)) { $stmtDel = $pdo->prepare(" DELETE FROM production_photos WHERE production_id = :pid AND photo_type = :ptype AND param_position = :pos "); $stmtDel->execute([ ':pid' => $production_id, ':ptype' => $type, ':pos' => $param_position ]); } } // Primo insert (filename vuoto) $stmt = $pdo->prepare(" INSERT INTO production_photos (production_id, photo_type, filename, param_position) VALUES (:pid, :ptype, '', :pos) "); $stmt->execute([ ':pid' => $production_id, ':ptype' => $type, ':pos' => $param_position ]); $photo_id = $pdo->lastInsertId(); $timestamp = time(); // Nome file finale $filename = "{$production_id}-{$photo_id}-{$timestamp}.{$ext}"; $filepath = $photosDir . $filename; // Salvataggio file if (!move_uploaded_file($_FILES['photo']['tmp_name'], $filepath)) { throw new Exception("Errore salvataggio file"); } // Aggiorna filename nel DB $stmt = $pdo->prepare(" UPDATE production_photos SET filename = :fn WHERE id = :id "); $stmt->execute([ ':fn' => $filename, ':id' => $photo_id ]); echo json_encode(["success" => true]); } catch (Exception $e) { echo json_encode([ "success" => false, "message" => $e->getMessage() ]); }