64 lines
1.9 KiB
PHP
64 lines
1.9 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
require_once __DIR__ . '/../db/config.php';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405);
|
|
echo json_encode(['error' => 'Method not allowed']);
|
|
exit;
|
|
}
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
$name = trim($input['name'] ?? '');
|
|
$phone = trim($input['phone'] ?? '');
|
|
|
|
if (empty($name)) {
|
|
echo json_encode(['error' => 'Name is required']);
|
|
exit;
|
|
}
|
|
|
|
if (!preg_match('/^\d{8}$/', $phone)) {
|
|
echo json_encode(['error' => 'Phone number must be exactly 8 digits']);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
|
|
// Check if phone already exists
|
|
$stmt = $pdo->prepare("SELECT id FROM customers WHERE phone = ?");
|
|
$stmt->execute([$phone]);
|
|
if ($stmt->fetch()) {
|
|
echo json_encode(['error' => 'Customer with this phone number already exists']);
|
|
exit;
|
|
}
|
|
|
|
$stmt = $pdo->prepare("INSERT INTO customers (name, phone, points) VALUES (?, ?, 0)");
|
|
if ($stmt->execute([$name, $phone])) {
|
|
$id = $pdo->lastInsertId();
|
|
|
|
// Fetch settings for consistency (though new customer is 0 points)
|
|
$settingsStmt = $pdo->query("SELECT points_for_free_meal FROM loyalty_settings WHERE id = 1");
|
|
$settings = $settingsStmt->fetch(PDO::FETCH_ASSOC);
|
|
$threshold = $settings ? intval($settings['points_for_free_meal']) : 70;
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'customer' => [
|
|
'id' => $id,
|
|
'name' => $name,
|
|
'phone' => $phone,
|
|
'email' => '',
|
|
'points' => 0,
|
|
'eligible_for_free_meal' => false,
|
|
'points_needed' => $threshold
|
|
]
|
|
]);
|
|
} else {
|
|
echo json_encode(['error' => 'Failed to create customer']);
|
|
}
|
|
} catch (Exception $e) {
|
|
error_log("Create Customer Error: " . $e->getMessage());
|
|
echo json_encode(['error' => 'Database error']);
|
|
} |