<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['id'], $_POST['nomePlaylist'], $_POST['dns'], $_POST['usuario'], $_POST['senha'])) {
        $_SESSION['clienteqrlivecode'] = true;

        $id = $_POST['id'];
        $playlistTitle = $_POST['nomePlaylist'];
        $dns = $_POST['dns'];
        $username = $_POST['usuario'];
        $password = $_POST['senha'];

        $databaseFileClientes = './api/db/studiolivecode_clientes.db';
        $databaseFileDns = './api/db/studiolivecode_dns.db';

        try {
            $connClientes = new PDO("sqlite:$databaseFileClientes");
            $connClientes->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $stmt = $connClientes->prepare("SELECT mac_address FROM ibo WHERE key = :id");
            $stmt->bindParam(':id', $id);
            $stmt->execute();
            $iboRow = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($iboRow) {
                $macAddress = $iboRow['mac_address'];

                $connDns = new PDO("sqlite:$databaseFileDns");
                $connDns->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                $stmt = $connDns->prepare("SELECT url FROM dns WHERE title = :dns");
                $stmt->bindParam(':dns', $dns);
                $stmt->execute();
                $dnsRow = $stmt->fetch(PDO::FETCH_ASSOC);
                $dnsUrl = $dnsRow['url'];

                // URLs para verificar
                $urls = [
                    "$dnsUrl/get.php?username=$username&password=$password&type=m3u_plus&output=ts",
                    "$dnsUrl/get.php?username=$username&password=$password&type=m3u_plus&output=m3u8",
                    "$dnsUrl/get.php?username=$username&password=$password&type=m3u_plus&output=mpegts"
                ];

                $client = new Client();

                $isValid = false;
                foreach ($urls as $url) {
                    try {
                        $response = $client->request('GET', $url, ['http_errors' => false]);
                        if ($response->getStatusCode() == 200) {
                            $isValid = true;
                            break;
                        }
                    } catch (RequestException $e) {
                        // Continue to next URL if request fails
                    }
                }

                if ($isValid) {
                    $m3uUrl = "$dnsUrl/get.php?username=$username&password=$password&type=m3u_plus&output=ts";

                    $expireDate = date('Y-m-d H:i:s', strtotime('+10 days'));

                    $stmt = $connClientes->prepare("
                        UPDATE ibo SET username = :username, password = :password, url = :url, title = :title, expire_date = :expire_date, dns = :dns
                        WHERE mac_address = :mac_address
                    ");

                    $stmt->bindParam(':mac_address', $macAddress);
                    $stmt->bindParam(':title', $playlistTitle);
                    $stmt->bindParam(':url', $m3uUrl);
                    $stmt->bindParam(':username', $username);
                    $stmt->bindParam(':password', $password);
                    $stmt->bindParam(':expire_date', $expireDate);
                    $stmt->bindParam(':dns', $dnsUrl);

                    $stmt->execute();

                    $_SESSION['success_message'] = "Dados inseridos com sucesso.";
                    header("Location: loginqr.php");
                    exit();
                } else {
                    $_SESSION['error_message'] = "Usuário ou senha inválidos.";
                }
            } else {
                $_SESSION['error_message'] = "ID inválido.";
            }
        } catch (PDOException $e) {
            echo "Erro ao conectar ao banco de dados: " . $e->getMessage();
            exit();  
        } catch (Exception $e) {
            echo "Erro desconhecido: " . $e->getMessage();
            exit();
        }
    } else {
        header("Location: loginqr.php");
        exit();
    }
    header("Location: loginqr.php");
    exit();
} else {
    header("Location: loginqr.php");
    exit();
}
?>
