<?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');
$acc_categ2 = 'sales_person';
$perm_lvl = '2';

try {
    
        // IMPORTANT: wrap in transaction
         $pdo->beginTransaction();

    // 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, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, 'active')
    ");

    $stmt->execute([
        $username,
        $fname,
        $sname,
        $email,
        $hashedPassword,
        $phone,
        $co_id,
        $verification_code,
        $now
    ]);
    
    $user_id = $pdo->lastInsertId();
    
         // 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,
                ?,
                ?,
                'active'
            FROM accounts_Defaults
            WHERE acc_categ = 'sales_person'
            ");

        $stmt->execute([$co_id,$acc_name, $user_id, $firstDay]);
        
          $account_id = $pdo->lastInsertId();
          
          
    // Assign Personal account Permissions to Creator account
        $stmt = $pdo->prepare("
        INSERT INTO permissions 
        (co_id, user_id, pm_acc_id, pm_acc_categ, pm_acc_lvl) 
         VALUES ( ?, ?, ?, ?, ?)
        ");
            
        $stmt->execute([$co_id, $user_id, $account_id, $acc_categ2, $perm_lvl]);
 

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