<?php require_once '../Connections/cmctrfdb.php'; ?>
<?php require_once '../webassist/mysqli/rsobj.php'; ?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
include 'include/headscript.php';
include('languages/' . $_SESSION['langselect'] . '/tdgen.php');

// Recupera idcompany
if (isset($_POST['idcompany'])) {
    $idcompany = intval($_POST['idcompany']);
} elseif (isset($_GET['idcompany'])) {
    $idcompany = intval($_GET['idcompany']);
} else {
    die("Errore: idcompany non specificato.");
}

// Gestione del submit (solo INSERT)
if (isset($_POST['submit'])) {
    $description = $_POST['descriptionlogo'];
    $targetDir = "logos/";

    $file = $_FILES['logofile'];
    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileError = $file['error'];
    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    if ($fileError === 0 && in_array($fileExt, ['png', 'jpg', 'jpeg'])) {
        $newFileName = $idcompany . "_" . time() . "." . $fileExt;
        $fileDestination = $targetDir . $newFileName;

        $conn = new mysqli($servername, $username, $password, $dbname);
        if (move_uploaded_file($fileTmpName, $fileDestination)) {
            $sql = "INSERT INTO logo_td (descriptionlogo, filenamelogo, idcompany) VALUES (?, ?, ?)";
            $stmt = $conn->prepare($sql);
            if ($stmt) {
                $stmt->bind_param("ssi", $description, $newFileName, $idcompany);
                $stmt->execute();
                $stmt->close();
            } else {
                echo ($_SESSION['langselect'] == 'en') ? "Error during database insertion." : "Errore durante l'inserimento nel database.";
            }
        } else {
            echo ($_SESSION['langselect'] == 'en') ? "Error uploading the file." : "Errore nel caricamento del file.";
        }
        $conn->close();
    } else {
        echo ($_SESSION['langselect'] == 'en') ? "Only PNG and JPG files are allowed." : "Sono ammessi solo file PNG e JPG.";
    }
    // Reindirizza per evitare reinvii
    header("Location: logopopup.php?idcompany=$idcompany");
    exit();
}
?>

<!DOCTYPE html>
<html lang="<?php echo ($_SESSION['langselect'] == 'en') ? 'en' : 'it'; ?>">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo ($_SESSION['langselect'] == 'en') ? 'Add Logo' : 'Aggiungi Logo'; ?></title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet">
    <style>
        .drag-area {
            border: 2px dashed #ccc;
            border-radius: 20px;
            width: auto;
            margin: 10px 0;
            padding: 20px;
            text-align: center;
            font-size: 20px;
            color: #ccc;
        }

        .drag-area.highlight {
            border-color: blue;
            background-color: rgba(0, 0, 255, 0.1);
        }

        .custom-file-label::after {
            content: "<?php echo ($_SESSION['langselect'] == 'en') ? 'Browse' : 'Sfoglia'; ?>";
        }
    </style>
</head>

<body>
    <div class="container mt-5">
        <button type="button" class="btn btn-secondary" onclick="closeAndRefresh()"><?php echo ($_SESSION['langselect'] == 'en') ? 'Close and Refresh' : 'Chiudi e Aggiorna'; ?></button>
        <h3><?php echo ($_SESSION['langselect'] == 'en') ? 'Add Logo' : 'Aggiungi Logo'; ?></h3>

        <form id="uploadLogoForm" action="logopopup.php?idcompany=<?php echo $idcompany; ?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="idcompany" value="<?php echo $idcompany; ?>">
            <div class="form-group">
                <label for="logoDescription"><?php echo ($_SESSION['langselect'] == 'en') ? 'Logo Description:' : 'Descrizione Logo:'; ?></label>
                <input type="text" class="form-control" id="logoDescription" name="descriptionlogo" required>
            </div>
            <div class="form-group">
                <label for="logoFile"><?php echo ($_SESSION['langselect'] == 'en') ? 'Logo File:' : 'File Logo:'; ?></label>
                <div class="drag-area" id="drag-area">
                    <p><?php echo ($_SESSION['langselect'] == 'en') ? 'Drag the file here or click to select' : 'Trascina qui il file o clicca per selezionare'; ?></p>
                </div>
                <div class="custom-file mb-3">
                    <input type="file" class="custom-file-input" id="logoFile" name="logofile" accept=".png,.jpg,.jpeg" required>
                    <label class="custom-file-label" for="logoFile"><?php echo ($_SESSION['langselect'] == 'en') ? 'Choose file' : 'Scegli file'; ?></label>
                </div>
            </div>
            <button type="submit" class="btn btn-primary" name="submit"><?php echo ($_SESSION['langselect'] == 'en') ? 'Upload Logo' : 'Carica Logo'; ?></button>
        </form>
    </div>
    <div class="container mt-5">
        <h3><?php echo ($_SESSION['langselect'] == 'en') ? 'Uploaded Logos' : 'Loghi Caricati'; ?></h3>
        <table class="table">
            <thead>
                <tr>
                    <th><?php echo ($_SESSION['langselect'] == 'en') ? 'Description' : 'Descrizione'; ?></th>
                    <th><?php echo ($_SESSION['langselect'] == 'en') ? 'Logo' : 'Logo'; ?></th>
                    <th><?php echo ($_SESSION['langselect'] == 'en') ? 'Action' : 'Azione'; ?></th>
                </tr>
            </thead>
            <tbody>
                <?php
                $conn = new mysqli($servername, $username, $password, $dbname);
                $query = "SELECT idlogo_td, descriptionlogo, filenamelogo FROM logo_td WHERE idcompany = ?";
                $stmt = $conn->prepare($query);
                $stmt->bind_param("i", $idcompany);
                $stmt->execute();
                $result = $stmt->get_result();

                while ($row = $result->fetch_assoc()) {
                    echo "<tr>";
                    echo "<td>" . htmlspecialchars($row['descriptionlogo']) . "</td>";
                    echo "<td><img src='logos/" . htmlspecialchars($row['filenamelogo']) . "' alt='Logo' style='width: 50px;'></td>";
                    echo "<td>";
                    echo "<a href='deletelogo.php?id=" . $row['idlogo_td'] . "&idcompany=$idcompany' onclick='return confirm(\"" . ($_SESSION['langselect'] == 'en' ? 'Are you sure you want to delete this logo?' : 'Sei sicuro di voler cancellare questo logo?') . "\");'><i class='fas fa-trash-alt' style='color: red;'></i></a>";
                    echo "</td>";
                    echo "</tr>";
                }
                $stmt->close();
                $conn->close();
                ?>
            </tbody>
        </table>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.2/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script>
        $(".custom-file-input").on("change", function() {
            var fileName = $(this).val().split("\\").pop();
            $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
        });

        var dragArea = document.getElementById('drag-area');
        var input = document.getElementById('logoFile');

        ['dragenter', 'dragover'].forEach(eventName => {
            dragArea.addEventListener(eventName, (e) => {
                preventDefaults(e);
                dragArea.classList.add('highlight');
            }, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dragArea.addEventListener(eventName, (e) => {
                preventDefaults(e);
                dragArea.classList.remove('highlight');
            }, false);
        });

        dragArea.addEventListener('drop', (e) => {
            preventDefaults(e);
            let dt = e.dataTransfer;
            let files = dt.files;
            input.files = files;
            $(".custom-file-label").addClass("selected").html(files[0].name);
        }, false);

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        dragArea.addEventListener('click', () => input.click());

        function closeAndRefresh() {
            if (window.opener && !window.opener.closed) {
                window.opener.updateSelectDropdown();
            }
            window.close();
        }
    </script>
</body>

</html>