<?php
$message = '';
$editClient = null;

if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    try {
        $pdo->prepare("DELETE FROM " . DB_PREFIX . "clients WHERE id = ?")->execute([$_GET['delete']]);
        $message = ['type' => 'success', 'text' => 'Клиент удален'];
    } catch (Exception $e) {
        $message = ['type' => 'error', 'text' => 'Ошибка удаления'];
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['client_id'] ?? null;
    $data = [
        'name' => trim($_POST['name'] ?? ''),
        'contact_name' => trim($_POST['contact_name'] ?? ''),
        'email' => trim($_POST['email'] ?? ''),
        'phone' => trim($_POST['phone'] ?? ''),
        'telegram' => trim($_POST['telegram'] ?? ''),
        'website' => trim($_POST['website'] ?? ''),
        'description' => trim($_POST['description'] ?? ''),
        'status' => $_POST['status'] ?? 'active'
    ];

    if (empty($data['name'])) {
        $message = ['type' => 'error', 'text' => 'Укажите название клиента'];
    } else {
        try {
            if ($id) {
                $fields = []; $values = [];
                foreach ($data as $k => $v) { $fields[] = "$k = ?"; $values[] = $v; }
                $values[] = $id;
                $pdo->prepare("UPDATE " . DB_PREFIX . "clients SET " . implode(', ', $fields) . " WHERE id = ?")->execute($values);
                $message = ['type' => 'success', 'text' => 'Клиент обновлен'];
            } else {
                $pdo->prepare("INSERT INTO " . DB_PREFIX . "clients (name, contact_name, email, phone, telegram, website, description, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
                    ->execute(array_values($data));
                $message = ['type' => 'success', 'text' => 'Клиент добавлен'];
            }
        } catch (Exception $e) {
            $message = ['type' => 'error', 'text' => 'Ошибка: ' . $e->getMessage()];
        }
    }
}

if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM " . DB_PREFIX . "clients WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editClient = $stmt->fetch();
}

$search = $_GET['search'] ?? '';
if ($search) {
    $stmt = $pdo->prepare("SELECT * FROM " . DB_PREFIX . "clients WHERE name LIKE ? OR contact_name LIKE ? OR email LIKE ? ORDER BY created_at DESC");
    $stmt->execute(["%$search%", "%$search%", "%$search%"]);
} else {
    $stmt = $pdo->query("SELECT * FROM " . DB_PREFIX . "clients ORDER BY created_at DESC");
}
$clients = $stmt->fetchAll();
?>

<?php if ($message): ?>
<div class="alert alert-<?php echo $message['type']; ?>"><?php echo $message['text']; ?></div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <div class="search-box">
            <i class="fas fa-search"></i>
            <input type="text" placeholder="Поиск клиентов..." value="<?php echo sanitize($search); ?>" onkeyup="if(event.key==='Enter') location.href='?page=clients&search='+this.value">
        </div>
        <button class="btn btn-primary" onclick="openModal('clientModal')"><i class="fas fa-plus"></i> Добавить клиента</button>
    </div>
    <table class="data-table">
        <thead><tr><th>Название</th><th>Контакт</th><th>Email</th><th>Телефон</th><th>Статус</th><th>Действия</th></tr></thead>
        <tbody>
            <?php foreach ($clients as $client): ?>
            <tr>
                <td>
                    <div style="font-weight: 500;"><?php echo sanitize($client['name']); ?></div>
                    <?php if ($client['website']): ?><a href="<?php echo sanitize($client['website']); ?>" target="_blank" style="font-size: 12px; color: var(--primary);"><i class="fas fa-external-link-alt"></i> Сайт</a><?php endif; ?>
                </td>
                <td><?php echo sanitize($client['contact_name'] ?: '—'); ?></td>
                <td><?php echo sanitize($client['email'] ?: '—'); ?></td>
                <td><?php echo sanitize($client['phone'] ?: '—'); ?></td>
                <td><span class="badge-status <?php echo $client['status']; ?>"><?php echo $client['status'] === 'active' ? 'Активен' : 'Неактивен'; ?></span></td>
                <td>
                    <a href="?page=clients&edit=<?php echo $client['id']; ?>" class="btn btn-sm btn-secondary" style="margin-right: 5px;"><i class="fas fa-edit"></i></a>
                    <a href="?page=clients&delete=<?php echo $client['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Удалить клиента?')"><i class="fas fa-trash"></i></a>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($clients)): ?><tr><td colspan="6" style="text-align: center; color: var(--gray); padding: 40px;">Клиентов не найдено</td></tr><?php endif; ?>
        </tbody>
    </table>
</div>

<div class="modal-overlay" id="clientModal">
    <div class="modal">
        <div class="modal-header">
            <div class="modal-title"><?php echo $editClient ? 'Редактировать клиента' : 'Новый клиент'; ?></div>
            <button class="modal-close" onclick="closeModal('clientModal')">&times;</button>
        </div>
        <form method="POST">
            <div class="modal-body">
                <input type="hidden" name="client_id" value="<?php echo $editClient['id'] ?? ''; ?>">
                <div class="form-row">
                    <div class="form-group"><label>Название компании *</label><input type="text" name="name" value="<?php echo sanitize($editClient['name'] ?? ''); ?>" required></div>
                    <div class="form-group"><label>Контактное лицо</label><input type="text" name="contact_name" value="<?php echo sanitize($editClient['contact_name'] ?? ''); ?>"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>Email</label><input type="email" name="email" value="<?php echo sanitize($editClient['email'] ?? ''); ?>"></div>
                    <div class="form-group"><label>Телефон</label><input type="text" name="phone" value="<?php echo sanitize($editClient['phone'] ?? ''); ?>"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>Telegram</label><input type="text" name="telegram" value="<?php echo sanitize($editClient['telegram'] ?? ''); ?>"></div>
                    <div class="form-group"><label>Сайт</label><input type="url" name="website" value="<?php echo sanitize($editClient['website'] ?? ''); ?>"></div>
                </div>
                <div class="form-group"><label>Описание</label><textarea name="description" rows="3"><?php echo sanitize($editClient['description'] ?? ''); ?></textarea></div>
                <div class="form-group">
                    <label>Статус</label>
                    <select name="status">
                        <option value="active" <?php echo ($editClient['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Активен</option>
                        <option value="inactive" <?php echo ($editClient['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Неактивен</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('clientModal')">Отмена</button>
                <button type="submit" class="btn btn-primary"><?php echo $editClient ? 'Сохранить' : 'Добавить'; ?></button>
            </div>
        </form>
    </div>
</div>

<?php if ($editClient): ?><script>openModal('clientModal');</script><?php endif; ?>
