<?php
include('include/headscript.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Database connection
$conn = new mysqli($servername, $username, $password, $database);

// Get logged-in user ID
$iduserlogin = $_SESSION['iduserlogin'];

// Process POST request and retrieve owner_id
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $owner_id = isset($_POST['owner_id']) ? intval($_POST['owner_id']) : 0;

    if ($owner_id > 0) {
        // Retrieve owner details
        $queryOwner = $conn->prepare("
            SELECT first_name, last_name, company_name, owner_type 
            FROM property_owners 
            WHERE owner_id = ? AND user_id = ?
        ");
        $queryOwner->bind_param('ii', $owner_id, $iduserlogin);
        $queryOwner->execute();
        $resultOwner = $queryOwner->get_result();
        $ownerDetails = $resultOwner->fetch_assoc();

        if (!$ownerDetails) {
            die('Errore: Proprietario non trovato o accesso non autorizzato.');
        }

        // Set display name
        if ($ownerDetails['owner_type'] === 'individual') {
            $ownerName = $ownerDetails['first_name'] . ' ' . $ownerDetails['last_name'];
        } else {
            $ownerName = $ownerDetails['company_name'];
        }

        // Make owner_id available to JavaScript
        echo "<script>var owner_id = $owner_id;</script>";
    } else {
        die('Errore: ID proprietario non valido.');
    }
} else {
    die('Errore: Accesso non autorizzato.');
}

// Set default slug to "person"
$docpage = "person";

// Retrieve page_id for the "person" slug
$queryPageId = $conn->prepare("SELECT idpages FROM pages WHERE slug = ?");
$queryPageId->bind_param('s', $docpage);
$queryPageId->execute();
$resultPageId = $queryPageId->get_result();
$pageData = $resultPageId->fetch_assoc();

if ($pageData) {
    $page_id = $pageData['idpages']; // Page ID found
} else {
    die("Errore: Pagina non valida."); // Slug not found
}

// Retrieve documents associated with page_id, including sections
$queryDocuments = $conn->prepare("
    SELECT d.*, s.section_name AS section_name
    FROM documents d
    LEFT JOIN sections s ON d.idsections = s.idsections
    WHERE d.page_id = ?
    ORDER BY s.section_name, d.document_name
");
$queryDocuments->bind_param('i', $page_id);
$queryDocuments->execute();
$resultDocuments = $queryDocuments->get_result();

$documents = [];
while ($row = $resultDocuments->fetch_assoc()) {
    $documents[$row['section_name']][] = $row;
}

// Retrieve already uploaded documents for this entity
$queryLoadedDocuments = $conn->prepare("
    SELECT * 
    FROM doc_storage 
    WHERE owner_id = ?
");
$queryLoadedDocuments->bind_param('i', $owner_id);
$queryLoadedDocuments->execute();
$resultLoadedDocuments = $queryLoadedDocuments->get_result();

$loadedDocuments = [];
while ($row = $resultLoadedDocuments->fetch_assoc()) {
    $loadedDocuments[$row['document_id']][] = $row;
}
?>
<!DOCTYPE html>
<html lang="it">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Documenti della Casa</title>

    <!-- Bootstrap 4 CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/dripicons/2.0.0/webfont.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet" />

    <!-- Custom CSS -->
    <link href="assets/css/style.css" rel="stylesheet" type="text/css">

    <!-- Dropzone CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        /* Reset and full page layout */
        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: auto;
        }

        #wrapper {
            display: flex;
            min-height: 100vh;
            flex-direction: column;
        }

        .content-page {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: auto;
        }

        .content {
            flex: 1;
            overflow: auto;
        }

        .page-content-wrapper {
            flex: 1;
            overflow: auto;
        }

        .container-fluid {
            overflow: auto;
        }

        /* Existing styles */
        .section-title {
            font-size: 1.25rem;
            font-weight: bold;
            color: #333;
            margin-bottom: 20px;
        }

        .document-title {
            font-size: 1.1rem;
            font-weight: 500;
            margin-bottom: 10px;
        }

        .dropzone {
            background-color: #f0f8ff;
            border: 2px dashed #007bff;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            transition: background-color 0.3s ease;
        }

        .dropzone:hover {
            background-color: #e6f5ff;
        }

        .dropzone .dz-message {
            font-size: 1.1rem;
            font-weight: 500;
            color: #007bff;
        }

        .dropzone .dz-message i {
            font-size: 3rem;
            margin-bottom: 10px;
            color: #007bff;
        }

        /* Table scrolling */
        .document-list-table {
            display: block;
            max-height: 300px;
            overflow-y: auto;
        }

        .document-list-table tbody {
            display: block;
            overflow-y: auto;
            max-height: 250px;
        }

        .document-list-table thead,
        .document-list-table tbody tr {
            display: table;
            width: 100%;
            table-layout: fixed;
        }

        .section-separator {
            border-top: 2px solid #ddd;
            margin: 40px 0;
        }

        .btn {
            margin-right: 5px;
        }

        .btn.active {
            background-color: #007bff;
            color: #fff;
        }
    </style>
</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'); ?>
                <br>
                <div class="page-content-wrapper">
                    <div class="container-fluid">
                        <!-- Page Title -->
                        <div class="row">
                            <div class="col-sm-12">
                                <h4 class="page-title">Documenti per: <?php echo htmlspecialchars($ownerName); ?></h4>
                            </div>
                        </div>

                        <!-- Documents Sections -->
                        <?php foreach ($documents as $sectionName => $sectionDocuments) { ?>
                            <div class="section-separator"></div>
                            <h5 class="section-title"><?php echo htmlspecialchars($sectionName); ?></h5>

                            <?php foreach ($sectionDocuments as $document) { ?>
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="card card-body mb-4">
                                            <!-- Document Title -->
                                            <p class="document-title">
                                                <?php echo htmlspecialchars($document['document_name']); ?>
                                                <?php if ($document['is_required']) echo "<strong>(Obbligatorio)</strong>"; ?>
                                                <?php if ($document['max_documents'] > 0) echo " - Max: " . $document['max_documents']; ?>
                                            </p>

                                            <!-- Dropzone Area -->
                                            <div class="dropzone mb-3" id="dropzone-<?php echo $document['document_id']; ?>">
                                                <div class="dz-message">
                                                    <i class="fas fa-cloud-upload-alt"></i><br>
                                                    Trascina qui i documenti o clicca per caricare
                                                </div>
                                            </div>

                                            <!-- Uploaded Documents Table -->
                                            <h6 class="mt-4">Documenti già caricati:</h6>
                                            <table class="table table-bordered document-list-table" id="table-<?php echo $document['document_id']; ?>">
                                                <thead>
                                                    <tr>
                                                        <th>Nome Documento</th>
                                                        <th>Data Caricamento</th>
                                                        <th>Azioni</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php if (isset($loadedDocuments[$document['document_id']])) { ?>
                                                        <?php foreach ($loadedDocuments[$document['document_id']] as $loadedDoc) { ?>
                                                            <tr>
                                                                <td>
                                                                    <a href="persondocuments/<?php echo $loadedDoc['filename']; ?>" target="_blank">
                                                                        <?php echo htmlspecialchars($loadedDoc['filename']); ?>
                                                                    </a>
                                                                </td>
                                                                <td><?php echo htmlspecialchars($loadedDoc['created_at']); ?></td>
                                                                <td>
                                                                    <button class="btn btn-danger btn-sm delete-document"
                                                                        data-id="<?php echo $loadedDoc['id']; ?>"
                                                                        data-file="<?php echo $loadedDoc['filename']; ?>">
                                                                        Elimina
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        <?php } ?>
                                                    <?php } ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            <?php } ?>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer (if needed) -->
        <?php include('include/footer.php'); ?>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>

    <!-- Plugin Dropzone -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.js"></script>

    <script>
        // Disattiva auto-discover di Dropzone per evitare inizializzazioni duplicate
        Dropzone.autoDiscover = false;

        // Inizializza Dropzone per ciascun documento
        <?php foreach ($documents as $sectionName => $sectionDocuments) { ?>
            <?php foreach ($sectionDocuments as $document) { ?>
                new Dropzone("#dropzone-<?php echo $document['document_id']; ?>", {
                    url: "upload-document-person.php", // URL per il caricamento
                    paramName: "file", // Nome del campo per il file
                    maxFiles: <?php echo $document['max_documents']; ?>, // Numero massimo di file
                    addRemoveLinks: true,
                    dictDefaultMessage: "Trascina qui i documenti o clicca per caricare",
                    dictRemoveFile: "Rimuovi",
                    acceptedFiles: "application/pdf,image/*", // Solo PDF e immagini
                    init: function() {
                        // Successo nel caricamento
                        this.on("success", function(file, response) {
                            try {
                                // Forza il parsing della risposta se necessario
                                let parsedResponse = typeof response === "string" ? JSON.parse(response) : response;

                                if (parsedResponse.success) {
                                    let tableId = "#table-<?php echo $document['document_id']; ?> tbody";
                                    let row = `
                                        <tr>
                                            <td><a href="persondocuments/${parsedResponse.fileName}" target="_blank">${parsedResponse.fileName}</a></td>
                                            <td>${parsedResponse.uploadDate}</td>
                                            <td>
                                                <button class="btn btn-danger btn-sm delete-document" data-id="${parsedResponse.documentId}" data-file="${parsedResponse.fileName}">
                                                    Elimina
                                                </button>
                                            </td>
                                        </tr>`;
                                    $(tableId).append(row);

                                    // Rimuove il file dalla Dropzone
                                    this.removeFile(file);

                                    // Mostra un messaggio di successo
                                    Swal.fire({
                                        icon: "success",
                                        title: "Caricamento completato",
                                        text: "Documento caricato con successo.",
                                        timer: 1500,
                                        showConfirmButton: false,
                                    });
                                } else {
                                    Swal.fire({
                                        icon: "error",
                                        title: "Errore nel caricamento",
                                        text: parsedResponse.message || "Si è verificato un problema durante il caricamento.",
                                    });
                                }
                            } catch (error) {
                                console.error("Errore nel parsing della risposta:", error, response);
                                Swal.fire({
                                    icon: "error",
                                    title: "Errore",
                                    text: "Risposta dal server non valida.",
                                });
                            }
                        });


                        // Gestione degli errori
                        this.on("error", function(file, errorMessage) {
                            Swal.fire({
                                icon: "error",
                                title: "Errore nel caricamento",
                                text: errorMessage || "Si è verificato un problema.",
                            });
                            this.removeFile(file);
                        });
                    },
                    sending: function(file, xhr, formData) {
                        formData.append("entity_type", "person"); // Indica che è per le persone
                        formData.append("owner_id", owner_id); // Invia l'ID del proprietario dal contesto globale
                        formData.append("document_id", "<?php echo $document['document_id']; ?>");
                    }
                });
            <?php } ?>
        <?php } ?>

        // Elimina documento con SweetAlert
        $(document).on("click", ".delete-document", function() {
            const documentId = $(this).data("id");
            const fileName = $(this).data("file");
            const $row = $(this).closest("tr"); // Trova la riga associata al pulsante

            Swal.fire({
                title: "Sei sicuro?",
                text: "Questa azione eliminerà il documento in modo permanente.",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#d33",
                cancelButtonColor: "#3085d6",
                confirmButtonText: "Sì, elimina",
                cancelButtonText: "Annulla",
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: "delete-document.php",
                        type: "POST",
                        data: {
                            document_id: documentId,
                            file_name: fileName,
                        },
                        success: function(response) {
                            try {
                                const parsedResponse = typeof response === "string" ? JSON.parse(response) : response;

                                if (parsedResponse.success) {
                                    $row.remove(); // Rimuove la riga dalla tabella
                                    Swal.fire({
                                        icon: "success",
                                        title: "Eliminato",
                                        text: "Documento eliminato con successo.",
                                        timer: 1500,
                                        showConfirmButton: false,
                                    });
                                } else {
                                    Swal.fire({
                                        icon: "error",
                                        title: "Errore",
                                        text: parsedResponse.message || "Errore durante l'eliminazione del documento.",
                                    });
                                }
                            } catch (error) {
                                console.error("Errore durante l'eliminazione:", error);
                                Swal.fire({
                                    icon: "error",
                                    title: "Errore",
                                    text: "Risposta dal server non valida.",
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: "error",
                                title: "Errore",
                                text: "Si è verificato un problema con la richiesta.",
                            });
                        },
                    });
                }
            });
        });
    </script>



</body>

</html>