<?php
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(403); exit(json_encode(['success'=>false,'message'=>'Unauthorized'])); }
require_once '../connect.php';
if (!currentUserIsSuperAdmin($conn)) jsonResponse(false, 'Only system owner can create accounts');
$action = $_POST['action'] ?? '';
if ($action !== 'create_account') jsonResponse(false, 'Invalid action');
$client = sanitize($conn, $_POST['client_name'] ?? '');
$business = sanitize($conn, $_POST['business_name'] ?? '');
$phone = sanitize($conn, $_POST['phone'] ?? '');
$email = sanitize($conn, $_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
if (!$client || !$business || !$email || !$password) jsonResponse(false, 'Client, business, email and password are required');
$chk=$conn->query("SELECT id FROM users WHERE email='$email' LIMIT 1");
if($chk && $chk->num_rows) jsonResponse(false, 'Email already in use');
$conn->begin_transaction();
try {
    $conn->query("INSERT INTO accounts (client_name,business_name,phone,email,status,currency,price_decimals,default_leads_view,language_code,default_language_code) VALUES ('$client','$business','$phone','$email','active','USD',2,'list','en','en')");
    $newAccountId=(int)$conn->insert_id;
    $rolePerm=$conn->real_escape_string(json_encode(['all'=>true]));
    $conn->query("INSERT INTO roles (name,permissions,account_id) VALUES ('Administrator','$rolePerm',$newAccountId)");
    $roleId=(int)$conn->insert_id;
    $hash=$conn->real_escape_string(password_hash($password, PASSWORD_DEFAULT));
    $conn->query("INSERT INTO users (name,email,phone,password,role_id,account_id) VALUES ('$client','$email','$phone','$hash',$roleId,$newAccountId)");
    $newUserId=(int)$conn->insert_id;
    createDefaultStages($conn, $newAccountId);
    grantFullPermissions($conn, $newAccountId, $newUserId);
    $conn->commit();
    jsonResponse(true, 'Account created', ['account_id'=>crmEncodeId($newAccountId),'user_id'=>crmEncodeId($newUserId)]);
} catch (Throwable $e) {
    $conn->rollback();
    error_log('create_account failed: '.$e->getMessage());
    jsonResponse(false, 'Could not create account');
}
