<?php
session_start();
require_once(__DIR__ . '/../includes/db.php');

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

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $mobile = trim($_POST['mobile']);
    $domain_name = trim($_POST['domain_name']);

    if(!$name || !$email || !$mobile || !$domain_name){
        echo json_encode(['status'=>'error','message'=>'All fields are required.']);
        exit;
    }

    // Check if email already exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE email=? LIMIT 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();
    if($stmt->num_rows > 0){
        echo json_encode(['status'=>'error','message'=>'Email already registered. Please login.']);
        exit;
    }

    // Insert new user
    $stmt = $conn->prepare("INSERT INTO users (name,email,mobile) VALUES (?,?,?)");
    $stmt->bind_param("sss", $name,$email,$mobile);
    if($stmt->execute()){
        $user_id = $stmt->insert_id;

        // Insert initial hosting plan record (optional)
        $plan_name = $_POST['plan_name'] ?? '';
        $stmt2 = $conn->prepare("INSERT INTO hosting_plans (user_id, plan_name, domain_name, payment_status) VALUES (?,?,?,?)");
        $payment_status = 'pending';
        $stmt2->bind_param("isss", $user_id, $plan_name, $domain_name, $payment_status);
        $stmt2->execute();

        echo json_encode(['status'=>'success','user_id'=>$user_id]);
        exit;
    } else {
        echo json_encode(['status'=>'error','message'=>'Registration failed.']);
        exit;
    }
}
