<?php 
include ('includes/header.php');
$page_name = 'tmdb_api';
$json_file_path = 'api/ads/tmdbkey.json'; 

if(isset($_POST['submit'])){
    unset($_POST['submit']);
    $tmdbkey = $_POST['tmdbkey'];

    // Load current data
    $data = [];
    if (file_exists($json_file_path)) {
        $json_data = file_get_contents($json_file_path);
        $data = json_decode($json_data, true);
    }

    // Update only tmdbkey
    $data['tmdbkey'] = $tmdbkey;

    // Save updated JSON
    $json_data = json_encode($data, JSON_PRETTY_PRINT);
    if (file_put_contents($json_file_path, $json_data)) {
        echo "<script>window.location.href='". $page_name.".php?status=1'</script>";
    }
}

$tmdbkey = "";
if (file_exists($json_file_path)) {
    $json_data = file_get_contents($json_file_path);
    $data = json_decode($json_data, true);
    if ($data && isset($data['tmdbkey'])) {
        $tmdbkey = $data['tmdbkey'];
    }
}
?>

<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> TMDB API Key</h2>
                </center>
            </div>
            
            <div class="card-body">
                <form method="post">
                    <div class="form-group ctinput">
                        <label class="form-label">TMDB API Key</label>
                        <input class="form-control" name="tmdbkey" value="<?php echo isset($tmdbkey) ? htmlspecialchars($tmdbkey) : ''; ?>" 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'); ?>
