<?php

function Submit($sub_type, $db, $table_name, $seller_name)
{
    if ($sub_type == 'sub_new' && isset($_POST['intro_url'])) {
        $intro_url = $_POST['intro_url'];
        $stmt = $db->prepare("UPDATE $table_name SET url = :url WHERE owner = '$seller_name'");
        $stmt->bindValue(':url', $intro_url, SQLITE3_TEXT);
        $stmt->execute();
        echo "<script>window.location.href='index.php'</script>";
    }
}

error_reporting(0); // Avoid displaying errors to users in production
include '../includes/header2.php';

$table_name = 'intro';
$db = new SQLite3('../api/intro.db'); // Replace with your database configuration

$db->exec("CREATE TABLE IF NOT EXISTS $table_name (id INTEGER PRIMARY KEY, url TEXT)");
$rows = $db->querySingle("SELECT COUNT(*) as count FROM $table_name WHERE owner = '$seller_name'");
$numRows = intval($rows);

if ($numRows === 0) {
    $db->exec("INSERT INTO $table_name (url, owner) VALUES ('','$seller_name')");
}

$intro = $db->querySingle("SELECT url FROM $table_name WHERE owner = '$seller_name'");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Submit('sub_new', $db, $table_name, $seller_name);
}

if (!file_exists('intro')) {
    mkdir('intro', 0755, true);
}

?>

<div class="col-md-6 mx-auto">
    <div class="card-header card-header-warning">
    <center>
        <h2><i class="fa fa-television" aria-hidden="true" style="color: white;"></i> <span style="color: white;">Link para Video</span></h2>
    </center>
</div>
            <div class="card-body">
                <div class="col-12">
                </div>
                <form action="" method="post" enctype="multipart/form-data">
                    <br>
                    <div id="loc" class="form-group form-float form-group-lg">
                        <div class="form-line">
                            <label class="form-label"><strong>URL</strong></label>
                            <input type="text" class="form-control" name="intro_url" placeholder="Ex: https://www.youtube.com.br" value="<?php echo $intro; ?>">
                        </div>
                    </div>
                    <div class="form-group">
                        <center>
                            <button class="btn btn-info" name="submit" type="submit">
                                <i class="icon icon-check"></i> Submit
                            </button>
                        </center>
                    </div>
                    </center>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
include '../includes/footer2.php';
?>
