<?php include('include/headscript.php'); ?>
<?php
// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);

// Recupera l'id utente loggato
$iduserlogin = $_SESSION['iduserlogin'];

// Verifica se si sta aggiungendo o modificando un proprietario
$owner_id = isset($_GET['owner_id']) ? intval($_GET['owner_id']) : 0;
$isNew = $owner_id == 0;

// Se è un aggiornamento, recupera i dati esistenti del proprietario
if (!$isNew) {
    $query = $conn->prepare("SELECT * FROM property_owners WHERE owner_id = ? AND user_id = ?");
    $query->bind_param("ii", $owner_id, $iduserlogin);
    $query->execute();
    $result = $query->get_result();
    $ownerData = $result->fetch_assoc();

    // Assegna i valori esistenti ai campi
    $first_name = $ownerData['first_name'];
    $last_name = $ownerData['last_name'];
    $company_name = $ownerData['company_name'];
    $tax_code = $ownerData['tax_code'];
    $email = $ownerData['email'];
    $phone = $ownerData['phone'];
    $address = $ownerData['address'];
    $postal_code = $ownerData['postal_code'];
    $city = $ownerData['city'];
    $province = $ownerData['province'];
    $country = $ownerData['country'];  // ID della tabella auth_countries
    $owner_type = $ownerData['owner_type'];
    $role = $ownerData['role'];
} else {
    // Inizializza i campi vuoti per un nuovo proprietario
    $first_name = $last_name = $company_name = $tax_code = $email = $phone = $address = $postal_code = $city = $province = $country = $role = '';
    $owner_type = 'individual';
}

// Recupera la lista dei paesi dalla tabella auth_countries
$countriesQuery = $conn->prepare("SELECT id, name FROM auth_countries ORDER BY name ASC");
$countriesQuery->execute();
$countriesResult = $countriesQuery->get_result();
?>

<!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><?php echo $isNew ? "Aggiungi Proprietario" : "Modifica Proprietario"; ?></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" />

    <!-- 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">

    <!-- Select2 CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />

    <!-- Select2 JS -->


