<?php
require_once("header.php");
require_once("left_sidebar.php");
$errori_input[] = " Errore Generico ";
$sql_info = "SELECT * FROM clienti order by id_cliente";
list($status_info,$contenuto_info,$nrows_info) = read_db_pdo($sql_info);

$sql_impostazioni = "SELECT * FROM impostazioni";
list($status_impostazioni,$contenuto_impostazioni,$nrows_impostazioni) = read_db_pdo($sql_impostazioni);
$abilita_test = $contenuto_impostazioni[0]["test"];

$counter = count($contenuto_info);
$todays_date = date("Y-m-d H:i:s");
$index = 0;

  for ($index = 0; $index < $counter; $index++) {
	
	$scadenza = $contenuto_info[$index]["scadenza"];
	
   if($todays_date > $scadenza) {
	$array_linea = array(
			'id_cliente' => $contenuto_info[$index] ["id_cliente"],
			'stato' => 0,
			'scadenza' => $contenuto_info[$index]["scadenza"],
		    'isTest' => 0
	);
	try {
	
      $db->beginTransaction();
	  $sql_query="UPDATE clienti SET stato=:stato, scadenza=:scadenza, isTest=:isTest WHERE id_cliente=:id_cliente";
	  list($status_linea,$nrows_linea) = write_db_pdo_trans($sql_query,$array_linea);
	  $db->commit();	
   }
   catch(WriteDBException $e) {
	$db->rollBack();
	$pdo_error = $e->getMessage();
	echo "errore db 1 $pdo_error ";
	exit;
	} catch(ReadDBException $e) {
	$db->rollBack();
	$pdo_error = $e->getMessage();
	echo "errore db 2 $pdo_error ";
	exit;
	}
   }
  }

?>
<style>/* Stili di base per la pagina */
.content-wrapper {
    background-color: #000000 !important;
    color: #ffffff !important;
}

/* Stili per la card principale */
.card {
    background: #0c161c !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
}

.card-title {
    color: #00ffff !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    padding: 15px !important;
}

/* Stili per la tabella */
.table {
    color: #ffffff !important;
    background: #0c161c !important;
}

.table thead th {
    background: #000000 !important;
    color: #00ffff !important;
    border-color: rgba(255, 255, 255, 0.1) !important;
}

.table td, .table th {
    border-color: rgba(255, 255, 255, 0.1) !important;
    padding: 12px !important;
}

/* Stili per i badge di stato */
.badge-outline-success {
    color: #00ffaa !important;
    border: 1px solid #00ffaa !important;
}

.badge-outline-warning {
    color: #ffaa00 !important;
    border: 1px solid #ffaa00 !important;
}

.badge-outline-danger {
    color: #ff3366 !important;
    border: 1px solid #ff3366 !important;
}

/* Stili per i modali */
.modal-content {
    background: #0c161c !important;
    color: #ffffff !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
}

.modal-header {
    border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
}

.modal-footer {
    border-top: 1px solid rgba(255, 255, 255, 0.1) !important;
}

/* Stili per i form */
.form-control {
    background: rgba(255, 255, 255, 0.1) !important;
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    color: #ffffff !important;
}

.form-control:disabled {
    background: rgba(255, 255, 255, 0.05) !important;
    color: rgba(255, 255, 255, 0.5) !important;
}

/* Stili per i bottoni */
.btn-danger, .btn-success, .btn-primary, .btn-warning, .btn-info {
    background: linear-gradient(90deg, #00ffff, #ff00ff) !important;
    background-size: 200% 100% !important;
    border: none !important;
    color: white !important;
    font-weight: bold !important;
    animation: gradientAnimation 3s ease infinite !important;
    transition: all 0.3s ease !important;
}

.btn:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 0 10px rgba(0, 255, 255, 0.5) !important;
}

/* Stili per DataTables */
.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter,
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_processing,
.dataTables_wrapper .dataTables_paginate {
    color: #ffffff !important;
}

.dataTables_wrapper .dataTables_paginate .paginate_button {
    color: #ffffff !important;
}

