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

$fname = trim($_POST["fname"] ?? '');
$sname= trim($_POST["sname"] ?? '');
$country= trim($_POST["country"] ?? '');
$city= trim($_POST["city"] ?? '');
$phone = trim($_POST["phone"] ?? '');
$business = trim($_POST["business"] ?? '');
$email = trim($_POST["email"] ?? '');
$password = $_POST["password"] ?? '';
$password2 = $_POST["password2"] ?? '';
$terms = isset($_POST["terms"]);

if (!$email || !$password || !$password2 || !$fname || !$sname || !$country || !$city || !$phone || !$terms || !$business) {
    echo json_encode(["status" => "error", "type" => "empty"]);
    exit;
}

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

if ($password !== $password2) {
    echo json_encode(["status" => "error", "type" => "password_mismatch"]);
    exit;
}

if (!$terms) {
    echo json_encode(["status" => "error", "type" => "terms"]);
    exit;
}

$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// generate 6 digit code
$verification_code = rand(100000, 999999);
$now = date('Y-m-d H:i:s');
$user_role = 'master';


try {
    $stmt = $pdo->prepare("INSERT INTO users (username, firstname, secondname, email, password, phone, verification_code, code_created_at, role) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$email, $fname, $sname, $email, $hashedPassword, $phone, $verification_code, $now, $user_role]);
    
    $stmt = $pdo->prepare("INSERT INTO company (org_name, org_parent, user_id, phone, country, city, created_at) SELECT ?, 'P', u.id, ?, ?, ?, ? FROM users u WHERE u.username = ?");
    $stmt->execute([$business, $phone, $country, $city, $now, $email]);

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

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