<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Não autenticado']);
    exit;
}

try {
    $dbPath = __DIR__ . '/../ibo_panel.db';
    $db = new PDO('sqlite:' . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Verificar se a coluna 'cliente' existe, se não, adicionar
    $stmt = $db->query("PRAGMA table_info(playlist)");
    $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $hasClienteColumn = false;

    foreach ($columns as $column) {
        if ($column['name'] === 'cliente') {
            $hasClienteColumn = true;
            break;
        }
    }

    if (!$hasClienteColumn) {
        $db->exec("ALTER TABLE playlist ADD COLUMN cliente TEXT");
    }

    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? 'view';

    if ($action === 'view') {

        $stmt = $db->query("SELECT * FROM playlist ORDER BY id DESC");
        $playlistRecords = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode(['success' => true, 'data' => $playlistRecords]);

    } elseif ($action === 'get_dns_options') {

        $stmt = $db->query("SELECT id, title FROM dns");
        $dnsOptions = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode(['success' => true, 'data' => $dnsOptions]);

    } elseif ($action === 'add') {

        $cliente = trim($input['cliente'] ?? '');
        if ($cliente === '') {
            $cliente = null;
        }

        $dns_id = trim($input['dns_id'] ?? '');
        $mac_address = trim($input['mac_address'] ?? '');
        $username = trim($input['username'] ?? '');
        $password = trim($input['password'] ?? '');
        $link = trim($input['link'] ?? '');

        // PIN sempre será "0000"
        $pin = "0000";

        // Cliente NÃO é mais obrigatório
        if (empty($dns_id) || empty($mac_address) || empty($username) || empty($password)) {
            echo json_encode([
                'success' => false,
                'message' => 'DNS ID, MAC Address, Username and Password are required!'
            ]);
            exit();
        }

        if (empty($link)) {
            $link = '';
        }

        $stmt = $db->prepare("
            INSERT INTO playlist 
            (cliente, dns_id, mac_address, username, password, pin, link)
            VALUES 
            (:cliente, :dns_id, :mac_address, :username, :password, :pin, :link)
        ");

        $stmt->execute([
            ':cliente' => $cliente,
            ':dns_id' => $dns_id,
            ':mac_address' => $mac_address,
            ':username' => $username,
            ':password' => $password,
            ':pin' => $pin,
            ':link' => $link
        ]);

        $newId = $db->lastInsertId();

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

    } elseif ($action === 'edit') {

        $id = $input['id'] ?? '';

        $cliente = trim($input['cliente'] ?? '');
        if ($cliente === '') {
            $cliente = null;
        }

        $dns_id = trim($input['dns_id'] ?? '');
        $mac_address = trim($input['mac_address'] ?? '');
        $username = trim($input['username'] ?? '');
        $password = trim($input['password'] ?? '');
        $link = trim($input['link'] ?? '');

        // PIN sempre será "0000"
        $pin = "0000";

        // Cliente NÃO é obrigatório
        if (empty($id) || empty($dns_id) || empty($mac_address) || empty($username) || empty($password)) {
            echo json_encode([
                'success' => false,
                'message' => 'ID, DNS ID, MAC Address, Username and Password are required!'
            ]);
            exit();
        }

        if (empty($link)) {
            $link = '';
        }

        $stmt = $db->prepare("
            UPDATE playlist 
            SET cliente = :cliente,
                dns_id = :dns_id,
                mac_address = :mac_address,
                username = :username,
                password = :password,
                pin = :pin,
                link = :link
            WHERE id = :id
        ");

        $stmt->execute([
            ':cliente' => $cliente,
            ':dns_id' => $dns_id,
            ':mac_address' => $mac_address,
            ':username' => $username,
            ':password' => $password,
            ':pin' => $pin,
            ':link' => $link,
            ':id' => $id
        ]);

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

    } elseif ($action === 'delete') {

        $id = $input['id'] ?? '';

        if (empty($id)) {
            echo json_encode(['success' => false, 'message' => 'ID is required']);
            exit();
        }

        $stmt = $db->prepare("DELETE FROM playlist WHERE id = :id");
        $stmt->execute([':id' => $id]);

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

    } else {

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

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