<?php
// File: /admin/paintings_handler.php
session_start();
require_once __DIR__ . '/../db.php';

// Security: Only admins can access this script
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("Access Denied.");
}

// --- HANDLE TOGGLE FEATURED STATUS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_featured'])) {
    $painting_id = filter_var($_POST['painting_id'], FILTER_SANITIZE_NUMBER_INT);
    $current_status = filter_var($_POST['current_status'], FILTER_SANITIZE_NUMBER_INT);

    $new_status = $current_status == 1 ? 0 : 1;

    try {
        $stmt = $conn->prepare("UPDATE paintings SET is_featured = ? WHERE id = ?");
        $stmt->bind_param("ii", $new_status, $painting_id);
        $stmt->execute();
        $stmt->close();
        header("Location: paintings.php?status=featured_toggled");
        exit();
    } catch (mysqli_sql_exception $e) {
        // Catch any database errors
        error_log("Paintings Handler (Toggle) Error: " . $e->getMessage());
        header("Location: paintings.php?error=db_error");
        exit();
    }
}


// --- HANDLE DELETE PAINTING ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_painting'])) {
    $painting_id = filter_var($_POST['painting_id'], FILTER_SANITIZE_NUMBER_INT);

    try {
        // Optional: Add logic here to delete the actual image file from the server
        // to save space.
        
        $stmt = $conn->prepare("DELETE FROM paintings WHERE id = ?");
        $stmt->bind_param("i", $painting_id);
        $stmt->execute();
        $stmt->close();
        
        header("Location: paintings.php?status=deleted");
        exit();

    } catch (mysqli_sql_exception $e) {
        // --- ⭐️ THIS IS THE FIX ⭐️ ---
        // Catch the database exception
        
        // MySQL error code 1451 is "Cannot delete or update a parent row: a foreign key constraint fails"
        if ($e->getCode() == 1451) {
            // This is the error we expected. Redirect with a clear message.
            header("Location: paintings.php?error=constraint");
        } else {
            // It was a different database error
            error_log("Paintings Handler (Delete) Error: " . $e->getMessage());
            header("Location: paintings.php?error=db_error");
        }
        exit();
        // --- END OF FIX ---
    }
}

// Default redirect if no action is matched
header("Location: paintings.php");
exit();
?>