<?php

date_default_timezone_set('Asia/Kuala_Lumpur');

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

$servername = "localhost";
$username = "[BRAND_CODE_USER]";
$password = "[USER_PASSWORD]";
$dbname = "[BRAND_CODE_DATABASE]";

try {
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8mb4", $username, $password);

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['error' => 'Only POST method allowed']);
        exit;
    }

    $name = trim($_POST['Name'] ?? '');
    $phoneNumber = trim($_POST['PhoneNumber'] ?? '');

    $name = mb_convert_encoding($name, 'UTF-8', 'auto');

    if (empty($name)) {
        echo json_encode(['error' => 'Name is required']);
        exit;
    }

    if (empty($phoneNumber)) {
        echo json_encode(['error' => 'Phone number is required']);
        exit;
    }

    $checkStmt = $pdo->prepare("SELECT Id FROM data WHERE PhoneNumber = ?");
    $checkStmt->execute([$phoneNumber]);

    if ($checkStmt->rowCount() > 0) {
        echo json_encode(['error' => 'Phone number already exists']);
        exit;
    }

    $malaysiaTime = date('Y-m-d H:i:s');

    $insertStmt = $pdo->prepare("INSERT INTO data (Name, PhoneNumber, IsSend, CreateAt, ErrorMsg, ReSend) 
                     VALUES (?, ?, 0, ?, NULL, NULL)");

    if ($insertStmt->execute([$name, $phoneNumber, $malaysiaTime])) {
        $insertId = $pdo->lastInsertId();
        echo json_encode(['success' => true, 'Id' => $insertId]);
    } else {
        echo json_encode(['error' => 'Failed to save data']);
    }

} catch (PDOException $e) {
    error_log('Database error: ' . $e->getMessage());
    echo json_encode(['error' => 'Database connection failed']);
} catch (Exception $e) {
    error_log('General error: ' . $e->getMessage());
    echo json_encode(['error' => 'An error occurred']);
}