<?php include('include/headscript.php');

// Verifica se l'ID della classe è stato passato correttamente tramite GET
if (isset($_GET['idyogaclass']) && is_numeric($_GET['idyogaclass'])) {
    $idyogaclass = intval($_GET['idyogaclass']);
} else {
    // Se non c'è un ID valido, reindirizza alla pagina delle classi
    header("Location: yogaclass.php");
    exit;
}

// Recupera i dati della classe corrente dal database
$conn = new mysqli($servername, $username, $password, $database);
$query = $conn->prepare("SELECT * FROM yogaclass WHERE idyogaclass = ?");
$query->bind_param("i", $idyogaclass);
$query->execute();
$result = $query->get_result();
$classData = $result->fetch_assoc();

// Se il form è stato inviato, aggiorna i dati
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nameyogaclass = $_POST['nameyogaclass'];
    $idclasscategory = $_POST['idclasscategory'];
    $descriptionyogaclass = $_POST['descriptionyogaclass'];
    $productcode = $_POST['productcode'];

    // Se è stata caricata una nuova immagine
    if (!empty($_FILES['imgyogaclass']['name'])) {
        $img_name = $_FILES['imgyogaclass']['name'];
        $img_tmp_name = $_FILES['imgyogaclass']['tmp_name'];
        $ext = pathinfo($img_name, PATHINFO_EXTENSION);
        $new_img_name = time() . '-' . $idyogaclass . '.' . $ext;
        $upload_path = 'uploadphotoclass/' . $new_img_name;

        // Elimina l'immagine precedente
        if (!empty($classData['imgyogaclass']) && file_exists('uploadphotoclass/' . $classData['imgyogaclass'])) {
            unlink('uploadphotoclass/' . $classData['imgyogaclass']);
        }

        // Carica la nuova immagine
        move_uploaded_file($img_tmp_name, $upload_path);
    } else {
        // Mantieni l'immagine esistente se non viene caricata una nuova
        $new_img_name = $_POST['existing_img'];
    }

    // Aggiorna i dati della classe nel database
    $update_query = $conn->prepare("
        UPDATE yogaclass 
        SET nameyogaclass = ?, idclasscategory = ?, descriptionyogaclass = ?, imgyogaclass = ?, productcode = ?
        WHERE idyogaclass = ?
    ");
    $update_query->bind_param("sisssi", $nameyogaclass, $idclasscategory, $descriptionyogaclass, $new_img_name, $productcode, $idyogaclass);

    if ($update_query->execute()) {
        // Reindirizza alla pagina delle classi con un messaggio di successo
        header("Location: yogaclass.php?message=class_updated");
        exit;
    } else {
        echo "Errore durante l'aggiornamento della classe.";
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Modifica Classe</title>
    <?php include('include/seo.php'); ?>
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="assets/css/icons.css" rel="stylesheet" type="text/css">
    <link href="assets/css/style.css" rel="stylesheet" type="text/css">
    <script src="https://cdn.ckeditor.com/ckeditor5/35.0.1/classic/ckeditor.js"></script>
</head>

<body class="fixed-left">

    <div id="wrapper">
        <?php include('include/navigationbar.php'); ?>

        <div class="content-page">
            <div class="content">
                <?php include('include/topbar.php'); ?>

                <div class="page-content-wrapper">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="page-title-box">
                                    <div class="btn-group float-right">
                                        <ol class="breadcrumb hide-phone p-0 m-0">
                                            <li class="breadcrumb-item"><a href="#">YogiWhere</a></li>
                                            <li class="breadcrumb-item active">Modifica Classe</li>
                                        </ol>
                                    </div>
                                    <h4 class="page-title">Modifica Classe</h4>
                                </div>
                            </div>
                        </div>

                        <!-- Form per modificare la classe -->
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="card card-body">
                                    <h4 class="card-title font-20 mt-0">Modifica Classe</h4>
                                    <form method="POST" enctype="multipart/form-data">
                                        <div class="form-group">
                                            <label for="nameyogaclass">Nome Classe</label>
                                            <input type="text" class="form-control" id="nameyogaclass" name="nameyogaclass" value="<?php echo htmlspecialchars($classData['nameyogaclass']); ?>" required>
                                        </div>
                                        <div class="form-group">
                                            <label for="idclasscategory">Categoria Classe</label>
                                            <select class="form-control" id="idclasscategory" name="idclasscategory" required>
                                                <?php
                                                // Recupera le categorie esistenti
                                                $query_categories = $conn->query("SELECT * FROM classcategory");
                                                while ($row = $query_categories->fetch_assoc()) {
                                                    $selected = ($row['idclasscategory'] == $classData['idclasscategory']) ? 'selected' : '';
                                                    echo '<option value="' . $row['idclasscategory'] . '" ' . $selected . '>' . $row['namecategory'] . '</option>';
                                                }
                                                ?>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label for="descriptionyogaclass">Descrizione Classe</label>
                                            <textarea class="form-control" id="descriptionyogaclass" name="descriptionyogaclass" rows="10"><?php echo htmlspecialchars($classData['descriptionyogaclass']); ?></textarea>
                                        </div>
                                        <div class="form-group">
                                            <label for="imgyogaclass">Immagine Classe</label>
                                            <input type="file" class="form-control" id="imgyogaclass" name="imgyogaclass">
                                            <input type="hidden" name="existing_img" value="<?php echo $classData['imgyogaclass']; ?>">
                                            <?php if (!empty($classData['imgyogaclass'])): ?>
                                                <img src="uploadphotoclass/<?php echo $classData['imgyogaclass']; ?>" alt="Immagine Classe" style="width: 150px; height: auto;">
                                            <?php endif; ?>
                                        </div>
                                        <div class="form-group">
                                            <label for="productcode">Codice Prodotto (Opzionale)</label>
                                            <input type="text" class="form-control" id="productcode" name="productcode" value="<?php echo htmlspecialchars($classData['productcode']); ?>">
                                        </div>
                                        <button type="submit" class="btn btn-primary">Salva Modifiche</button>
                                        <a href="yogaclass.php" class="btn btn-secondary">Annulla</a>
                                    </form>
                                </div>
                            </div>
                        </div>

                    </div> <!-- container-fluid -->
                </div> <!-- page-content-wrapper -->
            </div> <!-- content -->

            <?php include('include/footer.php'); ?>
        </div> <!-- content-page -->
    </div> <!-- wrapper -->

    <!-- Includi CKEditor -->
    <script>
        ClassicEditor
            .create(document.querySelector('#descriptionyogaclass'))
            .catch(error => {
                console.error(error);
            });
    </script>

    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/js/app.js"></script>
</body>

</html>