</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="#">CasaDoc</a></li>
                                            <li class="breadcrumb-item active"><?php echo $isNew ? "Aggiungi Proprietario" : "Modifica Proprietario"; ?></li>
                                        </ol>
                                    </div>
                                    <h4 class="page-title"><?php echo $isNew ? "Aggiungi Proprietario" : "Modifica Proprietario"; ?></h4>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-12">
                                <div class="card card-body">
                                    <form id="owner-form" method="POST" action="save-owner.php">
                                        <input type="hidden" name="owner_id" value="<?php echo $owner_id; ?>">

                                        <!-- Tipo di proprietario -->
                                        <div class="form-group">
                                            <label>Tipo di Proprietario</label>
                                            <select id="owner_type" name="owner_type" class="form-control" required>
                                                <option value="individual" <?php echo $owner_type == 'individual' ? 'selected' : ''; ?>>Persona Fisica</option>
                                                <option value="company" <?php echo $owner_type == 'company' ? 'selected' : ''; ?>>Società</option>
                                            </select>
                                        </div>

                                        <!-- Nome e Cognome o Nome della Società -->
                                        <div class="form-group individual-field">
                                            <label>Nome</label>
                                            <input type="text" name="first_name" class="form-control" value="<?php echo htmlspecialchars($first_name); ?>">
                                        </div>

                                        <div class="form-group individual-field">
                                            <label>Cognome</label>
                                            <input type="text" name="last_name" class="form-control" value="<?php echo htmlspecialchars($last_name); ?>">
                                        </div>

                                        <div class="form-group company-field" style="display:none;">
                                            <label>Nome della Società</label>
                                            <input type="text" name="company_name" class="form-control" value="<?php echo htmlspecialchars($company_name); ?>">
                                        </div>

                                        <!-- Codice Fiscale o Partita IVA -->
                                        <div class="form-group">
                                            <label>Codice Fiscale / Partita IVA</label>
                                            <input type="text" name="tax_code" class="form-control" value="<?php echo htmlspecialchars($tax_code); ?>" required>
                                        </div>

                                        <!-- Email -->
                                        <div class="form-group">
                                            <label>Email</label>
                                            <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($email); ?>" required>
                                        </div>

                                        <!-- Telefono -->
                                        <div class="form-group">
                                            <label>Telefono</label>
                                            <input type="text" name="phone" class="form-control" value="<?php echo htmlspecialchars($phone); ?>">
                                        </div>

                                        <!-- Indirizzo -->
                                        <div class="form-group">
                                            <label>Indirizzo</label>
                                            <input type="text" name="address" class="form-control" value="<?php echo htmlspecialchars($address); ?>">
                                        </div>

                                        <!-- CAP -->
                                        <div class="form-group">
                                            <label>CAP</label>
                                            <input type="text" name="postal_code" class="form-control" value="<?php echo htmlspecialchars($postal_code); ?>">
                                        </div>

                                        <!-- Città -->
                                        <div class="form-group">
                                            <label>Città</label>
                                            <input type="text" name="city" class="form-control" value="<?php echo htmlspecialchars($city); ?>">
                                        </div>

                                        <!-- Provincia -->
                                        <div class="form-group">
                                            <label>Provincia</label>
                                            <input type="text" name="province" class="form-control" value="<?php echo htmlspecialchars($province); ?>">
                                        </div>

                                        <!-- Nazione (Dropdown con valori da auth_countries) -->
                                        <div class="form-group">
                                            <label>Nazione</label>
                                            <select name="country" class="form-control">
                                                <?php while ($row = $countriesResult->fetch_assoc()) { ?>
                                                    <option value="<?php echo $row['id']; ?>" <?php echo $country == $row['id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($row['name']); ?>
                                                    </option>
                                                <?php } ?>
                                            </select>
                                        </div>

                                        <!-- Ruolo -->
                                        <div class="form-group">
                                            <label>Ruolo</label>
                                            <input type="text" name="role" class="form-control" value="<?php echo htmlspecialchars($role); ?>">
                                        </div>

                                        <button type="submit" class="btn btn-primary"><?php echo $isNew ? "Aggiungi Proprietario" : "Salva Modifiche"; ?></button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div><!-- container -->
                </div><!-- Page content Wrapper -->
            </div><!-- content -->
            <?php include('include/footer.php'); ?>
        </div><!-- End Right content here -->
    </div><!-- END wrapper -->

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            function toggleOwnerFields() {
                if ($('#owner_type').val() === 'individual') {
                    $('.individual-field').show();
                    $('.company-field').hide();
                } else {
                    $('.individual-field').hide();
                    $('.company-field').show();
                }
            }

            // Inizializza la visualizzazione corretta dei campi in base al tipo di proprietario
            toggleOwnerFields();

            // Cambia la visualizzazione dei campi quando cambia il tipo di proprietario
            $('#owner_type').change(function() {
                toggleOwnerFields();
            });
        });
    </script>
    <script>
        $(document).ready(function() {
            // Inizializza Select2 per il campo country
            $('select[name="country"]').select2({
                placeholder: 'Seleziona una nazione',
                allowClear: true
            });

            // Funzione per mostrare/nascondere i campi in base al tipo di proprietario
            function toggleOwnerFields() {
                if ($('#owner_type').val() === 'individual') {
                    $('.individual-field').show();
                    $('.company-field').hide();
                } else {
                    $('.individual-field').hide();
                    $('.company-field').show();
                }
            }

            // Inizializza la visualizzazione corretta dei campi
            toggleOwnerFields();

            // Cambia la visualizzazione dei campi quando cambia il tipo di proprietario
            $('#owner_type').change(function() {
                toggleOwnerFields();
            });
        });
    </script>

</body>

</html>