<?php
// api/register.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

require_once __DIR__ . '/../inc/db.php';
require_once __DIR__ . '/../inc/functions.php';

$data = get_post_data();
$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$password = $data['password'] ?? '';
$confirm = $data['confirm_password'] ?? $data['confirm'] ?? '';

if (!$name || !$email || !$password || !$confirm) {
    send_json(['status'=>false,'msg'=>'All fields are required']);
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    send_json(['status'=>false,'msg'=>'Invalid email']);
}
if ($password !== $confirm) {
    send_json(['status'=>false,'msg'=>'Password and confirm password do not match']);
}

// check if email exists
$stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
    send_json(['status'=>false,'msg'=>'Email already registered']);
}
$stmt->close();

$hash = password_hash($password, PASSWORD_BCRYPT);
$token = create_api_token(32);

$stmt = $conn->prepare("INSERT INTO users (name, email, password, api_token) VALUES (?,?,?,?)");
$stmt->bind_param("ssss", $name, $email, $hash, $token);
if ($stmt->execute()) {
    $insert_id = $stmt->insert_id;
    send_json(['status'=>true,'msg'=>'Registration successful','data'=>['id'=>$insert_id,'name'=>$name,'email'=>$email,'api_token'=>$token]]);
} else {
    send_json(['status'=>false,'msg'=>'Registration failed', 'error' => $conn->error]);
}
?>
