prepare(" SELECT smtp_id FROM company_smtp WHERE company_id = :company_id LIMIT 1 "); $sth->execute([':company_id' => $company_id]); db_check($sth, $answer); $existing_id = $sth->fetchColumn(); if ($existing_id) { if ($raw_pass !== '') { $sth = $pdo1->prepare(" UPDATE company_smtp SET server = :server, port = :port, username = :username, password = :password, from_name = :from_name, from_email = :from_email, encryption = :encryption, updated_at = NOW() WHERE smtp_id = :smtp_id "); $sth->execute([ ':server' => $server, ':port' => $port, ':username' => $username, ':password' => encrypt_password($raw_pass), ':from_name' => $from_name, ':from_email' => $from_email, ':encryption' => $encryption, ':smtp_id' => $existing_id, ]); } else { // Keep existing password — don't touch it $sth = $pdo1->prepare(" UPDATE company_smtp SET server = :server, port = :port, username = :username, from_name = :from_name, from_email = :from_email, encryption = :encryption, updated_at = NOW() WHERE smtp_id = :smtp_id "); $sth->execute([ ':server' => $server, ':port' => $port, ':username' => $username, ':from_name' => $from_name, ':from_email' => $from_email, ':encryption' => $encryption, ':smtp_id' => $existing_id, ]); } } else { // New record — password required if ($raw_pass === '') { $answer['message'] = 'Password is required for a new SMTP configuration.'; http_response_code(422); exit(json_encode($answer)); } $sth = $pdo1->prepare(" INSERT INTO company_smtp (company_id, server, port, username, password, from_name, from_email, encryption, updated_at) VALUES (:company_id, :server, :port, :username, :password, :from_name, :from_email, :encryption, NOW()) "); $sth->execute([ ':company_id' => $company_id, ':server' => $server, ':port' => $port, ':username' => $username, ':password' => encrypt_password($raw_pass), ':from_name' => $from_name, ':from_email' => $from_email, ':encryption' => $encryption, ]); } db_check($sth, $answer); $answer['success'] = 1; $answer['message'] = 'SMTP settings saved.'; } catch (Exception $e) { $answer['message'] = 'Failed to save SMTP settings.'; http_response_code(500); } exit(json_encode($answer)); ?>