<?php
session_start();
header('Content-Type: application/json');

try {
    // Conexão com o banco de dados SQLite
    $db = new PDO('sqlite:../ibo_panel.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Captura o input JSON enviado pelo Fetch API
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? 'view';

    switch ($action) {
        
        case 'view':
            $stmt = $db->query("SELECT * FROM playlist ORDER BY id DESC");
            $playlistRecords = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'data' => $playlistRecords]);
            break;

        case 'get_dns_options':
            $stmt = $db->query("SELECT id, title FROM dns ORDER BY title ASC");
            $dnsOptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'data' => $dnsOptions]);
            break;

        case 'add':
            $dns_id      = trim($input['dns_id'] ?? '');
            $mac_address = trim($input['mac_address'] ?? '');
            $username    = trim($input['username'] ?? '');
            $password    = trim($input['password'] ?? '');
            $pin         = trim($input['pin'] ?? '0000');
            $m3u         = trim($input['m3u'] ?? '');

            if (empty($dns_id) || empty($mac_address) || empty($username) || empty($password)) {
                echo json_encode(['success' => false, 'message' => 'DNS, MAC, User and Pass are required']);
                exit();
            }

            $stmt = $db->prepare("INSERT INTO playlist (dns_id, mac_address, username, password, pin, m3u) VALUES (:dns_id, :mac_address, :username, :password, :pin, :m3u)");
            $stmt->execute([
                ':dns_id'      => $dns_id,
                ':mac_address' => $mac_address,
                ':username'    => $username,
                ':password'    => $password,
                ':pin'         => $pin,
                ':m3u'         => $m3u
            ]);

            echo json_encode(['success' => true, 'message' => 'Playlist entry added successfully']);
            break;

        case 'edit':
            $id          = $input['id'];
            $dns_id      = trim($input['dns_id'] ?? '');
            $mac_address = trim($input['mac_address'] ?? '');
            $username    = trim($input['username'] ?? '');
            $password    = trim($input['password'] ?? '');
            $pin         = trim($input['pin'] ?? '0000');
            $m3u         = trim($input['m3u'] ?? '');

            $stmt = $db->prepare("UPDATE playlist SET dns_id = :dns_id, mac_address = :mac_address, username = :username, password = :password, pin = :pin, m3u = :m3u WHERE id = :id");
            $stmt->execute([
                ':dns_id'      => $dns_id,
                ':mac_address' => $mac_address,
                ':username'    => $username,
                ':password'    => $password,
                ':pin'         => $pin,
                ':m3u'         => $m3u,
                ':id'          => $id,
            ]);

            echo json_encode(['success' => true, 'message' => 'Playlist entry updated successfully']);
            break;

        case 'delete':
            $id = $input['id'] ?? null;
            if (!$id) {
                echo json_encode(['success' => false, 'message' => 'ID missing']);
                exit();
            }

            $stmt = $db->prepare("DELETE FROM playlist WHERE id = :id");
            $stmt->execute([':id' => $id]);
            echo json_encode(['success' => true, 'message' => 'Playlist entry deleted successfully']);
            break;

        // --- NOVA FUNÇÃO ADICIONADA ---
        case 'clear_all':
            // No SQLite, DELETE FROM sem WHERE apaga todos os registros
            $stmt = $db->prepare("DELETE FROM playlist");
            $stmt->execute();
            
            // Opcional: Reiniciar o contador de ID (Auto-increment) no SQLite
            $db->exec("DELETE FROM sqlite_sequence WHERE name='playlist'");

            echo json_encode(['success' => true, 'message' => 'All MAC addresses have been cleared']);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>