<?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';

// Recupera idcompany
if (isset($_POST['idcompany'])) {
    $idcompany = intval($_POST['idcompany']);
} elseif (isset($_GET['idcompany'])) {
    $idcompany = intval($_GET['idcompany']);
} else {
    die(($_SESSION['langselect'] == 'en') ? "Error: idcompany not specified." : "Errore: idcompany non specificato.");
}
include('languages/' . $_SESSION['langselect'] . '/tdgen.php');

// Variabili per modalità modifica
$editMode = false;
$qualcheckId = 0;
$description = '';
$qualchecktext = '';

// Verifica se siamo in modalità modifica
if (isset($_GET['edit_id']) && !isset($_POST['submit'])) {
    $editMode = true;
    $qualcheckId = intval($_GET['edit_id']);
    $conn = new mysqli($servername, $username, $password, $dbname);
    $query = "SELECT descriptionqualcheck, qualchecktext FROM qualcheck_td WHERE idqualcheck_td = ? AND idcompany = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("ii", $qualcheckId, $idcompany);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        $description = htmlspecialchars($row['descriptionqualcheck']);
        $qualchecktext = htmlspecialchars($row['qualchecktext']);
    } else {
        $editMode = false; // Se non troviamo il record, usciamo dalla modalità modifica
    }
    $stmt->close();
    $conn->close();
}

// Gestione del submit
if (isset($_POST['submit'])) {
    $description = $_POST['descriptionqualcheck'];
    $qualchecktext = $_POST['qualchecktext'];
    $qualcheckId = isset($_POST['qualcheck_id']) ? intval($_POST['qualcheck_id']) : 0;
    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($qualcheckId > 0) {
        // Modalità UPDATE
        $sql = "UPDATE qualcheck_td SET descriptionqualcheck = ?, qualchecktext = ? WHERE idqualcheck_td = ? AND idcompany = ?";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param("ssii", $description, $qualchecktext, $qualcheckId, $idcompany);
            $stmt->execute();
            $stmt->close();
        } else {
            echo ($_SESSION['langselect'] == 'en') ? "Error during database update." : "Errore durante l'aggiornamento nel database.";
        }
    } else {
        // Modalità INSERT
        $sql = "INSERT INTO qualcheck_td (descriptionqualcheck, qualchecktext, idcompany) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param("ssi", $description, $qualchecktext, $idcompany);
            $stmt->execute();
            $stmt->close();
        } else {
            echo ($_SESSION['langselect'] == 'en') ? "Error during database insertion." : "Errore durante l'inserimento nel database.";
        }
    }
    $conn->close();
    // Reindirizza per evitare duplicati
    header("Location: qualcheck.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 $editMode ? ($_SESSION['langselect'] == 'en' ? 'Edit Qualification' : 'Modifica Qualificazione') : ($_SESSION['langselect'] == 'en' ? 'Add Qualification' : 'Aggiungi Qualificazione'); ?></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">
    <script src="ckeditor/build/ckeditor.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            ClassicEditor
                .create(document.querySelector('#qualcheckText'), {
                    toolbar: {
                        items: [
                            'undo', 'redo', '|', 'heading', '|', 'fontFamily', 'fontSize', '|',
                            'bold', 'italic', '|', 'link', 'blockQuote', '|',
                            'alignment:left', 'alignment:right', 'alignment:center', 'alignment:justify', '|',
                            'bulletedList', 'numberedList', 'outdent', 'indent', '|', 'insertTable', '|', 'imageUpload'
                        ],
                        shouldNotGroupWhenFull: true
                    },
                    table: {
                        contentToolbar: ['tableColumn', 'tableRow', 'mergeTableCells']
                    },
                    simpleUpload: {
                        uploadUrl: 'uploadck.php',
                        withCredentials: true,
                        headers: {
                            'X-CSRF-TOKEN': 'CSRF-Token',
                            Authorization: 'Bearer <JSON Web Token>'
                        }
                    }
                })
                .catch(error => {
                    console.error(error);
                });
        });

        function closeAndRefresh() {
            window.opener.location.reload();
            window.close();
        }
    </script>
    <style>
        .ck-editor__editable_inline {
            min-height: 200px;
        }

        .ck-editor__editable {
            resize: vertical;
            overflow: auto;
        }
    </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 $editMode ? ($_SESSION['langselect'] == 'en' ? 'Edit Production Quality Control' : 'Modifica Controllo Qualità produzione') : ($_SESSION['langselect'] == 'en' ? 'Add Production Quality Control' : 'Aggiungi Controllo Qualità produzione'); ?></h3>

        <form action="qualcheck.php?idcompany=<?php echo $idcompany; ?>" method="post">
            <input type="hidden" name="idcompany" value="<?php echo $idcompany; ?>">
            <input type="hidden" name="qualcheck_id" value="<?php echo $qualcheckId; ?>">
            <div class="form-group">
                <label for="descriptionQualcheck"><?php echo ($_SESSION['langselect'] == 'en') ? 'Description:' : 'Descrizione:'; ?></label>
                <input type="text" class="form-control" id="descriptionQualcheck" name="descriptionqualcheck" value="<?php echo $description; ?>" required>
            </div>
            <div class="form-group">
                <label for="qualcheckText"><?php echo ($_SESSION['langselect'] == 'en') ? 'Production Quality Control:' : 'Controllo Qualità produzione:'; ?></label>
                <textarea class="form-control" id="qualcheckText" name="qualchecktext" rows="5"><?php echo $qualchecktext; ?></textarea>
            </div>
            <button type="submit" class="btn btn-primary" name="submit"><?php echo $editMode ? ($_SESSION['langselect'] == 'en' ? 'Update' : 'Aggiorna') : ($_SESSION['langselect'] == 'en' ? 'Add' : 'Aggiungi'); ?></button>
            <?php if ($editMode) { ?>
                <a href="qualcheck.php?idcompany=<?php echo $idcompany; ?>" class="btn btn-secondary"><?php echo ($_SESSION['langselect'] == 'en') ? 'Cancel Edit' : 'Annulla Modifica'; ?></a>
            <?php } ?>
        </form>
    </div>

    <div class="container mt-5">
        <h3><?php echo ($_SESSION['langselect'] == 'en') ? 'Inserted Production Quality Controls' : 'Controllo Qualità produzione Inseriti'; ?></h3>
        <table class="table">
            <thead>
                <tr>
                    <th><?php echo ($_SESSION['langselect'] == 'en') ? 'Description' : 'Descrizione'; ?></th>
                    <th><?php echo ($_SESSION['langselect'] == 'en') ? 'Actions' : 'Azioni'; ?></th>
                </tr>
            </thead>
            <tbody>
                <?php
                $conn = new mysqli($servername, $username, $password, $dbname);
                $query = "SELECT idqualcheck_td, descriptionqualcheck, qualchecktext FROM qualcheck_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['descriptionqualcheck']) . "</td>";
                    echo "<td>";
                    echo "<a href='qualcheck.php?idcompany=$idcompany&edit_id=" . $row['idqualcheck_td'] . "' style='color: blue; margin-right: 10px;'><i class='fas fa-edit'></i></a>";
                    echo "<a href='delete_qualcheck.php?id=" . $row['idqualcheck_td'] . "&idcompany=$idcompany' style='color: red;'><i class='fas fa-trash-alt'></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>
</body>

</html>