<?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';
$status = 'active';

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



try {

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

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

    $stmt->execute([$email,$fname,$sname,$email,$hashedPassword,$phone,$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, user_id, parent_id, status) 
        VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([$company_id, $acc_name, $acc_type2, $inc_exp, $acc_categ2, $entry_form, $acc_source, $PnL2, $bl_sheet, $user_id, $user_id, $status]);
    
     // 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, parent_id, status) 
        SELECT ?, acc_name, acc_type, inc_exp, acc_categ, entry_form, acc_source, PnL, bl_sheet, ?, status 
        FROM accounts_Defaults
        ");
            
        $stmt->execute([$company_id, $user_id]);
        
    // Assign Permissions to Creator of Company
        $stmt = $pdo->prepare("
        INSERT INTO permissions 
        (co_id, user_id, pm_acc_categ, pm_acc_lvl) 
        SELECT ?, ?, pm_acc_categ, 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]);

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