| Server IP : 80.211.21.168 / Your IP : 216.73.217.33 Web Server : Apache System : Linux alex-webdesign.it 3.10.0-1160.119.1.el7.tuxcare.els22.x86_64 #1 SMP Mon Aug 18 06:07:12 UTC 2025 x86_64 User : admin_japan ( 10003) PHP Version : 8.2.32 Disable Function : opcache_get_status MySQL : OFF | cURL : ON | WGET : OFF | Perl : OFF | Python : OFF | Sudo : OFF | Pkexec : OFF Directory : /var/www/vhosts/cerchijapan.it/ai4dealers.com/MRC2/ |
Upload File : |
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
// --- Connessione al database ---
$mysqli = new mysqli('localhost', 'admin_valucrm', 'RCMvalus1994!', 'admin_valucrm');
if ($mysqli->connect_error) {
die("Connessione al database fallita: " . $mysqli->connect_error);
}
/**
* Normalizza una stringa per i confronti unici.
*/
function normalize_string(string $s): string {
$s = mb_convert_encoding($s, 'UTF-8', mb_detect_encoding($s));
$s = mb_strtolower($s, 'UTF-8');
$s = iconv('UTF-8', 'ASCII//TRANSLIT', $s);
$s = str_replace(["'", "’"], ' ', $s);
$s = preg_replace('/\s+/', ' ', $s);
return trim($s);
}
/**
* Carica un CSV pipe-delimited (salta header) e restituisce array di [raw, addr].
*/
function load_csv_data(string $file): array {
$out = [];
if (!file_exists($file)) return $out;
if (($h = fopen($file, 'r')) !== false) {
// salta header
fgetcsv($h, 0, '|');
while ($r = fgetcsv($h, 0, '|')) {
if (count($r) >= 2) {
$out[] = [
'raw' => trim($r[0]),
'addr' => trim($r[1])
];
}
}
fclose($h);
}
return $out;
}
// --- 1) Carico CSV ---
$csv_entries = load_csv_data('csvconce.csv');
// --- 2) Carico la lista dei nomi normalizzati già in DB ---
$db_norm_names = [];
$sql = "SELECT DISTINCT company_name FROM clients";
if ($res = $mysqli->query($sql)) {
while ($row = $res->fetch_assoc()) {
$db_norm_names[] = $row['company_name']; // in DB salvi già il nome normalizzato
}
$res->free();
} else {
die("Errore query clients: " . $mysqli->error);
}
// --- 3) Costruisco lista di voci valide (solo quelle NON in DB) ---
$valid_entries = [];
foreach ($csv_entries as $e) {
$norm = normalize_string($e['raw']);
if (!in_array($norm, $db_norm_names, true)) {
$valid_entries[] = [
'raw' => $e['raw'],
'addr' => $e['addr']
];
}
}
// --- 4) Estraggo l’elenco unico dei nomi e costruisco mappa raw => [indirizzi…] ---
$name_list = [];
$address_map = [];
foreach ($valid_entries as $e) {
$name_list[] = $e['raw'];
$address_map[$e['raw']][] = $e['addr'];
}
$name_list = array_values(array_unique($name_list));
foreach ($address_map as $raw => $addrs) {
$address_map[$raw] = array_values(array_unique($addrs));
}
// JSON per JS
$name_list_json = json_encode($name_list, JSON_UNESCAPED_UNICODE);
$address_map_json = json_encode($address_map, JSON_UNESCAPED_UNICODE);
// --- 5) Gestione del POST ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// input raw
$raw_name = trim($_POST['company_name'] ?? '');
$addr_input = trim($_POST['address'] ?? '');
$phone = trim($_POST['phone_number'] ?? '');
$email = trim($_POST['email_contacted'] ?? '');
$status = trim($_POST['status'] ?? '');
$notes = trim($_POST['notes'] ?? '');
$user_id = $_SESSION['user_id'];
// normalizzo il nome
$norm_name = normalize_string($raw_name);
// 5.1 Validazione base: nome e indirizzo devono essere tra quelli caricati
if (
!in_array($raw_name, $name_list, true)
|| !isset($address_map[$raw_name])
|| !in_array($addr_input, $address_map[$raw_name], true)
) {
echo "<div class='alert alert-danger'>Errore: nome o indirizzo non validi.</div>";
} else {
// 5.2 Controllo lato server: azienda già esistente?
$stmt = $mysqli->prepare("SELECT 1 FROM clients WHERE company_name = ?");
if (!$stmt) {
die("<div class='alert alert-danger'>Errore prepare: " . htmlspecialchars($mysqli->error) . "</div>");
}
$stmt->bind_param('s', $norm_name);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
echo "<div class='alert alert-danger'>Errore: azienda già prenotata in precedenza.</div>";
$stmt->close();
} else {
$stmt->close();
// --- Raccolta dei piani ---
$plans = [];
if (!empty($_POST['plan_buyer_check'])) {
$plans[] = "Buyer - " . $mysqli->real_escape_string($_POST['plan_buyer']);
}
if (!empty($_POST['plan_seller_check'])) {
$plans[] = "Seller - " . $mysqli->real_escape_string($_POST['plan_seller']);
}
if (!empty($_POST['plan_remarketing_check'])) {
$plans[] = "Remarketing - " . $mysqli->real_escape_string($_POST['plan_remarketing']);
}
// Piani custom
$custom = [];
foreach ($_POST as $k => $v) {
if (preg_match('/^custom_plan_name_(\d+)$/', $k, $m)) {
$i = $m[1];
if (!empty($_POST["custom_plan_price_{$i}"])) {
$n = $mysqli->real_escape_string($v);
$p = $mysqli->real_escape_string($_POST["custom_plan_price_{$i}"]);
$custom[] = "{$n} - {$p}";
}
}
}
$plan_str = implode(', ', $plans);
if ($custom) {
$plan_str .= ($plan_str ? ', ' : '') . 'Custom Plans: ' . implode(', ', $custom);
}
// --- 5.3 Inserimento in DB con created_at e last_modified ---
$now = date('Y-m-d H:i:s');
$ins = $mysqli->prepare(
"INSERT INTO clients
(company_name, phone_number, address, email_contacted, status, notes, plan, user_id, created_at, last_modified)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
if (!$ins) {
die("<div class='alert alert-danger'>Errore prepare inserimento: " . htmlspecialchars($mysqli->error) . "</div>");
}
$ins->bind_param(
'sssssssiss',
$norm_name, // company_name (normalizzato)
$phone, // phone_number
$addr_input, // address
$email, // email_contacted
$status, // status
$notes, // notes
$plan_str, // plan
$user_id, // user_id (int)
$now, // created_at
$now // last_modified
);
if ($ins->execute()) {
echo "<div class='alert alert-success'>Cliente aggiunto con successo.</div>";
// Ricarico la pagina per aggiornare dati/autocomplete
header("Refresh:1");
} else {
echo "<div class='alert alert-danger'>Errore inserimento: "
. htmlspecialchars($ins->error) . "</div>";
}
$ins->close();
}
}
}
?>
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<title>ValuCRM - Aggiungi Cliente</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="assets/css/futuristic-theme.css">
<style>
.page-header {
padding: 2rem 0;
margin-bottom: 2rem;
text-align: center;
}
.form-card {
background: var(--gradient-card);
border: 2px solid var(--color-border-secondary);
border-radius: var(--radius-xl);
padding: 2rem;
margin-bottom: 2rem;
box-shadow: var(--shadow-lg);
}
.form-section-title {
font-family: var(--font-heading);
font-size: 1.25rem;
color: var(--color-text-primary);
margin-bottom: 1.5rem;
padding-bottom: 0.5rem;
border-bottom: 2px solid var(--color-border-primary);
}
.ui-autocomplete {
background: var(--color-bg-card);
border: 2px solid var(--color-border-primary);
border-radius: var(--radius-md);
box-shadow: var(--shadow-xl);
max-height: 300px;
overflow-y: auto;
}
.ui-menu-item {
padding: 0.5rem 1rem;
color: var(--color-text-secondary);
cursor: pointer;
transition: all var(--transition-fast);
}
.ui-menu-item:hover,
.ui-state-active {
background: var(--color-bg-hover) !important;
color: var(--color-primary) !important;
border: none !important;
}
</style>
</head>
<body>
<div class="container mt-4">
<div class="page-header">
<h1>➕ Aggiungi Nuovo Cliente</h1>
<p style="color: var(--color-text-secondary);">Compila il form per aggiungere un cliente al sistema</p>
</div>
<div class="mb-4">
<a href="index.php" class="btn btn-secondary">← Torna alla Home</a>
<a href="dashboard.php" class="btn btn-primary">📊 Dashboard</a>
</div>
<div class="form-card">
<form method="post">
<div class="form-section-title">📋 Informazioni Azienda</div>
<div class="form-group">
<label for="company_name">Nome azienda</label>
<input type="text" id="company_name" name="company_name"
class="form-control" placeholder="Inizia a digitare..." required>
</div>
<div class="form-group">
<label for="address">Indirizzo</label>
<input type="text" id="address" name="address"
class="form-control" placeholder="Seleziona prima il nome" required>
</div>
<div class="form-group">
<label for="phone_number">Telefono</label>
<input type="text" id="phone_number" name="phone_number"
class="form-control" required>
</div>
<div class="form-group">
<label for="email_contacted">Email contattata</label>
<input type="email" id="email_contacted" name="email_contacted"
class="form-control" required>
</div>
<div class="form-group">
<label for="status">Status</label>
<select id="status" name="status" class="form-control" required>
<option>In trattativa</option>
<option>Inviato mail</option>
<option>Chiamato</option>
<option>Demo in corso</option>
<option>Cliente attivo</option>
</select>
</div>
<div class="form-section-title mt-4">💼 Piani e Servizi</div>
<div class="form-group">
<label class="form-label">Piani Standard</label>
<div class="form-check mb-3">
<input type="checkbox" id="plan_buyer_check" name="plan_buyer_check" class="form-check-input">
<label class="form-check-label" for="plan_buyer_check">🛒 Buyer</label>
<select id="plan_buyer" name="plan_buyer" class="form-control mt-2" disabled>
<option>Basic</option>
<option>Medium</option>
<option>UNLIMITED</option>
</select>
</div>
<div class="form-check mb-3">
<input type="checkbox" id="plan_seller_check" name="plan_seller_check" class="form-check-input">
<label class="form-check-label" for="plan_seller_check">💰 Seller</label>
<select id="plan_seller" name="plan_seller" class="form-control mt-2" disabled>
<option>Basic</option>
<option>Medium</option>
<option>UNLIMITED</option>
</select>
</div>
<div class="form-check mb-3">
<input type="checkbox" id="plan_remarketing_check" name="plan_remarketing_check" class="form-check-input">
<label class="form-check-label" for="plan_remarketing_check">📢 Remarketing</label>
<select id="plan_remarketing" name="plan_remarketing" class="form-control mt-2" disabled>
<option>Basic</option>
<option>Medium</option>
<option>UNLIMITED</option>
</select>
</div>
</div>
<div class="form-group">
<label class="form-label">Piani Personalizzati</label>
<div id="custom_plans_container">
<div class="custom-plan-row mb-2">
<input type="text" name="custom_plan_name_1" class="form-control mb-2" placeholder="Nome piano">
<input type="text" name="custom_plan_price_1" class="form-control mb-2" placeholder="Prezzo">
</div>
</div>
<button type="button" id="add_custom_plan" class="btn btn-secondary btn-sm">+ Aggiungi Piano</button>
</div>
<div class="form-group">
<label for="notes">Note</label>
<textarea id="notes" name="notes" class="form-control"></textarea>
</div>
<div class="form-section-title mt-4">📝 Note Aggiuntive</div>
<div class="form-group">
<label for="notes">Note</label>
<textarea id="notes" name="notes" class="form-control" rows="4"></textarea>
</div>
<div class="text-center mt-4">
<button type="submit" class="btn btn-primary btn-lg">
✅ Aggiungi Cliente al Sistema
</button>
</div>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script>
// dati per autocomplete
var nameItems = <?php echo $name_list_json; ?>;
var addressMap = <?php echo $address_map_json; ?>;
$(function(){
// autocomplete nome azienda
$("#company_name").autocomplete({
source: nameItems,
minLength: 2,
select: function(e, ui){
var name = ui.item.value;
var addrs = addressMap[name] || [];
$("#address").val('');
$("#address").autocomplete('option', 'source', addrs);
if (addrs.length === 1) {
$("#address").val(addrs[0]);
}
}
});
// autocomplete indirizzo (vuoto finché non scelgo nome)
$("#address").autocomplete({
source: [],
minLength: 0
}).focus(function(){
$(this).autocomplete("search", "");
});
// toggle piani standard
$('#plan_buyer_check').change(function(){
$('#plan_buyer').prop('disabled', !this.checked);
});
$('#plan_seller_check').change(function(){
$('#plan_seller').prop('disabled', !this.checked);
});
$('#plan_remarketing_check').change(function(){
$('#plan_remarketing').prop('disabled', !this.checked);
});
// aggiunta piani custom
var idx = 1;
$('#add_custom_plan').click(function(){
idx++;
$('#custom_plans_container').append(
'<div class="custom-plan-row">'+
'<input type="text" name="custom_plan_name_'+idx+'" class="form-control mb-2" placeholder="Nome piano">'+
'<input type="text" name="custom_plan_price_'+idx+'" class="form-control mb-2" placeholder="Prezzo">'+
'</div>'
);
});
});
</script>
</body>
</html>