<?php
// Attiva errori PHP per debug
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Connessione al database e query
include '../../Connections/repnew.php';
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$stmt = $conn->prepare("SELECT * FROM reportsections LIMIT 1");
if (!$stmt) {
    die("Statement preparation failed: " . $conn->error);
}
$stmt->execute();
$result = $stmt->get_result();
$insertdata = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$conn->close();

// Verifica dei dati
if (empty($insertdata)) {
    die("No data found in reportsections.");
}

$jsonData = json_encode($insertdata[0], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
?>

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


<style>
    .modal-dialog {
        max-width: none !important;
        width: auto !important;
    }

    .custom-modal-dialog {
        max-width: 70vw !important;
        width: 70vw !important;
        height: 85vh !important;
        margin: 50px auto !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
    }

    .modal-content {
        width: 100% !important;
        height: 100% !important;
    }

    .pagetitle {
        font-size: 1.5vw !important;
    }

    .custom-textarea {
        font-size: 1vw !important;
        width: 100% !important;
        height: 20vh !important;
        padding: 10px !important;
        border-radius: 10px !important;
    }

    .modal-body {
        overflow-y: auto !important;
        height: 60vh !important;
        padding: 20px !important;
        box-sizing: border-box !important;
    }

    .modalspinner {
        border: 8px solid #f3f3f3;
        border-top: 8px solid #3498db;
        border-radius: 50%;
        width: 60px;
        height: 60px;
        animation: spin 1s linear infinite;
        position: fixed;
        top: 40%;
        left: 50%;
        transform: translate(-90%, -50%);
        z-index: 9999;
    }

    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }
</style>
</head>

