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

// Trim all inputs safely
$email      = trim($_POST["email"] ?? '');
$co_id      = trim($_POST["id"] ?? '');
$fname      = trim($_POST["fname"] ?? '');
$sname      = trim($_POST["sname"] ?? '');
$username   = trim($_POST["username"] ?? '');
$phone      = trim($_POST["phone"] ?? '');
$password   = $_POST["password"] ?? '';
$password2  = $_POST["password2"] ?? '';
$terms      = isset($_POST["terms"]);

// ✅ Check required fields (email was missing in your original check)
if (!$fname || !$sname || !$username || !$phone || !$email || !$password || !$password2) {
    http_response_code(400);
    echo json_encode(["status" => "error", "type" => "empty"]);
    exit;
}

// ✅ Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "type" => "email"]);
    exit;
}

// ✅ Password match check
if ($password !== $password2) {
    http_response_code(400);
    echo json_encode(["status" => "error", "type" => "password_mismatch"]);
    exit;
}

// ✅ Terms agreement check
if (!$terms) {
    http_response_code(400);
    echo json_encode(["status" => "error", "type" => "terms"]);
    exit;
}

// ✅ Secure password hash
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

// ✅ Secure 6-digit verification code
$verification_code = random_int(100000, 999999);
$now = date('Y-m-d H:i:s');

try {

    // OPTIONAL (Recommended): Check if email or username exists first
    $check = $pdo->prepare("SELECT id FROM users WHERE email = ? OR username = ?");
    $check->execute([$email, $username]);

    if ($check->fetch()) {
        http_response_code(409);
        echo json_encode(["status" => "error", "type" => "exists"]);
        exit;
    }

    // Insert user
    $stmt = $pdo->prepare("
        INSERT INTO users 
        (username, firstname, secondname, email, password, phone, org_id, verification_code, code_created_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $username,
        $fname,
        $sname,
        $email,
        $hashedPassword,
        $phone,
        $co_id,
        $verification_code,
        $now
    ]);

    echo json_encode([
        "status" => "success"
    ]);

} catch (PDOException $e) {

    if ($e->getCode() == 23000) {
        http_response_code(409);
        echo json_encode(["status" => "error", "type" => "exists"]);
    } else {
        http_response_code(500);
        echo json_encode(["status" => "error", "type" => "server"]);
    }
}
