<?php 
include("../includes/inc-config.php");

include(CHEMIN."includes/inc-header.php");
include(CHEMIN."includes/inc-fonctions.php");

include(CHEMIN."includes/Spyc.php");
include(CHEMIN."includes/yaml-readwriteclass.php");
$zine=new yamlreadwrite(); 

if(isset($_FILES) && is_array($_FILES) && count($_FILES)) {
    $output = array();
    $output['FILES'] = $_FILES;
    $chemin_fichier=str_replace(URL,CHEMIN,current(explode("?", $_POST['nom_fichier'])));
    $nom_fichier=fichier_seul($chemin_fichier);
    $chemin_dossier=str_replace($nom_fichier,"",$chemin_fichier);

    if (strpos($chemin_fichier, 'originaux') !== false) { // l'image vient des originaux
        // sauver l'image sans le nom originaux
        $chemin_dossier=str_replace("originaux/","",$chemin_dossier);

    } else { // l'image n'a pas encore été modifiée, sauver l'original
        fix_exists_dir($chemin_dossier."originaux"); 
        copy($chemin_fichier, $chemin_dossier."originaux/".$nom_fichier);
    }
    if(move_uploaded_file($_FILES['croppedImage']['tmp_name'], $chemin_dossier.$nom_fichier)){
        echo "OK";
    } else {
        echo "raté";
    }
    // virer les vignettes de cette image
    $vignette=current(explode(".", $nom_fichier));
    foreach(glob(CHEMIN.DOSSIER_VIGNETTES."/".$vignette."*") as $fichier){
        unlink($fichier);
    }
    die();
} 

if(!isset($_GET['image'])){
    echo "pas d'image";
    die();
} else {
    if(isset($_GET['original'])){
        $image_seule=basename($_GET['image']);
        $dossier=str_replace(basename($image_seule),"",$_GET['image']);
        $image=$dossier."originaux/".$image_seule;

    } else {
        $image=$_GET['image'];
        $image_seule=basename($image);
        $dossier=str_replace("/".$image_seule,"",$image);
    }

    $source=$dossier."/config_zine.yaml";
    $zine->yamlread($source);
    $infos = $zine->yaml_simple_array();
    $format=$tailles_zine[$infos["format_zine"]];

    $wpix=floor($format['width']-($infos["taille_marge"]*2));
    $hpix=floor($format['height']-($infos["taille_marge"]*2));


}
?>

<script src="<?= URL; ?>assets/cropper/cropper.min.js"></script>
<link rel="stylesheet" href="<?= URL; ?>assets/cropper/cropper.min.css">
<script src="<?= URL; ?>assets/cropper/jquery-cropper.js"></script>

<main id="main" class="container-fluid px-4">
    <div class="row my-4">
        <div class="col-12 texte mb-4">
             <h2>Modifier le document</h2>
        </div>
    <div class="row">
        <div class="col-12 col-sm-9 col-md-6 h-100">
            <div id="image_container">
                <?php 
                $public_url=str_replace(CHEMIN,URL,$image);
                ?>
                <img id="image" class="h-100" src="<?= $public_url; ?>">
            </div>
        </div>
        <div class="col-12 col-sm-3 col-md-6 p-3">
           
            <div class="mb-5">
                <p>Vous pouvez recadrer et effectuer une rotation sur le document.<br>
                    Attention ! Ces modifications sont irréversibles !
                </p>
                <p>
                    Pour annuler les modifications, il suffit de cliquer sur le bouton "Retour".
                </p>
            </div>
            <div>
                <div class="btn-group mb-3" role="group" aria-label="First group">
                    <button type="button" class="btn btn-primary btn-lg cropper-rotate" data-angle="90"><i class="bi bi-arrow-clockwise"></i>
                    </button>
                    <button type="button" class="btn btn-primary btn-lg cropper-rotate" data-angle="-90"><i class="bi bi-arrow-counterclockwise"></i>
                    </button>
                </div>
                <div class="btn-group mb-3 " role="group" aria-label="second group">

                    <button type="button" class="ms-3 btn btn-primary btn-lg cropper-centrer" title="centrer"><i class="bi bi-file-plus"></i></button>

                </div>
            </div>
            <div>
                <div class="btn-group" role="group" aria-label="Third group">
                    <button id="cropper-submit" type="button" class="btn btn-success text-light">Modifier</button>
                </div>
                <div class="mt-3" role="group" aria-label="Third group">
                    <a href="zine_gerer_propositions.php?zine=<?= $dossier; ?>" type="button" class="btn btn-danger text-light">Retour</a>
                </div>
            </div>
        </div>
    </div>
</main>
<script>
    var $image = $('#image');
    $image.cropper({
        aspectRatio: <?= $wpix; ?> / <?= $hpix; ?>,
        viewMode: 2,
        crop: function(e) {

    }
                   });

    // Get the Cropper.js instance after initialized
    var cropper = $image.data('cropper');

    $("#cropper-submit").click(function(){
        var nom_fichier=$image.attr("src");
        var extension=nom_fichier.split('.').pop();
        var mime="image/png";
        var qualite="";
        if(extension=="jpg"){
            mime="image/jpeg";
            qualite="0.8";
        }

        cropper.getCroppedCanvas().toBlob(function (blob) {
            var formData = new FormData();
            formData.append('nom_fichier', nom_fichier);
            formData.append('croppedImage', blob);
            formData.append('zine', '<?= $dossier; ?>');
            // Use `jQuery.ajax` method
            $.ajax({
                //url: 
                method: "POST",
                data: formData,
                processData: false,
                contentType: false,
                success: function (m) {
                    console.log('Upload success '+m);
                    //alert(m);
                    var retour="zine_gerer_propositions.php?zine=<?= $dossier; ?>";

                    window.location.href = retour;
                },
                error: function () {
                    console.log('Upload error');
                }
            });
        },mime,qualite);

    });

    $(".cropper-rotate").click(function(){
        var angle=$(this).attr("data-angle");
        cropper.rotate(angle);
    });
    
    $(".cropper-centrer").click(function(){
            var imageData = cropper.getImageData();
            var canvasData = cropper.getContainerData();
            cropper.zoomTo(0.1);

            var px=(canvasData.width-imageData.width)/2;
            var py=(canvasData.height-imageData.height)/2;
            cropper.moveTo(px,py);

        });
function stopZoom (e) {
            var image = $(this).cropper('getImageData'),
                zoomLevel = image.width / image.naturalWidth;

            if (zoomLevel > 10 || zoomLevel < 0.1) {
                e.preventDefault();
            }
        }

</script>


<?php 
include("inc-admin-footer.php");
include("../includes/inc-footer.php");
?>