<?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"]);
// Combine first and second name
$acc_name = trim($fname . ' ' . $sname);
$firstDay = date('Y-m-d');

// ✅ 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, is_verified, verification_code, code_created_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
    ");

    $stmt->execute([
        $username,
        $fname,
        $sname,
        $email,
        $hashedPassword,
        $phone,
        $co_id,
        $verification_code,
        $now
    ]);
    
         // Insert Accounts ( Default account)
$stmt = $pdo->prepare("
INSERT INTO accounts
(
    co_id,
    acc_name,
    acc_type,
    inc_exp,
    acc_categ,
    entry_form,
    acc_source,
    PnL,
    bl_sheet,
    bl_sh_main_sort,
    bl_sh_sub_cat,
    bl_sh_sub_sort,
    user_id,
    op_bl_date,
    status
)
SELECT
    ?,
    ?,
    acc_type,
    inc_exp,
    acc_categ,
    entry_form,
    acc_source,
    PnL,
    bl_sheet,
    bl_sh_main_sort,
    bl_sh_sub_cat,
    bl_sh_sub_sort,
    ?,
    ?,
    status
FROM accounts_Defaults
WHERE acc_categ = 'sales_person'
");

    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"]);
    }
}
