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

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

// Read and decode the JSON body
$input = file_get_contents("php://input");
$data = json_decode($input, true);

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

// Sanitize inputs
$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);

// Sanitize checkbox/radio options
$goals = [
    'early_discharge'   => filter_var($data['early_discharge'] ?? '', FILTER_SANITIZE_STRING),
    'low_stamina'       => filter_var($data['low_stamina'] ?? '', FILTER_SANITIZE_STRING),
    'size_issue'        => filter_var($data['size_issue'] ?? '', FILTER_SANITIZE_STRING),
    'erection_problem'  => filter_var($data['erection_problem'] ?? '', FILTER_SANITIZE_STRING)
];

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

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

// Create order ID and date
$orderid = mt_rand(10000, 99999);
$orderdate = date('Y-m-d');

// Construct payload
$payload = array_merge([
    'orderid'   => $orderid,
    'fullname'  => $name,
    'mobile'    => $phone,
    'age'       => $age,
    'weight'    => $weight,
    'orderdate' => $orderdate
], $goals);

// Log raw payload
file_put_contents('form-log.txt', print_r($payload, true), FILE_APPEND);

// Send data to external API
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => 'http://shrichitt.in/crm/api/sex-growth',
    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);

// Handle response
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"]);
}
