<?php 
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST");
header("Allow: POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Origin");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request method'
    ]);
    exit;
}

require 'db.php'; // Include DB connection

// Get POST data
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$surname = isset($_POST['surname']) ? trim($_POST['surname']) : '';
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$reg_no = isset($_POST['reg_no']) ? trim($_POST['reg_no']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';

// Basic validation
if (empty($name) || empty($surname) || empty($username) || empty($reg_no) || empty($email) || empty($password) || empty($phone)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'All fields are required.'
    ]);
    exit;
}

// Check if email, reg_no, or username already exists
$sqlCheck = "SELECT * FROM users WHERE email = :email OR reg_no = :reg_no OR username = :username LIMIT 1";
$stmtCheck = $conn->prepare($sqlCheck);
$stmtCheck->bindParam(':email', $email);
$stmtCheck->bindParam(':reg_no', $reg_no);
$stmtCheck->bindParam(':username', $username);
$stmtCheck->execute();

if ($stmtCheck->fetch(PDO::FETCH_ASSOC)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Email, Username or Registration number already exists.'
    ]);
    exit;
}

// Hash the password
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

// Insert user into database
$sqlInsert = "INSERT INTO users (name, surname, username, reg_no, email, password, phone) 
              VALUES (:name, :surname, :username, :reg_no, :email, :password, :phone)";
$stmtInsert = $conn->prepare($sqlInsert);
$stmtInsert->bindParam(':name', $name);
$stmtInsert->bindParam(':surname', $surname);
$stmtInsert->bindParam(':username', $username);
$stmtInsert->bindParam(':reg_no', $reg_no);
$stmtInsert->bindParam(':email', $email);
$stmtInsert->bindParam(':password', $hashedPassword);
$stmtInsert->bindParam(':phone', $phone);

if ($stmtInsert->execute()) {
    echo json_encode([
        'status' => 'success',
        'message' => 'User registered successfully.'
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to register user.'
    ]);
}
?>
