<?php
require_once 'database.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("不正なリクエストです。");
}

$action = $_GET['action'] ?? '';
$pdo = get_db_connection();

try {
    switch ($action) {
        case 'create':
            $name = $_POST['name'] ?? '';
            if (empty($name)) {
                die("顧客名は必須です。");
            }
            $stmt = $pdo->prepare(
                "INSERT INTO customers (name, name_kana, address, phone, email) 
                 VALUES (:name, :name_kana, :address, :phone, :email)"
            );
            $stmt->bindValue(':name', $name, PDO::PARAM_STR);
            $stmt->bindValue(':name_kana', $_POST['name_kana'] ?? null, PDO::PARAM_STR);
            $stmt->bindValue(':address', $_POST['address'] ?? null, PDO::PARAM_STR);
            $stmt->bindValue(':phone', $_POST['phone'] ?? null, PDO::PARAM_STR);
            $stmt->bindValue(':email', $_POST['email'] ?? null, PDO::PARAM_STR);
            $stmt->execute();
            break;

        case 'update':
            $id = $_POST['id'] ?? null;
            $name = $_POST['name'] ?? '';
            if (!$id || !filter_var($id, FILTER_VALIDATE_INT) || empty($name)) {
                die("無効なデータです。");
            }
            $stmt = $pdo->prepare(
                "UPDATE customers 
                 SET name = :name, name_kana = :name_kana, address = :address, phone = :phone, email = :email 
                 WHERE id = :id"
            );
            $stmt->bindValue(':id', $id, PDO::PARAM_INT);
            $stmt->bindValue(':name', $name, PDO::PARAM_STR);
            $stmt->bindValue(':name_kana', $_POST['name_kana'] ?? null, PDO::PARAM_STR);
            $stmt->bindValue(':address', $_POST['address'] ?? null, PDO::PARAM_STR);
            $stmt->bindValue(':phone', $_POST['phone'] ?? null, PDO::PARAM_STR);
            $stmt->bindValue(':email', $_POST['email'] ?? null, PDO::PARAM_STR);
            $stmt->execute();
            break;

        case 'delete':
            $id = $_POST['id'] ?? null;
            if (!$id || !filter_var($id, FILTER_VALIDATE_INT)) {
                die("無効なIDです。");
            }
            $stmt = $pdo->prepare("DELETE FROM customers WHERE id = :id");
            $stmt->bindValue(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            break;

        default:
            die("無効なアクションです。");
    }

    header('Location: index.php');
    exit;

} catch (PDOException $e) {
    die("データベースエラー: " . $e->getMessage());
}
