<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$page_title = "Logo and Background Management";

$logoJsonFile = './api/images/logo_filenames.json';
$bgJsonFile = './api/images/image_filenames.json';

$logoDirectory = './assets/media/logos/';
$apiImageDirectory = './api/images/';
$bgDirectory = $apiImageDirectory;

if (!is_dir($logoDirectory)) {
    mkdir($logoDirectory, 0755, true);
}
if (!is_dir($apiImageDirectory)) {
    mkdir($apiImageDirectory, 0755, true);
}
if (!is_dir($bgDirectory)) {
    mkdir($bgDirectory, 0755, true);
}

$message = null;

function handleUpload($file, $type) {
    global $message, $logoDirectory, $apiImageDirectory, $bgDirectory, $logoJsonFile, $bgJsonFile;

    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!empty($file['name']) && in_array($file['type'], $allowedTypes)) {
        $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);

        if ($type === 'logo') {
            $fileName = 'logo.png';
            $destination1 = $logoDirectory . $fileName;
            $destination2 = $apiImageDirectory . $fileName;

            if (move_uploaded_file($file['tmp_name'], $destination1) && copy($destination1, $destination2)) {
                $jsonData = json_encode([['ImageName' => './images/' . $fileName, 'Upload_type' => $type]]);
                file_put_contents($logoJsonFile, $jsonData);
                $message = "Logo uploaded successfully.";
            } else {
                $message = "Failed to upload logo.";
            }
        } elseif ($type === 'background') {
            $fileName = "background." . $fileExtension;
            $destination = $bgDirectory . $fileName;

            if (move_uploaded_file($file['tmp_name'], $destination)) {
                $jsonData = json_encode([['ImageName' => './images/' . $fileName, 'Upload_type' => $type]]);
                file_put_contents($bgJsonFile, $jsonData);
                $message = "Background uploaded successfully.";
            } else {
                $message = "Failed to upload background.";
            }
        }
    } else {
        $message = "Invalid file type for $type. Only JPEG, PNG, and GIF are allowed.";
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['upload_type']) && $_POST['upload_type'] === 'logo') {
        if (isset($_FILES['logo'])) {
            handleUpload($_FILES['logo'], 'logo');
        }
    } elseif (isset($_POST['upload_type']) && $_POST['upload_type'] === 'background') {
        if (isset($_FILES['background'])) {
            handleUpload($_FILES['background'], 'background');
        }
    }
}

function getCurrentImage($jsonFile) {
    if (file_exists($jsonFile)) {
        $jsonData = json_decode(file_get_contents($jsonFile), true);
        return $jsonData[0]['ImageName'] ?? null;
    }
    return null;
}

$currentLogo = getCurrentImage($logoJsonFile);
$currentBackground = getCurrentImage($bgJsonFile);

$logoSrc = str_replace('./images/', './api/images/', $currentLogo);
$backgroundSrc = str_replace('./images/', './api/images/', $currentBackground);

$page_content = '<div class="card mb-4">
    <div class="card-body">
        <h4>Manage Logo and Background</h4>';

if ($message) {
    $page_content .= '<div class="alert alert-info">' . htmlspecialchars($message) . '</div>';
}

$page_content .= '
    <div class="row">
        <div class="col-md-6">
            <h5>Current Logo:</h5>
            <img src="' . htmlspecialchars($logoSrc ?? 'https://via.placeholder.com/200') . '" class="img-thumbnail mb-2" alt="Logo" style="max-width: 300px; height: 200px; object-fit: cover;">
            <form action="" method="post" enctype="multipart/form-data">
                <input type="hidden" name="upload_type" value="logo">
                <input type="file" name="logo" class="form-control mb-2" required>
                <button type="submit" class="btn btn-primary">Upload Logo</button>
            </form>
        </div>

        <div class="col-md-6">
            <h5>Current Background:</h5>
            <img src="' . htmlspecialchars($backgroundSrc ?? 'https://via.placeholder.com/200') . '" class="img-thumbnail mb-2" alt="Background" style="max-width: 300px; height: 200px; object-fit: cover;">
            <form action="" method="post" enctype="multipart/form-data">
                <input type="hidden" name="upload_type" value="background">
                <input type="file" name="background" class="form-control mb-2" required>
                <button type="submit" class="btn btn-primary">Upload Background</button>
            </form>
        </div>
    </div>';


include 'includes/layout.php';
?>
