<?php
require_once __DIR__ . '/../../inc/auth.php';
require_once __DIR__ . '/../../inc/functions.php';
$session = auth_require('owner', 'engineer');

$pdo = getDB();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id          = (int)($_POST['id'] ?? 0);
    $name        = trim($_POST['name'] ?? '');
    $inn         = trim($_POST['inn'] ?? '');
    $kpp         = trim($_POST['kpp'] ?? '');
    $address     = trim($_POST['legal_address'] ?? '');
    $contact     = trim($_POST['contact_person'] ?? '');
    $cphone      = trim($_POST['contact_phone'] ?? '');
    $cemail      = trim($_POST['contact_email'] ?? '');
    $status      = $_POST['status'] ?? 'active';
    $notes       = trim($_POST['notes'] ?? '');
    $csrf        = $_POST['csrf_token'] ?? '';

    if (!auth_csrf_verify($csrf)) {
        $message = 'Ошибка безопасности.';
    } elseif ($name === '') {
        $message = 'Название клиента обязательно.';
    } else {
        try {
            if ($id > 0) {
                $stmt = $pdo->prepare("UPDATE customers SET name=?, inn=?, kpp=?, legal_address=?, contact_person=?, contact_phone=?, contact_email=?, status=?, notes=? WHERE id=?");
                $stmt->execute([$name, $inn, $kpp, $address, $contact, $cphone, $cemail, $status, $notes, $id]);
                $message = 'Клиент обновлён.';
            } else {
                $stmt = $pdo->prepare("INSERT INTO customers (name, inn, kpp, legal_address, contact_person, contact_phone, contact_email, status, notes, created_by) VALUES (?,?,?,?,?,?,?,?,?,?)");
                $stmt->execute([$name, $inn, $kpp, $address, $contact, $cphone, $cemail, $status, $notes, $session['user_id']]);
                $message = 'Клиент создан.';
            }
            auth_log($session['user_id'], $id > 0 ? 'customer_update' : 'customer_create', "Name: $name");
        } catch (\PDOException $e) {
            $message = 'Ошибка: ' . $e->getMessage();
        }
    }
}

if (isset($_GET['delete']) && auth_has_role('owner')) {
    $id = (int)$_GET['delete'];
    if (auth_csrf_verify($_GET['csrf'] ?? '')) {
        $pdo->prepare("DELETE FROM customers WHERE id=?")->execute([$id]);
        $message = 'Клиент удалён.';
        auth_log($session['user_id'], 'customer_delete', "ID: $id");
    }
}

$editCust = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id=?");
    $stmt->execute([(int)$_GET['edit']]);
    $editCust = $stmt->fetch();
}

