<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

$folder_name = "api/";
$logo_path = $folder_name . "logo.png";
$message = "";

if (isset($_POST["upload_logo"])) {
    $errors = array();
    $file_name = $_FILES["logo"]["name"];
    $file_size = $_FILES["logo"]["size"];
    $file_tmp = $_FILES["logo"]["tmp_name"];
    $file_type = $_FILES["logo"]["type"];
    $file_name_parts = explode(".", $_FILES["logo"]["name"]);
    $file_ext = strtolower(end($file_name_parts));
    $extensions = array("png");
    
    if (!in_array($file_ext, $extensions)) {
        $errors[] = "Extension not allowed, please choose a PNG file.";
    }

    if ($file_size > 5242880) {
        $errors[] = "File size must not exceed 5 MB";
    }

    if (empty($errors)) {
        move_uploaded_file($file_tmp, $folder_name . "logo.png");
        header("Location: " . $_SERVER["PHP_SELF"]);
        exit;
    } else {
        foreach ($errors as $error) {
            $message .= "<div class=\"alert alert-danger\">$error</div>";
        }
    }
}

include("includes/header.php");
?>

<!-- Begin Page Content -->
<div class="container-fluid">
    <div class="col-md-8 mx-auto">
        <!-- Custom codes -->
        <div class="card-body">
            <div class="form-group">
                <form method="post" enctype="multipart/form-data">
                    <label class="control-label" for="logo">
                        <strong> Upload Logo Image</strong>
                    </label>
                    <div class="input-group">
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" name="logo" id="logo" placeholder="Choose Logo" onchange="uploadLogo(this)" aria-describedby="logo">
                            <label class="custom-file-label" for="logo" placeholder="Choose Logo"><span id="image-logo"></span></label>
                            <input type="hidden" name="logo" value="logo">
                        </div>
                        <button type="submit" name="upload_logo" class="btn btn-info">Upload</button>
                    </div>
                </form>
                <br>
            </div>
        </div>

        <!-- Theme -->
        <div class="align-items-center">
            <center>
                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Current Logo</div>
                <div class="h5 mb-0 font-weight-bold text-gray-800">
                    <?php if (file_exists($logo_path)) : ?>
                        <img src="<?= $logo_path . "?t=" . time() ?>" alt="Current Logo" style="max-width: 500px; max-height: 500px;">
                    <?php else : ?>
                        <p>No logo uploaded yet.</p>
                    <?php endif; ?>
                </div>
            </center>
        </div>
    </div>
</div>

<?php
echo $message;
include('includes/footer.php');
?>
</body>
</html>
