74 lines
2.6 KiB
PHP
74 lines
2.6 KiB
PHP
<?php
|
|
// favourite_toggle.php — Aggiunge/rimuove un salone dai preferiti (AJAX, JSON)
|
|
// Chiamato dai cuori .js-fav in search.php, search-map.php, salon.php
|
|
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
|
|
// Risponde SEMPRE JSON: lo impostiamo subito, prima di qualsiasi output,
|
|
// così il JS lato client può fare .json() senza sorprese.
|
|
header('Content-Type: application/json');
|
|
|
|
// Connessione DB (stessa classe dell'area admin)
|
|
require_once(__DIR__ . '/userarea/class/db-functions.php');
|
|
$pdo = DBHandlerSelect::getInstance()->getConnection();
|
|
|
|
// --- 1. Utente loggato? Se no, segnaliamo al client di aprire la modale ---
|
|
// Usiamo need_login come "codice" che il JS riconosce per mostrare l'invito
|
|
// a registrarsi, invece di un errore generico.
|
|
if (empty($_SESSION['iduserlogin'])) {
|
|
echo json_encode(['ok' => false, 'need_login' => true]);
|
|
exit;
|
|
}
|
|
|
|
// --- 2. Accettiamo solo POST (le azioni che modificano dati non vanno in GET) ---
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
echo json_encode(['ok' => false, 'error' => 'method_not_allowed']);
|
|
exit;
|
|
}
|
|
|
|
$user_id = (int)$_SESSION['iduserlogin'];
|
|
$shop_id = (int)($_POST['shop_id'] ?? 0);
|
|
|
|
if ($shop_id <= 0) {
|
|
echo json_encode(['ok' => false, 'error' => 'invalid_shop']);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
// --- 3. Il salone esiste ed è attivo? Evita preferiti "fantasma" ---
|
|
$chk = $pdo->prepare("SELECT id FROM shops WHERE id = ? AND active = 1");
|
|
$chk->execute([$shop_id]);
|
|
if (!$chk->fetch()) {
|
|
echo json_encode(['ok' => false, 'error' => 'shop_not_found']);
|
|
exit;
|
|
}
|
|
|
|
// --- 4. È già tra i preferiti? Decide se aggiungere o togliere ---
|
|
$exists = $pdo->prepare(
|
|
"SELECT id FROM user_favorite_shops WHERE user_id = ? AND shop_id = ?"
|
|
);
|
|
$exists->execute([$user_id, $shop_id]);
|
|
$row = $exists->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if ($row) {
|
|
// Già preferito → rimuovi
|
|
$del = $pdo->prepare("DELETE FROM user_favorite_shops WHERE id = ?");
|
|
$del->execute([$row['id']]);
|
|
echo json_encode(['ok' => true, 'favorite' => false]);
|
|
} else {
|
|
// Non preferito → aggiungi
|
|
$ins = $pdo->prepare(
|
|
"INSERT INTO user_favorite_shops (user_id, shop_id) VALUES (?, ?)"
|
|
);
|
|
$ins->execute([$user_id, $shop_id]);
|
|
echo json_encode(['ok' => true, 'favorite' => true]);
|
|
}
|
|
} catch (Throwable $e) {
|
|
// Non esponiamo il messaggio reale in produzione: logghiamo e basta.
|
|
error_log('favourite_toggle: ' . $e->getMessage());
|
|
echo json_encode(['ok' => false, 'error' => 'server_error']);
|
|
exit;
|
|
}
|