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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Method Not Allowed"]);
    exit;
}

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

if (!isset($data['name']) || !isset($data['phone'])) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Missing required fields."]);
    exit;
}

$name   = filter_var($data['name'], FILTER_SANITIZE_STRING);
$phone  = filter_var($data['phone'], FILTER_SANITIZE_STRING);
$age    = filter_var($data['age'] ?? '', FILTER_SANITIZE_STRING);
$weight = filter_var($data['weight'] ?? '', FILTER_SANITIZE_STRING);
$goal   = $data['goal'] ?? []; // Should be array

if (!preg_match("/^[0-9]{10}$/", $phone)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Invalid phone number format."]);
    exit;
}

if (strlen($name) < 3) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Name must be at least 3 characters long."]);
    exit;
}

// Format goal list as comma-separated string
$goal_list = '';
if (is_array($goal)) {
    $goal = array_map('strip_tags', $goal); // XSS protection
    $goal_list = implode(',', $goal);
}

$orderid   = mt_rand(10000, 99999);
$orderdate = date('Y-m-d');

// Payload to send
$payload = [
    'orderid'    => $orderid,
    'fullname'   => $name,
    'mobile'     => $phone,
    'age'        => $age,
    'weight'     => $weight,
    'goal'       => $goal_list,
    'orderdate'  => $orderdate
];
// Log input
file_put_contents('form-log.txt', print_r($payload, true), FILE_APPEND);

// Send to external API
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => 'http://shrichitt.in/crm/api/sex-growth2',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json'
    ],
]);

$response = curl_exec($curl);
$curl_error = curl_error($curl);
curl_close($curl);

// Log success or error
if ($curl_error) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "CURL Error: " . $curl_error]);
} else {
    $decoded_response = json_decode($response, true);
    $payload['api_response'] = $decoded_response ?: $response;

    file_put_contents('success-form-log.txt', print_r($payload, true), FILE_APPEND);
    echo json_encode(["status" => "success", "message" => "Data Inserted Successfully"]);
}
