<?php
// Initialize the session
session_start(['read_and_close' => true]);
if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        "status"=>"error",
        "type"=>"session_expired"
    ]);
    exit;
}
require 'db.php';
header('Content-Type: application/json');

$coid  = $_SESSION['co_id'];
$userid  = $_SESSION['user_id'];

session_write_close();

$country   = trim($_POST["country1"] ?? '');
$city      = trim($_POST["city1"] ?? '');
$business  = trim($_POST["business1"] ?? '');

$terms     = isset($_POST["terms"]);

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



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

        $stmt = $pdo->prepare("
            SELECT 1 
            FROM company 
            WHERE biz_code = ?
        ");

        $stmt->execute([$code]);

        $exists = $stmt->fetchColumn();

    } 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 company
    $stmt = $pdo->prepare("
        INSERT INTO company 
        (org_name, org_parent, user_id,  country, city, created_at, biz_code, status) 
        VALUES (?, 'P', ?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([$business, $userid ,$country,$city,$now,$verification_code, $status]);
    
   $company_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,$firstDay]);
       

    // 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, $userid]);
        
        // 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) {

    if ($pdo->inTransaction()) {
    $pdo->rollBack();
}

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