cambios importantes
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
class CompanyRepository
|
||||
{
|
||||
public static function findByPhoneNumberId(string $phoneNumberId): ?array
|
||||
{
|
||||
$stmt = db()->prepare("SELECT * FROM companies WHERE phone_number_id = ? AND is_active = 1 LIMIT 1");
|
||||
$stmt->execute([$phoneNumberId]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
public static function findById(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare("SELECT * FROM companies WHERE id = ? LIMIT 1");
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
public static function findByApiKey(string $apiKey): ?array
|
||||
{
|
||||
$stmt = db()->prepare("SELECT * FROM companies WHERE api_key = ? AND is_active = 1 LIMIT 1");
|
||||
$stmt->execute([$apiKey]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
public static function findAll(bool $includeInactive = false): array
|
||||
{
|
||||
$where = $includeInactive ? '1=1' : 'is_active = 1';
|
||||
return db()->query("SELECT * FROM companies WHERE {$where} ORDER BY name")->fetchAll();
|
||||
}
|
||||
|
||||
public static function save(array $data): int
|
||||
{
|
||||
$db = db();
|
||||
$id = (int)($data['id'] ?? 0);
|
||||
|
||||
$fields = ['name', 'display_name', 'phone_number_id', 'display_phone', 'api_base_url', 'api_key', 'bot_type', 'requires_approval', 'is_active', 'config_json'];
|
||||
$params = [];
|
||||
$sets = [];
|
||||
foreach ($fields as $f) {
|
||||
if (array_key_exists($f, $data)) {
|
||||
$sets[] = "{$f} = ?";
|
||||
$params[] = is_array($data[$f]) || is_object($data[$f]) ? json_encode($data[$f]) : $data[$f];
|
||||
}
|
||||
}
|
||||
|
||||
if ($id > 0) {
|
||||
$params[] = $id;
|
||||
$stmt = $db->prepare("UPDATE companies SET " . implode(', ', $sets) . " WHERE id = ?");
|
||||
$stmt->execute($params);
|
||||
return $id;
|
||||
} else {
|
||||
// Ensure required fields
|
||||
$required = ['name', 'phone_number_id', 'api_base_url'];
|
||||
$insertData = [];
|
||||
foreach ($required as $r) {
|
||||
$insertData[$r] = $data[$r] ?? '';
|
||||
}
|
||||
foreach ($fields as $f) {
|
||||
if (array_key_exists($f, $data)) {
|
||||
$insertData[$f] = $data[$f];
|
||||
}
|
||||
}
|
||||
$cols = implode(', ', array_keys($insertData));
|
||||
$vals = implode(', ', array_fill(0, count($insertData), '?'));
|
||||
$stmt = $db->prepare("INSERT INTO companies ({$cols}) VALUES ({$vals})");
|
||||
$stmt->execute(array_values($insertData));
|
||||
return (int)$db->lastInsertId();
|
||||
}
|
||||
}
|
||||
|
||||
public static function delete(int $id): bool
|
||||
{
|
||||
$stmt = db()->prepare("DELETE FROM companies WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
return $stmt->rowCount() > 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user