$search = trim($_GET['search'] ?? '');
if ($search !== '') {
    $stmt = $pdo->prepare("
        SELECT c.*,
               (SELECT COUNT(*) FROM objects WHERE customer_id=c.id) as objects_count,
               (SELECT COUNT(*) FROM sla_contracts WHERE customer_id=c.id AND status='active') as active_contracts
        FROM customers c
        WHERE c.name LIKE ? OR c.inn LIKE ? OR c.contact_person LIKE ?
        ORDER BY c.name
    ");
    $stmt->execute(["%$search%", "%$search%", "%$search%"]);
} else {
    $stmt = $pdo->query("
        SELECT c.*,
               (SELECT COUNT(*) FROM objects WHERE customer_id=c.id) as objects_count,
               (SELECT COUNT(*) FROM sla_contracts WHERE customer_id=c.id AND status='active') as active_contracts
        FROM customers c
        ORDER BY c.name
    ");
}
$customers = $stmt->fetchAll();

$csrf = auth_csrf_token();
require __DIR__ . '/../../inc/header.php';
?>

<div class="main-header">
    <div>
        <h1>Клиенты</h1>
        <div class="breadcrumb"><a href="/service/dashboard.php">Главная</a> / Клиенты</div>
    </div>
    <button class="btn btn-primary btn-sm" onclick="openModal()" data-tooltip="Добавить клиента">+ Добавить</button>
</div>

<?php if ($message): ?>
<div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<form class="search-box" method="get">
    <input type="text" name="search" placeholder="Поиск клиентов..." value="<?= htmlspecialchars($search) ?>">
    <button type="submit" class="btn btn-primary btn-sm" data-tooltip="Поиск">Найти</button>
    <?php if ($search): ?><a href="customers.php" class="btn btn-secondary btn-sm" data-tooltip="Сбросить поиск">Сброс</a><?php endif; ?>
</form>

<div class="card">
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Название</th>
                    <th>ИНН</th>
                    <th>Контакт</th>
                    <th>Статус</th>
                    <th>Объекты</th>
                    <th>Активные SLA</th>
                    <th class="actions">Действия</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($customers)): ?>
                <tr><td colspan="7" style="text-align:center;color:var(--text-muted);">Нет клиентов</td></tr>
                <?php endif; ?>
                <?php foreach ($customers as $c): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($c['name']) ?></strong></td>
                    <td><?= $c['inn'] ?: '—' ?></td>
                    <td><?= htmlspecialchars($c['contact_person'] ?: '—') ?></td>
                    <td><span class="badge badge-<?= $c['status'] ?>"><?= $c['status'] ?></span></td>
                    <td><a href="objects.php?customer_id=<?= $c['id'] ?>"><?= (int)$c['objects_count'] ?></a></td>
                    <td><?= (int)$c['active_contracts'] ?></td>
                    <td class="actions">
                        <a href="?edit=<?= $c['id'] ?>" class="btn btn-secondary btn-sm" data-tooltip="Редактировать">✏️</a>
                        <a href="objects.php?customer_id=<?= $c['id'] ?>" class="btn btn-secondary btn-sm" data-tooltip="Объекты клиента">🏢</a>
                        <a href="sla.php?customer_id=<?= $c['id'] ?>" class="btn btn-secondary btn-sm" data-tooltip="SLA контракты">📋</a>
                        <?php if (auth_has_role('owner')): ?>
                        <a href="?delete=<?= $c['id'] ?>&csrf=<?= $csrf ?>" class="btn btn-danger btn-sm" onclick="return confirm('Удалить клиента? Все связанные объекты останутся без привязки.')" data-tooltip="Удалить">🗑️</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal-overlay <?= $editCust ? 'open' : '' ?>" id="custModal">
    <div class="modal">
        <button class="modal-close" onclick="closeModal()">&times;</button>
        <h2><?= $editCust ? 'Редактировать' : 'Добавить' ?> клиента</h2>
        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="id" value="<?= $editCust['id'] ?? 0 ?>">

            <div class="form-row">
                <div class="form-group">
                    <label for="name">Название *</label>
                    <input type="text" id="name" name="name" value="<?= htmlspecialchars($editCust['name'] ?? '') ?>" required>
                </div>
                <div class="form-group">
                    <label for="inn">ИНН</label>
                    <input type="text" id="inn" name="inn" value="<?= htmlspecialchars($editCust['inn'] ?? '') ?>" maxlength="12">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="kpp">КПП</label>
                    <input type="text" id="kpp" name="kpp" value="<?= htmlspecialchars($editCust['kpp'] ?? '') ?>" maxlength="9">
                </div>
                <div class="form-group">
                    <label for="contact_person">Контактное лицо</label>
                    <input type="text" id="contact_person" name="contact_person" value="<?= htmlspecialchars($editCust['contact_person'] ?? '') ?>">
                </div>
            </div>
            <div class="form-group">
                <label for="legal_address">Юридический адрес</label>
                <input type="text" id="legal_address" name="legal_address" value="<?= htmlspecialchars($editCust['legal_address'] ?? '') ?>">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="contact_phone">Телефон</label>
                    <input type="text" id="contact_phone" name="contact_phone" value="<?= htmlspecialchars($editCust['contact_phone'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label for="contact_email">Email</label>
                    <input type="email" id="contact_email" name="contact_email" value="<?= htmlspecialchars($editCust['contact_email'] ?? '') ?>">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="status">Статус</label>
                    <select id="status" name="status">
                        <option value="active" <?= ($editCust['status'] ?? '') === 'active' ? 'selected' : '' ?>>Активен</option>
                        <option value="inactive" <?= ($editCust['status'] ?? '') === 'inactive' ? 'selected' : '' ?>>Неактивен</option>
                        <option value="prospect" <?= ($editCust['status'] ?? '') === 'prospect' ? 'selected' : '' ?>>Потенциальный</option>
                    </select>
                </div>
                <div class="form-group"></div>
            </div>
            <div class="form-group">
                <label for="notes">Примечания</label>
                <textarea id="notes" name="notes"><?= htmlspecialchars($editCust['notes'] ?? '') ?></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Сохранить</button>
            <button type="button" class="btn btn-secondary" onclick="closeModal()">Отмена</button>
        </form>
    </div>
</div>

<script>
function openModal() { document.getElementById('custModal').classList.add('open'); }
function closeModal() { document.getElementById('custModal').classList.remove('open'); window.location.href = 'customers.php'; }
</script>

<?php require __DIR__ . '/../../inc/footer.php'; ?>
