<?php
declare(strict_types=1);
require_once __DIR__ . '/db/config.php';
session_start();

if (empty($_SESSION['is_admin'])) {
    header('Location: index.php');
    exit;
}

$action = $_POST['action'] ?? '';

if ($action === 'add') {
    $title = $_POST['title'] ?? '';
    $artist = $_POST['artist'] ?? '';
    if ($title && $artist) {
        $stmt = db()->prepare("INSERT INTO songs (title, artist) VALUES (?, ?)");
        $stmt->execute([$title, $artist]);
    }
} elseif ($action === 'delete') {
    $id = $_POST['id'] ?? '';
    if ($id) {
        $stmt = db()->prepare("DELETE FROM songs WHERE id = ?");
        $stmt->execute([$id]);
    }
} elseif ($action === 'toggle_active') {
    $id = $_POST['id'] ?? '';
    if ($id) {
        // First, check the current status
        $stmt = db()->prepare("SELECT is_active FROM songs WHERE id = ?");
        $stmt->execute([$id]);
        $current = $stmt->fetchColumn();
        
        if ($current) {
            // Deactivate it
            $stmt = db()->prepare("UPDATE songs SET is_active = 0 WHERE id = ?");
            $stmt->execute([$id]);
        } else {
            // Activate this one and deactivate ALL others
            $stmt = db()->prepare("UPDATE songs SET is_active = 0");
            $stmt->execute();
            $stmt = db()->prepare("UPDATE songs SET is_active = 1 WHERE id = ?");
            $stmt->execute([$id]);
        }
    }
}

header('Location: index.php?admin=lili');
exit;