<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

require_once "config.php";

$data = json_decode(file_get_contents("php://input"), true);

/* ---------- REQUIRED FIELDS ---------- */
$required = ['first_name','last_name','email','phone','state'];

foreach ($required as $field) {
    if (empty($data[$field])) {
        http_response_code(422);
        echo json_encode([
            "status" => false,
            "message" => "$field is required"
        ]);
        exit;
    }
}

/* ---------- SANITIZE ---------- */
$first_name = trim($data['first_name']);
$last_name  = trim($data['last_name']);
$email      = strtolower(trim($data['email']));
$phone      = trim($data['phone']);
$state      = trim($data['state']);
$customer_id = "CUS" . random_int(100000,999999);

try {

    // Check duplicate email
    $check = $pdo->prepare("SELECT id FROM customers WHERE email = ?");
    $check->execute([$email]);

    if ($check->rowCount() > 0) {
        http_response_code(409);
        echo json_encode([
            "status" => false,
            "message" => "Email already registered"
        ]);
        exit;
    }

    // Insert customer
    $stmt = $pdo->prepare("
        INSERT INTO customers 
        (customer_id, first_name, last_name, email, phone, state)
        VALUES (?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $customer_id,
        $first_name,
        $last_name,
        $email,
        $phone,
        $state
    ]);

    echo json_encode([
        "status" => true,
        "message" => "Account created successfully",
        "customer_id" => $customer_id
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        "status" => false,
        "message" => "Server error"
    ]);
}