Files
sam-sales/sales_scenario/api_handler.php

68 lines
2.7 KiB
PHP
Raw Normal View History

2025-12-17 12:59:26 +09:00
<?php
include '../lib/mydb.php';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
$method = $_SERVER['REQUEST_METHOD'];
$pdo = db_connect();
if ($method === 'GET') {
$tenantId = $_GET['tenant_id'] ?? 'default_tenant';
try {
$stmt = $pdo->prepare("SELECT step_id, checkpoint_index FROM sales_scenario_checklist WHERE tenant_id = :tenant_id AND is_checked = 1");
$stmt->execute([':tenant_id' => $tenantId]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$data = [];
foreach ($rows as $row) {
if (!isset($data[$row['step_id']])) {
$data[$row['step_id']] = [];
}
$data[$row['step_id']][] = (int)$row['checkpoint_index'];
}
echo json_encode(['success' => true, 'data' => $data]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
}
elseif ($method === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
echo json_encode(['success' => false, 'message' => 'Invalid input']);
exit;
}
$tenantId = $input['tenant_id'] ?? 'default_tenant';
$stepId = $input['step_id'];
$checkpointIndex = $input['checkpoint_index'];
$isChecked = $input['is_checked'] ? 1 : 0;
try {
if ($isChecked) {
// Insert or ignore (if already exists)
$stmt = $pdo->prepare("INSERT IGNORE INTO sales_scenario_checklist (tenant_id, step_id, checkpoint_index, is_checked) VALUES (:tenant_id, :step_id, :idx, 1)");
$stmt->execute([':tenant_id' => $tenantId, ':step_id' => $stepId, ':idx' => $checkpointIndex]);
} else {
// Delete record if unchecked
$stmt = $pdo->prepare("DELETE FROM sales_scenario_checklist WHERE tenant_id = :tenant_id AND step_id = :step_id AND checkpoint_index = :idx");
$stmt->execute([':tenant_id' => $tenantId, ':step_id' => $stepId, ':idx' => $checkpointIndex]);
}
// Return updated list for this step
$stmt = $pdo->prepare("SELECT checkpoint_index FROM sales_scenario_checklist WHERE tenant_id = :tenant_id AND step_id = :step_id AND is_checked = 1");
$stmt->execute([':tenant_id' => $tenantId, ':step_id' => $stepId]);
$checkedIndices = $stmt->fetchAll(PDO::FETCH_COLUMN);
echo json_encode(['success' => true, 'data' => array_map('intval', $checkedIndices)]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
}
?>