<?php include('include/headscript.php'); ?>
<?php require_once 'class/db-functions.php'; ?>

<?php
// Inizializza la connessione al database con la classe DBHandlerSelect
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();

// Verifica se si sta aggiungendo una nuova casa o aggiornando una esistente
$idhome = isset($_GET['idhome']) ? intval($_GET['idhome']) : 0;
$isNew = ($idhome == 0);

if ($isNew) {
    // Inserisci un nuovo record
    $insertQuery = $pdo->prepare("INSERT INTO home (iduser) VALUES (:iduser)");
    $insertQuery->execute(['iduser' => $iduserlogin]);
    $idhome = $pdo->lastInsertId();

    // Ricarica la pagina con il nuovo idhome
    header("Location: manage-home-tabs.php?idhome=$idhome");
    exit();
}

// Carica i dati della casa
$query = $pdo->prepare("SELECT * FROM home WHERE idhome = :idhome AND iduser = :iduser");
$query->execute(['idhome' => $idhome, 'iduser' => $iduserlogin]);
$homeData = $query->fetch();

// Assegna i valori
$namedb = $homeData['name'] ?? '';
$addressdb = $homeData['address'] ?? '';
$countrydb = $homeData['country'] ?? '';
$citydb = $homeData['city'] ?? '';
$zipdb = $homeData['zip'] ?? '';
$commentdb = $homeData['comment'] ?? '';
$latitudedb = $homeData['latitude'] ?? '';
$longitudedb = $homeData['longitude'] ?? '';
$fulladdressdb = $homeData['fulladdress'] ?? '';
$mainphoto = !empty($homeData['mainphoto']) ? 'mainphoto/' . $homeData['mainphoto'] : 'assets/images/no-image.jpg';
?>

<!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">
    <title>Gestione Immobile</title>
    <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">
    <!-- Select2 CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.css" rel="stylesheet">

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Popper.js (necessario per Bootstrap) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- Select2 JS con fallback -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/js/select2.min.js"></script>
    <!-- DataTables JS -->
    <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>
    <!-- Dropzone JS -->
    <script src="https://cdn.jsdelivr.net/npm/dropzone@5.9.2/dist/dropzone.min.js"></script>
    <!-- MD5 JS -->
    <script src="https://cdn.jsdelivr.net/npm/md5-js@0.0.3/md5.min.js"></script>
    <script>
        // Fallback per Select2
        if (typeof $.fn.select2 === "undefined") {
            document.write('<script src="assets/js/select2.min.js"><\/script>');
        }
    </script>
    <style>
        /* Stile per il banner */
        .header-banner-overlay {
            position: relative;
            width: 100%;
            background: linear-gradient(to right, rgba(30, 58, 138, 0.8), rgba(255, 255, 255, 0.2));
            padding: 20px;
            display: flex;
            align-items: center;
            color: white;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .header-banner-overlay img {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 8px;
            margin-right: 20px;
            border: 2px solid #fff;
        }

        .header-banner-overlay .property-info h2 {
            font-size: 24px;
            margin: 0;
            font-weight: bold;
            color: #ffffff;
        }

        .header-banner-overlay .property-info p {
            font-size: 14px;
            margin: 5px 0 0;
            opacity: 0.9;
        }

        .header-banner-overlay .property-info .status {
            font-size: 12px;
            background: #28a745;
            padding: 5px 10px;
            border-radius: 12px;
            display: inline-block;
            margin-top: 10px;
        }

        /* Stile per i tab */
        .nav-tabs .nav-link {
            font-weight: bold;
            color: #495057;
        }

        .nav-tabs .nav-link.active {
            color: #007bff;
            border-color: #007bff;
        }

        #map {
            height: 400px;
            width: 100%;
        }

        .success-flash {
            background-color: #d4edda !important;
            transition: background-color 1s ease;
        }
    </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'); ?>
                <div class="page-content-wrapper">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="page-title-box d-flex justify-content-between align-items-center">
                                    <h4 class="page-title m-0"><?php echo $isNew ? "Aggiungi Casa" : "Gestisci Casa"; ?></h4>
                                    <button onclick="history.back()" class="btn btn-dark">
                                        <i class="fas fa-arrow-left"></i> Torna indietro
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Banner -->
                        <div class="header-banner-overlay">
                            <img src="<?php echo htmlspecialchars($mainphoto); ?>" alt="Foto Immobile">
                            <div class="property-info">
                                <h2><?php echo htmlspecialchars($namedb ?: 'Nuovo Immobile'); ?></h2>
                                <p><?php echo htmlspecialchars($fulladdressdb ?: 'Indirizzo non specificato'); ?></p>
                                <span class="status"><?php echo $isNew ? 'Nuovo' : 'Attivo'; ?></span>
                            </div>
                        </div>

                        <!-- Tab Navigation -->
                        <ul class="nav nav-tabs" id="propertyTabs" role="tablist">
                            <li class="nav-item">
                                <a class="nav-link" id="details-tab" data-toggle="tab" href="#details" role="tab" aria-controls="details" aria-selected="false">Dettagli</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" id="documents-tab" data-toggle="tab" href="#documents" role="tab" aria-controls="documents" aria-selected="true">Documenti</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" id="owners-tab" data-toggle="tab" href="#owners" role="tab" aria-controls="owners" aria-selected="false">Proprietari</a>
                            </li>
                        </ul>

                        <!-- Tab Content -->
                        <div class="tab-content" id="propertyTabsContent">
                            <!-- Tab Dettagli -->
                            <div class="tab-pane fade" id="details" role="tabpanel" aria-labelledby="details-tab">
                                <?php include('tabs/dettagli.php'); ?>
                            </div>
                            <!-- Tab Documenti -->
                            <div class="tab-pane fade show active" id="documents" role="tabpanel" aria-labelledby="documents-tab">
                                <?php include('tabs/documenti.php'); ?>
                            </div>
                            <!-- Tab Proprietari -->
                            <div class="tab-pane fade" id="owners" role="tabpanel" aria-labelledby="owners-tab">
                                <?php include('tabs/proprietari.php'); ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include('include/footer.php'); ?>
        </div>
    </div>

    <!-- Google Maps API -->
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyADtQRKgCpJNnQCP8QvBeKDcm0TrTPpsGY&libraries=places&callback=initAutocomplete"></script>
</body>

</html>