.dataTables_wrapper .dataTables_paginate .paginate_button.current {
    background: linear-gradient(90deg, #00ffff, #ff00ff) !important;
    border: none !important;
    color: white !important;
}

/* Stili per le notifiche toast */
.jq-toast-wrap {
    background: #0c161c !important;
    color: #ffffff !important;
}

/* Animazione gradiente */
@keyframes gradientAnimation {
    0% {
        background-position: 0% 50%;
    }
    50% {
        background-position: 100% 50%;
    }
    100% {
        background-position: 0% 50%;
    }
}
/* Stile per la sidebar sinistra */
.sidebar {
    background: black !important;
    border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
}

/* Stile per i link della sidebar */
.sidebar .nav-item .nav-link {
    color: #ffffff !important;
    transition: all 0.3s ease !important;
}

.sidebar .nav-item .nav-link:hover {
    background: rgba(0, 255, 255, 0.1) !important;
    color: #00ffff !important;
}

/* Stile per l'icona e il testo del logo */
.sidebar .navbar-brand {
    background: #0c161c !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
}

/* Stile per le divisioni tra i menu */
.sidebar .nav-item {
    border-bottom: 1px solid rgba(255, 255, 255, 0.05) !important;
}

/* Stile per le icone nella sidebar */
.sidebar .nav-link i {
    color: #00ffff !important;
}

/* Stile per l'item attivo */
.sidebar .nav-item.active .nav-link {
    background: linear-gradient(90deg, #00ffff20, transparent) !important;
    color: #00ffff !important;
}

/* Stile per il testo del menu */
.nav-link span {
    color: #ffffff !important;
}

/* Hover effect per i link */
.nav-link:hover span {
    color: #00ffff !important;
}

/* Stile per il separatore */
.sidebar-divider {
    border-color: rgba(255, 255, 255, 0.1) !important;
}
/* Stile per i select dropdown */
select.form-control {
    background-color: #0c161c !important;
    color: #ffffff !important;
    border-color: rgba(255, 255, 255, 0.2) !important;
}

select.form-control option {
    background-color: #0c161c !important;
    color: #ffffff !important;
    padding: 10px !important;
}

select.form-control option:hover,
select.form-control option:focus,
select.form-control option:active,
select.form-control option:checked {
    background: linear-gradient(90deg, #00ffff20, transparent) !important;
    color: #00ffff !important;
}

/* Stile per il contenitore del select quando è aperto */
select.form-control:focus {
    background-color: #0c161c !important;
    border-color: #00ffff !important;
    box-shadow: 0 0 0 0.2rem rgba(0, 255, 255, 0.25) !important;
}

/* Stile per le opzioni selezionate */
select.form-control option:checked {
    background: linear-gradient(90deg, #00ffff40, transparent) !important;
    color: #00ffff !important;
}
.navbar .navbar-brand-wrapper {
    border-right: 0px solid #000000;
}
.bg-danger {
    background-color: #4a00ff !important;
}
.bg-warning {
    background-color: #4a00ff !important;
}
.bg-primary, .settings-panel .color-tiles .tiles.primary {
    background-color: #4a00ff !important;
}
.modal .modal-dialog .modal-content .modal-header .close span {
    font-size: 34px;
    font-weight: 400;
    color: #02feff;
}
</style>
<link rel="stylesheet" href="vendors/datatables.net-bs4/dataTables.bootstrap4.css">
<link rel="stylesheet" href="vendors/jquery-toast-plugin/jquery.toast.min.css">

<div class="content-wrapper">

    <div class="card">
        <div class="card-body">
			<h4 class="card-title">Gestione Clienti</h4>
<!-------- INIZIO MODAL AGGIUNGI ------------->			
			<div class="modal fade" id="aggiungi_cliente" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" style="display: none;" aria-hidden="true">
                <div class="modal-dialog" role="document">
					<form class="forms-sample " name="aggiungi_cliente_f" id="aggiungi_cliente_f">
						<div class="modal-content">
							<div class="modal-header bg-danger text-white">
								<h5 class="modal-title" id="ModalLabel">Aggiungi Nuovo Cliente</h5>
								<button id="chiudi_modal_aggiungi" type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
							</div>
							<input type="hidden" name="azione" value="aggiungi_cliente">
							<input type="hidden" id="password_c" name="password_c">
							
							
							<div class="modal-body">
								<?php
								//echo "abilitati?". $abilita_test;
									if ($abilita_test == 0) echo "<button class='btn btn-primary' disabled><strong>⚠️⚠️I TEST SONO DISABILITATI DURANTE GLI EVENTI⚠️⚠️</strong></button>";
								?>
								<div class="form-group">
									<label for="username" class="col-form-label"><strong>Username:</strong></label>
									<input type="text" class="form-control" id="username_c" name="username_c">
								</div>
								<div class="form-group">
									<label for="password" class="col-form-label"><strong>Password:</strong></label>
									<input type="text" class="form-control" id="password_cx" name="password_cx" disabled>
								</div>
								<div class="form-group">
									<label for="exampleFormControlSelect2"><strong>Mesi di abbonamento</strong></label>
									<select class="form-control" id="mesi_abbonamento_c" name="mesi_abbonamento_c">
									<?php
										if ($abilita_test == 1) echo "<option value='b37cd7a'>[TEST] 1 ora</option>	";
									?>
									  							 
									  <option value="1">1 Mese [1 cr]</option>
									  <option value="3">3 Mesi [3 cr]</option>
									  <option value="6">6 Mesi [6 cr]</option>
									  <option value="12">12 Mesi [12 cr]</option>
									</select>
								</div>
								<div class="form-group">
									<label for="visioni" class="col-form-label"><strong>Visioni:</strong></label>
									<input type="text" class="form-control" id="visioni_c" name="visioni_c" value="2" disabled>
								</div>
								<div class="form-group">
									<label for="note"><strong>Note:</strong></label>
									<textarea class="form-control" id="note" name="note" rows="5"></textarea>
								</div>
							</div>
							<div class="modal-footer">
								<button type="submit" class="btn btn-success">CONFERMA</button>
								<button type="button" class="btn btn-light" data-dismiss="modal">Annulla</button>
							</div>
						</div>
					</form>
                </div>
            </div>
<!-------- FINE MODAL AGGIUNGI ------------->	
<!-------- INIZIO MODAL MODIFICA ------------->			
			<div class="modal fade" id="edita_cliente" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" style="display: none;" aria-hidden="true">
                <div class="modal-dialog" role="document">
					<form class="forms-sample " name="edita_cliente_f" id="edita_cliente_f">
						<div class="modal-content">
							<div class="modal-header bg-warning text-white">
								<h5 class="modal-title" id="ModalLabel">Modifica Cliente</h5>
								<button type="button" id="chiudi_modal_modifica" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
							</div>
							<input type="hidden" name="azione" value="edita_pass_note_cliente">
							<input type="hidden" id="id_cliente_c_e" name="id_cliente_c_e" value="">
							<input type="hidden" id="username_c_e" name="username_c_e" value="">
							<input type="hidden" id="old_password" name="old_password" value="">
							<div class="modal-body">
								<div class="form-group">
									<label for="username" class="col-form-label"><strong>Username:</strong></label>
									<input type="text" class="form-control" id="username_c2" name="username_c2" disabled>
								</div>
								<div class="form-group">
									<label for="password" class="col-form-label"><strong>Password:</strong></label>
									<input type="text" class="form-control" id="password_c_e" name="password_c_e">
								</div>
								<div class="form-group">
									<label for="visioni_c_e" class="col-form-label"><strong>Visioni:</strong></label>
									<input type="text" class="form-control" id="visioni_c_e" name="visioni_c_e" value="2" disabled>
								</div>
								<div class="form-group">
									<label for="note"><strong>Note:</strong></label>
									<textarea class="form-control" id="note_e" name="note_e" rows="5"></textarea>
								</div>
							</div>
							<div class="modal-footer">
								<button type="submit" class="btn btn-success">CONFERMA</button>
								<button type="button" class="btn btn-light" data-dismiss="modal">Annulla</button>
							</div>
						</div>
					</form>
                </div>
            </div>
<!-------- FINE MODAL MODIFICA ------------->	
<!-------- INIZIO MODAL ELIMINA ------------->			
			<div class="modal fade" id="elimina_cliente" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" style="display: none;" aria-hidden="true">
                <div class="modal-dialog" role="document">
					<form class="forms-sample " name="elimina_cliente_f" id="elimina_cliente_f">
						<div class="modal-content">
							<div class="modal-header bg-info text-white">
								<h5 class="modal-title" id="ModalLabel">Elimina Cliente</h5>
								<button type="button" id="chiudi_modal_elimina" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
							</div>
							<input type="hidden" name="azione" value="elimina_cliente">
							<input type="hidden" id="id_cliente_c_d" name="id_cliente_c_d">
							<input type="hidden" id="username_c_d" name="username_c_d">
							<div class="modal-body">
								<p style="text-align:justify">Sei sicuro di voler eliminare il cliente [<strong id="nome_cliente" name="nome_cliente"> </strong>]</p>
								<div class="modal-footer">
									<button type="submit" class="btn btn-success">CONFERMA</button>
									<button type="button" class="btn btn-light" data-dismiss="modal">Annulla</button>
								</div>
							</div>
					</form>
						</div>
				</div>
			</div>
<!-------- FINE MODAL ELIMINA ------------->	
<!-------- INIZIO MODAL ESTENDI ------------->			
			<div class="modal fade" id="estendi_linea" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" style="display: none;" aria-hidden="true">
                <div class="modal-dialog" role="document">
					<form class="forms-sample " name="estendi_linea_f" id="estendi_linea_f">
						<div class="modal-content">
							<div class="modal-header bg-primary text-white">
								<h5 class="modal-title" id="ModalLabel">Estendi Abbonamento Cliente</h5>
								<button type="button" id="chiudi_modal_estendi" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
							</div>
							<input type="hidden" name="azione" value="estendi_linea">
							<input type="hidden" id="id_cliente_c_e_l" name="id_cliente_c_e_l">
							<input type="hidden" id="username_c_e_l" name="username_c_e_l">
							<div class="modal-body">
								<div class="form-group">
									<label for="username" class="col-form-label"><strong>Username:</strong></label>
									<input type="text" class="form-control" id="username_c3" name="username_c3" disabled>
								</div>
								<div class="form-group">
									<label for="exampleFormControlSelect2"><strong>Mesi di abbonamento</strong></label>
									<select class="form-control" id="mesi_abbonamento_c_e" name="mesi_abbonamento_c_e">
									  <option value="1">1 Mese [2 cr]</option>
									  <option value="3">3 Mesi [3 cr]</option>
									  <option value="6">6 Mesi [6 cr]</option>
									  <option value="12">12 Mesi [12 cr]</option>
									</select>
								</div>
								<div class="modal-footer">
									<button type="submit" class="btn btn-success">CONFERMA</button>
									<button type="button" class="btn btn-light" data-dismiss="modal">Annulla</button>
								</div>
							</div>
					</form>
						</div>
				</div>
			</div>
<!-------- FINE MODAL ESTENDI ------------->
			<button type="button" onclick="generaPwd(8);$('#aggiungi_cliente_f').trigger('reset');" class="btn btn-danger btn-icon-text" data-toggle="modal" data-target="#aggiungi_cliente" data-whatever="aggiungi_cliente"><i class="mdi mdi-account-plus btn-icon-prepend"></i>Aggiungi Cliente</button><br><br>
			<div class="row">
				<div class="col-12">
					<div class="table-responsive">
						<table id="client_list" name="client_list" class="table table-bordered">
							<thead>
								<tr>
									<th style="width:5%">#</th>
									<th style="width:5%">Stato</th>
									<th style="width:15%">Creatore</th>
									<th style="width:15%">Username</th>
									<th style="width:15%">Password</th>
									<th style="width:5%">Visioni</th>
									<th style="width:10%">Scadenza</th>
									<th style="width:25%">Note</th>
									<th style="width:5%">Azioni</th>
								</tr>
							</thead>
							<tbody>
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<div class="jq-toast-wrap top-right">
	<div class="jq-toast-single jq-has-icon jq-icon-success" style="text-align: left; display: none;">
		<span class="jq-toast-loader jq-toast-loaded" style="-webkit-transition: width 2.6s ease-in;-o-transition: width 2.6s ease-in;transition: width 2.6s ease-in;background-color: #f96868;"></span>
		<span class="close-jq-toast-single">×</span>
		<h2 class="jq-toast-heading">Success</h2>
		And these were just the basic demos! Scroll down to check further details on how to customize the output.
	</div>
</div>
<script>
function generaPwd(length) {
   var result           = '';
   var characters       = 'abcdefghijklmnopqrstuvwxyz0123456789';
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   $('#password_c').attr('value',result);
   $('#password_cx').attr('value',result);
}

function edita_cliente(id, username, password, note) {
	$('#id_cliente_c_e').attr('value', id);
	$('#username_c2').attr('value', username);
	$('#username_c_e').attr('value', username);
	$('#password_c_e').attr('value', password);
	$('#old_password').attr('value', password);
	$('#note_e').val(note);
}
function estendilinea_cliente(id, username) {
	$('#id_cliente_c_e_l').attr('value', id);
	$('#username_c3').attr('value', username);
	$('#username_c_e_l').attr('value', username);
}
function elimina_cliente(id, username) {
	$('#id_cliente_c_d').attr('value', id);
	$('#username_c_d').attr('value', username);
	$('#nome_cliente').html(username);
}

$( document ).ready(function() {	
	
	var client_list =  $('#client_list').DataTable({
			"order":  [ 0, "desc" ] ,
			"lengthMenu": [[15, 30, 50, 100 ], [15, 30, 50,100 ]],
			"pageLength": 15,
			"responsive": true,
			"autoWidth": false,
			"language": {
					"sEmptyTable":     "Nessun dato presente nella tabella",
					"sInfo":           "Vista da _START_ a _END_ di _TOTAL_ elementi",
					"sInfoEmpty":      "Vista da 0 a 0 di 0 elementi",
					"sInfoFiltered":   "(filtrati da _MAX_ elementi totali)",
					"sInfoPostFix":    "",
					"sInfoThousands":  ".",
					"sLengthMenu":     "Visualizza _MENU_ elementi",
					"sLoadingRecords": "Caricamento...",
					"sProcessing":     "Elaborazione...",
					"sSearch":         "Cerca:",
					"sZeroRecords":    "La ricerca non ha portato alcun risultato.",
					"oPaginate": {
						"sFirst":      "Inizio",
						"sPrevious":   "Precedente",
						"sNext":       "Successivo",
						"sLast":       "Fine"
					}, 
					"oAria": {
						"sSortAscending":  ": attiva per ordinare la colonna in ordine crescente",
						"sSortDescending": ": attiva per ordinare la colonna in ordine decrescente"
					}
			},

			"ajax": "lista_clienti_json.php",
			"dataSrc": "data",
			"columns": [
					{ data: 0},
					{ data: 1,
						"render": function (data, type, row) {
							if ( row[1] == '0') {
								return "<label class='badge badge-outline-warning' title='SCADUTO'>Scaduto</label>";
							}  
							if ( row[1] == '1') {
								return "<label class='badge badge-outline-success' title='ATTIVO'>Attivo</label>";
							}	
							if ( row[1] == '2') {
								return "<label class='badge badge-outline-danger' title='BLOCCATO'>Bloccato</label>";
							}					
							return row[1];
						}
					},
					{ data: 2,
						"render": function (data, type, row) {
							if ( row[2] == '0') {
								return "<label class='badge badge-danger' title='offline'>offline</label>";
							}  
							if ( row[2] == '1') {
								return "<label class='badge badge-success' title='online'>online</label>";
							}					
							return row[2];
						}				
					},
				{ data: 3},
				{ data: 4},
				{ data: 5,
					"className": "text-center",
				},
				{ data: 6},
				{ data: 7},
				{ data: 8},
			]
	});
	
	$( "#aggiungi_cliente_f" ).submit(function( e ) {  
    // Ottieni i valori iniziali
    var crediti_s = $('#mesi_abbonamento_c').val();
    if ((crediti_s == "test1h") || (crediti_s == "test12h")) {
        crediti_s = 0;
    }
    crediti_s = parseInt(crediti_s, 10) || 0; // Assicurati che sia un numero

    var crediti_i = parseInt($('#crediti_top').html(), 10) || 0; // Converte in numero
    console.log("Valore iniziale - crediti_s:", crediti_s, "crediti_i:", crediti_i);

    e.preventDefault(); // Previeni il comportamento predefinito del form

    $.ajax({
        url: "operazioni_aj.php",
        type: "POST",
        data: $("#aggiungi_cliente_f").serialize(),
        success: function(data) {
            console.log("Risultato dal server:", data);
            if (data == "OK") {  
                // Chiudi la modale e ricarica i dati
                $("#chiudi_modal_aggiungi").click();
                $("#client_list").dataTable().fnClearTable(); 
                client_list.ajax.reload();
                NotificaSuccesso("Successo", "Cliente aggiunto correttamente");

                // Aggiorna i crediti
                if (crediti_i !== "∞") {
                    var crediti_n = crediti_i - crediti_s;
                    console.log("Nuovo valore calcolato per crediti:", crediti_n);
                    $('#crediti_top').html(crediti_n);

                    // Controlla il valore aggiornato nel DOM
                    var valore_aggiornato = parseInt($('#crediti_top').html(), 10) || 0;
                    console.log("Valore DOM dopo aggiornamento:", valore_aggiornato);
                }
            } else {
                NotificaErrore("Attenzione Errori", data);					
            }				
        },
        error: function(data) {
            console.error("Errore nella chiamata AJAX per aggiungere cliente.");
            NotificaScriptNonDisponibile();
        }
    });
});


	
	$( "#elimina_cliente_f" ).submit(function( e ) {  
		e.preventDefault();
		$.ajax({
			url: "operazioni_aj.php",
			type: "POST",
			data: $("#elimina_cliente_f").serialize(),
			success: function(data) {
				if (data =="OK") { 
					$("#chiudi_modal_elimina").click()
					$("#client_list").dataTable().fnClearTable(); 
					client_list.ajax.reload()
					NotificaSuccesso("Successo", "Cliente eliminato correttamente");
					
				} else {
					NotificaErrore("Attenzione Errori", data);
				}				
			},
			error: function(data) {
				NotificaScriptNonDisponibile();
			}
		});
	});
	
	$( "#edita_cliente_f" ).submit(function( e ) {  
		e.preventDefault();
		$.ajax({
			url: "operazioni_aj.php",
			type: "POST",
			data: $("#edita_cliente_f").serialize(),
			success: function(data) {
				if (data =="OK") { 
					$("#chiudi_modal_modifica").click()
					NotificaSuccesso("Successo", "Cliente modificato correttamente");
					$("#client_list").dataTable().fnClearTable(); 
					client_list.ajax.reload()
				} else {
					NotificaErrore("Attenzione Errori", data);
				}				
			},
			error: function(data) {
				NotificaScriptNonDisponibile();
			}
		});
	});
	$( "#estendi_linea_f" ).submit(function( e ) {  
    // Ottieni i valori iniziali
    var crediti_s = $('#mesi_abbonamento_c_e').val();
    crediti_s = parseInt(crediti_s, 10) || 0; // Assicurati che sia un numero

    var crediti_i = parseInt($('#crediti_top').html(), 10) || 0; // Converte in numero
    console.log("Valore iniziale - crediti_s:", crediti_s, "crediti_i:", crediti_i);

    e.preventDefault(); // Previeni il comportamento predefinito del form

    $.ajax({
        url: "operazioni_aj.php",
        type: "POST",
        data: $("#estendi_linea_f").serialize(),
        success: function(data) {
            console.log("Risultato dal server:", data);
            if (data == "OK") { 
                // Chiudi la modale
                $("#chiudi_modal_estendi").click();
                NotificaSuccesso("Successo", "Abbonamento esteso correttamente");

                // Ricarica la tabella dei clienti
                $("#client_list").dataTable().fnClearTable(); 
                client_list.ajax.reload();

                // Aggiorna i crediti
                if (crediti_i !== "∞") {
                    var crediti_n = crediti_i - crediti_s;
                    console.log("Nuovo valore calcolato per crediti:", crediti_n);
                    $('#crediti_top').html(crediti_n);

                    // Controlla il valore aggiornato nel DOM
                    var valore_aggiornato = parseInt($('#crediti_top').html(), 10) || 0;
                    console.log("Valore DOM dopo aggiornamento:", valore_aggiornato);
                }
            } else {
                NotificaErrore("Attenzione Errori", data);
            }				
        },
        error: function(data) {
            console.error("Errore nella chiamata AJAX per estendere linea.");
            NotificaScriptNonDisponibile();
        }
    });
});


	
});

</script>
 
  <script src="vendors/jquery-toast-plugin/jquery.toast.min.js"></script>
  <script src="js/notifiche.js"></script>
  <script src="vendors/datatables.net/jquery.dataTables.js"></script>
  <script src="vendors/datatables.net-bs4/dataTables.bootstrap4.js"></script>
<script src="vendors/progressbar.js/progressbar.min.js"></script>
<script src="js/progress-bar.js"></script>
<?php

require_once("footer.php");
?>