<?php
require_once 'db.php';

$search_keyword = '';
if (isset($_GET['search'])) {
    $search_keyword = $_GET['search'];
}

// 検索クエリの作成
$sql = "SELECT * FROM customers";
if (!empty($search_keyword)) {
    // 検索対象に address カラムを追加
    $sql .= " WHERE name LIKE :keyword OR name_kana LIKE :keyword OR address LIKE :keyword OR phone LIKE :keyword OR email LIKE :keyword";
}
$sql .= " ORDER BY id ASC";

$stmt = $db->prepare($sql);

if (!empty($search_keyword)) {
    $stmt->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR);
}

$stmt->execute();
$customers = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>顧客管理システム</title>
    <style>
        /* 簡単なスタイル */
        body { font-family: sans-serif; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; }
        th { background-color: #f2f2f2; }
        .button-group a, .button-group button { margin-right: 5px; }
        .search-form { margin-bottom: 20px; }
    </style>
</head>
<body>
    <h1>顧客一覧</h1>

    <div class="search-form">
        <form action="index.php" method="get">
            <input type="text" name="search" placeholder="検索キーワード" value="<?= h($search_keyword) ?>">
            <button type="submit">検索</button>
        </form>
    </div>

    <div class="button-group">
        <a href="create.php"><button>新規登録</button></a>
    </div>

    <table>
        <thead>
            <tr>
                <th>顧客ID</th>
                <th>顧客名</th>
                <th>フリガナ</th>
                <th>住所</th>
                <th>電話番号</th>
                <th>メールアドレス</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($customers as $customer): ?>
                <tr>
                    <td><?= h($customer['id']) ?></td>
                    <td><?= h($customer['name']) ?></td>
                    <td><?= h($customer['name_kana']) ?></td>
                    <!-- nl2br()で改行を<br>タグに変換して表示 -->
                    <td><?= nl2br(h($customer['address'])) ?></td>
                    <td><?= h($customer['phone']) ?></td>
                    <td><?= h($customer['email']) ?></td>
                    <td class="button-group">
                        <a href="edit.php?id=<?= h($customer['id']) ?>"><button>更新</button></a>
                        <form action="delete.php" method="post" style="display:inline;" onsubmit="return confirm('本当に削除しますか？');">
                            <input type="hidden" name="id" value="<?= h($customer['id']) ?>">
                            <button type="submit">削除</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</body>
</html>