<body>

    <!-- Modale -->
    <div class="modal fade" id="documentModal" tabindex="-1" aria-labelledby="documentModalLabel" aria-hidden="true"
        role="dialog" data-backdrop="static" data-bs-keyboard="false">

        <div class="modal-dialog custom-modal-dialog custom-modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="pagetitle">Finalcial Report</h5>
                    <button type="button" class="btn-close" data-dismiss="modal" aria-label="false" id="btn-close">
                        <span>&times</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="modalspinner" class="modalspinner" style="display: none;"></div>
                    <div class="mb-3 row">
                        <label for="title" class="col-sm-1 col-form-label">Title</label>
                        <div class="col-sm-11">
                            <input type="text" class="form-control" id="title" value="<?php echo ($insertdata[0]['cover_title']) ?>">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label for="subtitle" class="col-sm-1 col-form-label">Subtitle</label>
                        <div class="col-sm-11">
                            <input type="text" class="form-control" id="subtitle" value="<?php echo ($insertdata[0]['cover_subtitle']) ?>">
                        </div>
                    </div>
                    <div class="page1">
                        <div class="mb-3 row">
                            <label for="section1" class="col-sm-1 col-form-label">Section1</label>
                            <div class="col-sm-11">
                                <input type="text" class="form-control" id="section1" placeholder="section1" value="<?php echo ($insertdata[0]['instructionsdetails_title']) ?>">
                            </div>
                        </div>
                        <div class="mb-3 row">
                            <div class="col-sm-12">
                                <div type="text" class="content" id="content1"><?php echo ($insertdata[0]['instructiondetails_text']) ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="page2">
                        <div class="mb-3 row">
                            <label for="section2" class="col-sm-1 col-form-label">Section2</label>
                            <div class="col-sm-11">
                                <input type="text" class="form-control" id="section2" placeholder="section2" value="<?php echo ($insertdata[0]['overviewstatistic_title']) ?>">
                            </div>
                        </div>
                        <div class="mb-3 row">
                            <div class="col-sm-12">
                                <div type="text" class="content" id="content2"><?php echo ($insertdata[0]['overviewstatistic_text']) ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="page3">
                        <div class="mb-3 row">
                            <label for="section3" class="col-sm-1 col-form-label">Section3</label>
                            <div class="col-sm-11">
                                <input type="text" class="form-control" id="section3" placeholder="section3" value="<?php echo ($insertdata[0]['supplieristatistic_title']) ?>">
                            </div>
                        </div>
                        <div class="mb-3 row">
                            <div class="col-sm-12">
                                <div type="text" class="content" id="content3"><?php echo ($insertdata[0]['supplieristatistic_text']) ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="page4">
                        <div class="mb-3 row">
                            <label for="section4" class="col-sm-1 col-form-label">Section4</label>
                            <div class="col-sm-11">
                                <input type="text" class="form-control" id="section4" placeholder="section4" value="<?php echo ($insertdata[0]['analysisstatistic_title']) ?>">
                            </div>
                        </div>
                        <div class="mb-3 row">
                            <div class="col-sm-12">
                                <div type="text" class="content" id="content4"><?php echo ($insertdata[0]['analysisstatistic_text']) ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="page5">
                        <div class="mb-3 row">
                            <label for="section5" class="col-sm-1 col-form-label">Section5</label>
                            <div class="col-sm-11">
                                <input type="text" class="form-control" id="section5" placeholder="section5" value="<?php echo ($insertdata[0]['analytscompounds_title']) ?>">
                            </div>
                        </div>
                        <div class="mb-3 row">
                            <div class="col-sm-12">
                                <div type="text" class="content" id="content5"><?php echo ($insertdata[0]['analytscompounds_text']) ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="page6">
                        <div class="mb-3 row">
                            <label for="section6" class="col-sm-1 col-form-label">Section6</label>
                            <div class="col-sm-11">
                                <input type="text" class="form-control" id="section6" placeholder="section6" value="<?php echo ($insertdata[0]['finalevaluation_title']) ?>">
                            </div>
                        </div>
                        <div class="mb-3 row">
                            <div class="col-sm-12">
                                <div type="text" class="content" id="content6"><?php echo ($insertdata[0]['finalevaluation_text']) ?></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer mb-3">
                    <button type="button" class="btn btn-danger" id="createPdf">PDF</button>
                    <button type="button" class="btn btn-success" id="createWord">Word</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap, jQuery, CKEditor e html2canvas -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

    <script>
        let titles = [];
        let contents = [];
        let chartdata = [];
        const editors = [];
        const spinner = document.getElementById('modalspinner');

        for (let i = 1; i < 7; i++) {
            ClassicEditor
                .create(document.querySelector('#content' + i), {
                    toolbar: [
                        'bold', 'italic', 'bulletedList', 'numberedList', 'alignment', 'undo', 'redo'
                    ]
                })
                .then(editor => {
                    editors[i - 1] = editor;
                })
                .catch(error => {
                    console.error('Error initializing CKEditor for content' + i + ':', error);
                });
        }

        function disableModal(flag) {
            document.getElementById('btn-close').disabled = flag;
            document.getElementById('title').disabled = flag;
            document.getElementById('subtitle').disabled = flag;
            document.getElementById('section1').disabled = flag;
            document.getElementById('content1').disabled = flag;
            document.getElementById('section2').disabled = flag;
            document.getElementById('content2').disabled = flag;
            document.getElementById('section3').disabled = flag;
            document.getElementById('content3').disabled = flag;
            document.getElementById('section4').disabled = flag;
            document.getElementById('content4').disabled = flag;
            document.getElementById('section5').disabled = flag;
            document.getElementById('content5').disabled = flag;
            document.getElementById('section6').disabled = flag;
            document.getElementById('content6').disabled = flag;
        }

        document.getElementById('createPdf').addEventListener('click', function() {
            disableModal(true);
            spinner.style.display = 'block';
            contents = [];
            contents.push(document.getElementById('subtitle').value);
            editors.forEach((editor, index) => {
                const data = editor.getData();
                const selectedElement = editor.model.document.selection.getSelectedElement();
                const styles = selectedElement ? selectedElement.getAttribute('style') || 'No style applied' : 'No style applied';
                contents.push(data);
            });
            getTitleData();
            createChart('pdf');
        });

        document.getElementById('createWord').addEventListener('click', function() {
            disableModal(true);
            spinner.style.display = 'block';
            contents = [];
            contents.push(document.getElementById('subtitle').value);
            editors.forEach((editor, index) => {
                const data = editor.getData();
                const selectedElement = editor.model.document.selection.getSelectedElement();
                const styles = selectedElement ? selectedElement.getAttribute('style') || 'No style applied' : 'No style applied';
                contents.push(data);
            });
            getTitleData();
            createChart('word');
        });

        function getTitleData() {
            titles = [];
            titles.push(document.getElementById('title').value);
            for (let i = 1; i < 7; i++) {
                titles.push(document.getElementById('section' + i).value);
            }
        }

        function createPdf() {
            filterStart = document.getElementById('startDate').value;
            filterEnd = document.getElementById('endDate').value;
            try {
                $.ajax({
                    url: 'createPdf.php',
                    type: 'POST',
                    data: {
                        title: titles,
                        content: contents,
                        filterStart: filterStart,
                        filterEnd: filterEnd
                    },
                    dataType: 'json',
                    success: function(response) {
                        const fileurl = response['message'] + response['file'];
                        const filename = response['file'];
                        fetch(fileurl)
                            .then((response) => response.blob())
                            .then((blob) => {
                                console.log("blob", blob);
                                const url = window.URL.createObjectURL(blob);
                                const a = document.createElement("a");
                                a.style.display = "none";
                                a.href = url;
                                console.log('second - ', url);
                                console.log(filename);
                                a.download = filename;
                                document.body.appendChild(a);
                                a.click();
                                window.URL.revokeObjectURL(url);
                            })
                            .catch((error) => console.error("error downloading file", error));
                        console.log('success', response);
                    },
                    error: function(response) {
                        alert('PDF download fail');
                        console.log('error', response);
                    }

                });
            } catch (error) {
                alert(error);
            } finally {
                disableModal(false);
                spinner.style.display = 'none';
            }
        }

        const chartIds = [1, 2, 3, 4, 5, 6];

        async function createChart(flag) {
            var formData = new FormData();

            for (const chartId of chartIds) {
                try {
                    let chartElement = document.getElementById('chart' + chartId);
                    const canvas = await html2canvas(chartElement, {
                        backgroundColor: 'ffffff',
                        scale: 5
                    });
                    const chartImg = canvas.toDataURL('image/png');

                    formData.append('chartfile[]', chartImg);

                } catch (error) {
                    console.log('Capture error:', error);
                }
            }

            try {
                const response = await fetch('create_chart.php', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('Error creating images:', errorText);
                } else {
                    const result = await response.text();
                    if (flag == 'pdf') createPdf();
                    if (flag == 'word') createWord();
                }
            } catch (error) {
                console.error('Fetch error:', error);
            }
        }

        function createWord() {
            filterStart = document.getElementById('startDate').value;
            filterEnd = document.getElementById('endDate').value;
            createChart();
            try {
                $.ajax({
                    url: 'createWord.php',
                    type: 'POST',
                    data: {
                        title: titles,
                        content: contents,
                        filterStart: filterStart,
                        filterEnd: filterEnd,
                    },
                    dataType: 'json',
                    success: function(response) {
                        const url = response['message'] + response['file'];
                        const filename = response['file'];
                        console.log(url, "----", filename);
                        fetch(url)
                            .then((response) => response.blob())
                            .then((blob) => {
                                const url = window.URL.createObjectURL(blob);
                                console.log(url);
                                const a = document.createElement("a");
                                a.style.display = "none";
                                a.href = url;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.click();
                                window.URL.revokeObjectURL(url);
                            })
                            .catch((error) => console.error("error downloading file", error));
                        console.log('success', response);
                    },
                    error: function(response) {
                        alert('WORD download fail');
                        console.log('error', response);
                    }

                });
            } catch (error) {
                alert(error);
            } finally {
                disableModal(false);
                spinner.style.display = 'none';
            }
        }
    </script>

</body>

</html>