<?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;
}

$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

/*
|--------------------------------------------------------------------------
| Generate Unique 6-Digit Code (PDO VERSION)
|--------------------------------------------------------------------------
*/
function generateUniqueCode($pdo) {
    do {
        $code = random_int(100000, 999999);

        $stmt = $pdo->prepare("SELECT 1 FROM users WHERE verification_code = ?");
        $stmt->execute([$code]);

        $exists = $stmt->fetchColumn(); // returns false if none found

    } while ($exists);

    return $code;
}

$verification_code = generateUniqueCode($pdo);
$now = date('Y-m-d H:i:s');
$user_role = 'master';
$main_wh = 'Main WH';
$cash_ac = 'Cash A/C';
$acc_type = 'Stock';
$acc_type2 = 'Cash';
$inc_exp = '';
$acc_categ = 'warehouse';
$acc_categ2 = 'sales_person';
$acc_categ3 = 'cash_wallet';
$entry_form = 'sale';
$acc_source= 'internal';
$PnL = 'revenue';
$PnL2 = 'none';
$bl_sheet = 'current assets';
$bl_sh_main_sort= '1';
$bl_sh_sub_cat='Accounts Recievable';
$bl_sh_sub_sort='4';
$status = 'active';
$perm_lvl = '7';
$is_verified = '1';

// Combine first and second name
$acc_name = trim($fname . ' ' . $sname);
$firstDay = date('Y-m-d');



try {

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

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

    $stmt->execute([$email,$fname,$sname,$email,$hashedPassword,$phone,$is_verified,$verification_code,$now,$user_role, $status]);

    $user_id = $pdo->lastInsertId();

    // Insert company
    $stmt = $pdo->prepare("
        INSERT INTO company 
        (org_name, org_parent, user_id, phone, country, city, created_at, biz_code, status) 
        VALUES (?, 'P', ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([$business,$user_id,$phone,$country,$city,$now,$verification_code, $status]);
    
   $company_id = $pdo->lastInsertId();

        // Insert Accounts ( user 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) 
        VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?)
    ");

    $stmt->execute([$company_id, $acc_name, $acc_type2, $inc_exp, $acc_categ2, $entry_form, $acc_source, $PnL2, $bl_sheet, $bl_sh_main_sort, $bl_sh_sub_cat, $bl_sh_sub_sort, $user_id, $firstDay, $status]);

   $user_acc_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_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, ?, status 
        FROM accounts_Defaults WHERE (acc_categ<>'sales_person' AND acc_type<>'Deffered Earnings' AND acc_type<>'Deffered Expenses')
        ");
            
       // $stmt->execute([$company_id, $user_id]);
       $stmt->execute([$company_id,$firstDay]);
       
    // 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([$company_id, $user_id, $user_acc_id, $acc_categ2, $perm_lvl]);
        
    // Assign Admin Permissions to Creator of Company
        $stmt = $pdo->prepare("
        INSERT INTO permissions 
        (co_id, user_id, pm_acc_categ, menu_access, pm_acc_lvl) 
        SELECT ?, ?, pm_acc_categ, menu_access, pm_acc_lvl 
        FROM permissions_Defaults
        ");
            
        $stmt->execute([$company_id, $user_id]);
        
        // Create Lock period for Company
        $stmt = $pdo->prepare("
        INSERT INTO trans_period 
        (co_id, min_date) 
        VALUES ( ?, ?)
        ");
            
        $stmt->execute([$company_id, $firstDay]);

    // Create tax settings
        $stmt = $pdo->prepare("
        INSERT INTO taxation 
        (co_id, form, rate, ledger_account) 
        SELECT ?, entry_form, 18, id 
        FROM accounts WHERE acc_categ='journal' AND (pnl='revenue' OR pnl='purchase' OR pnl='profit') AND co_id=?
        ");
            
        $stmt->execute([$company_id, $company_id]);
        
    // Create ledger mapping for transactions
        $stmt = $pdo->prepare("
        INSERT INTO ledger_map 
        (co_id, form, ledger_account) 
        SELECT ?, entry_form, id 
        FROM accounts WHERE acc_categ='journal' AND (pnl='revenue' OR pnl='cost' OR acc_type='sales_tax' OR pnl='purchase' OR pnl='tax' OR pnl='profit') AND co_id=?
        ");
            
        $stmt->execute([$company_id, $company_id]);

    // Create account start date track
        $stmt = $pdo->prepare("
        INSERT INTO account_start_date_track 
        (co_id, acc_id, acc_name, from_date) 
        SELECT ?, id, acc_name,  ?
        FROM accounts WHERE  co_id=?
        ");
            
        $stmt->execute([$company_id, $firstDay, $company_id]);
        
    // Add Document Numbering settings
        $stmt = $pdo->prepare("
      INSERT INTO doc_no_generator 
        (  co_id, form, starting_No, gen_status) 
        SELECT ?, form, starting_No, gen_status 
        FROM doc_no_generator_default 
        ");
            
        $stmt->execute([$company_id]);


    // 3️⃣ Update user with org_id
    $stmt = $pdo->prepare("UPDATE users SET org_id = ? WHERE id = ?");
    $stmt->execute([$company_id, $user_id]);

    $pdo->commit();

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

} catch (PDOException $e) {

    $pdo->rollBack();

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