<?php
header('Content-Type: application/json');

include_once __DIR__ . '/../../config/dbcon.php';
include_once __DIR__ . '/../../helpers/api_helper.php';


session_start();

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, "Invalid request method.");
}

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

$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$password = $data['password'] ?? '';
$phone = trim($data['phone'] ?? '');
$user_type = $data['user_type'] ?? '';

// Validation
if (!$name || !$email || !$password || !$phone || !$user_type) {
    sendResponse(422, "All fields are required.");
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    sendResponse(422, "Invalid email format.");
}

if (!preg_match('/^[0-9]{10,15}$/', $phone)) {
    sendResponse(422, "Phone number must be 10-15 digits.");
}

// Hash password
$passwordHash = password_hash($password, PASSWORD_DEFAULT);

try {
    // Check if email already exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    if ($stmt->rowCount() > 0) {
        sendResponse(409, "Email already registered.");
    }

    // Insert user
    $stmt = $conn->prepare("INSERT INTO users (name, email, password, phone, role, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
    $stmt->execute([$name, $email, $passwordHash, $phone, $user_type]);

    // Auto login: store in session
    $userId = $conn->lastInsertId();
    $_SESSION['user_name'] = $name;
    $_SESSION['user_phone'] = $phone;
    $_SESSION['user_type'] = $user_type;

    sendResponse(201, "Registration successful! You are now logged in.", [
        'user_id' => $userId,
        'user_name' => $name,
        'user_phone' => $phone,
        'user_type' => $user_type
    ]);

} catch (PDOException $e) {
    sendResponse(500, "Database error: " . $e->getMessage());
}
