<?php 
include ('includes/header.php');
$table_name = 'tsdbapi';
$page_name = 'tsdp_api';

// Insert initial data if the table is empty
$data = ['methord' => 'inapp', 'key' => '0'];
$db->insertIfEmpty($table_name, $data);

// Retrieve the existing data for display
$res = $db->select($table_name, '*', '', '');

// Handle form submission
if(isset($_POST['submit'])){
    unset($_POST['submit']);
    $updateData = $_POST;
    $db->update($table_name, $updateData, 'id = :id', [':id' => 1]);
    echo "<script>window.location.href='". $page_name.".php?status=1'</script>";
}

// Set default values for form fields based on current database values
$currentCla = $res[0]['methord'] ?? '+';
$currentTime = $res[0]['key'] ?? '0';
?>

<div class="col-md-6 mx-auto ctmain-table">
    <div class="card-body">
        <div class="card text-white ctcard">
            <div class="card-header card-header-warning">
                <center>
                    <h2><i class="icon icon-bullhorn"></i> Thesportsdb api</h2>
                </center>
            </div>
            
            <div class="card-body">
                <form method="post">
                    <div class="form-group ctinput">
                        <label class="form-label">Method </label>
                        <select id="methord" name="methord">
                            <option value="def" <?= $currentCla == 'def' ? 'selected' : '' ?>>Default api</option>
                            <option value="cust" <?= $currentCla == 'cust' ? 'selected' : '' ?>>Custom api</option>
                        </select>
                    </div>
                    <div class="form-group ctinput">
                        <label class="form-label">Enter API key</label>
                        <input class="form-control" id="key" name="key" value="<?= htmlspecialchars($currentTime) ?>" type="text"/>
                    </div>
                    <div class="form-group ctinputform-group">
                        <center>
                            <button class="btn btn-info" name="submit" type="submit">
                                <i class="icon icon-check"></i> Submit
                            </button>
                        </center>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include ('includes/footer.php');?>
