<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/config.php';

$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Método não permitido.';
    echo json_encode($response);
    exit;
}

$pdo = getDB();
$baseDomain = 'duolead.com.br';

try {
    $businessType = $_POST['business_type'] ?? 'retail';
    $storeName = trim($_POST['store_name'] ?? '');
    $subdomain = trim($_POST['subdomain'] ?? '');
    $ownerName = trim($_POST['owner_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $planId = $_POST['plan_id'] ?? 'free';

    $subdomain = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $subdomain));

    $storeTypeMap = ['retail' => 'clothing_store', 'service' => 'barbershop', 'food' => 'restaurant', 'other' => 'other'];
    $storeType = $storeTypeMap[$businessType] ?? 'other';

    if (empty($storeName)) throw new Exception('Nome da loja é obrigatório.');
    if (strlen($subdomain) < 3) throw new Exception('O endereço deve ter no mínimo 3 caracteres.');
    if (strlen($subdomain) > 30) throw new Exception('O endereço deve ter no máximo 30 caracteres.');
    if (empty($ownerName)) throw new Exception('Seu nome é obrigatório.');
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) throw new Exception('E-mail inválido.');
    if (strlen($password) < 6) throw new Exception('A senha deve ter no mínimo 6 caracteres.');
    if ($password !== $confirmPassword) throw new Exception('As senhas não conferem.');

    $reserved = ['www', 'app', 'admin', 'api', 'mail', 'ftp', 'cpanel', 'webmail', 'painel', 'sistema', 'login', 'register', 'dashboard', 'cadastro'];
    if (in_array($subdomain, $reserved)) throw new Exception('Este endereço está reservado.');

    $checkSubdomain = $pdo->prepare("SELECT id FROM stores WHERE subdomain = ?");
    $checkSubdomain->execute([$subdomain]);
    if ($checkSubdomain->fetch()) throw new Exception('Este endereço já está em uso.');

    $checkEmail = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $checkEmail->execute([$email]);
    if ($checkEmail->fetch()) throw new Exception('Este e-mail já está cadastrado.');

    $checkPlan = $pdo->prepare("SELECT id, has_trial, trial_days FROM plans WHERE id = ? AND is_active = 1");
    $checkPlan->execute([$planId]);
    $planData = $checkPlan->fetch(PDO::FETCH_ASSOC);
    if (!$planData) {
        $planId = 'free';
        $hasTrial = 1;
        $trialDays = 14;
    } else {
        $hasTrial = $planData['has_trial'] ?? 0;
        $trialDays = $planData['trial_days'] ?? 14;
    }

    // Definir status e trial_ends_at baseado nas configurações do plano
    $storeStatus = $hasTrial ? 'trial' : 'active';
    $trialEndsAt = $hasTrial ? date('Y-m-d H:i:s', strtotime("+{$trialDays} days")) : null;

    $pdo->beginTransaction();

    $insertStore = $pdo->prepare("INSERT INTO stores (name, type, business_type, slug, subdomain, whatsapp_number, email, plan_id, status, trial_ends_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    $insertStore->execute([$storeName, $storeType, $businessType, $subdomain, $subdomain, preg_replace('/\D/', '', $phone), $email, $planId, $storeStatus, $trialEndsAt]);
    $storeId = $pdo->lastInsertId();

    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    $insertUser = $pdo->prepare("INSERT INTO users (store_id, name, email, password_hash, phone, role, is_active, created_at) VALUES (?, ?, ?, ?, ?, 'owner', 1, NOW())");
    $insertUser->execute([$storeId, $ownerName, $email, $passwordHash, preg_replace('/\D/', '', $phone)]);
    $userId = $pdo->lastInsertId();

    $updateStore = $pdo->prepare("UPDATE stores SET owner_user_id = ? WHERE id = ?");
    $updateStore->execute([$userId, $storeId]);

    $pdo->commit();

    $storeUrl = 'https://' . $subdomain . '.' . $baseDomain;
    $response['success'] = true;
    $response['message'] = 'Loja criada com sucesso!';
    $response['store_url'] = $storeUrl;
    $response['store_id'] = $storeId;
    $response['user_id'] = $userId;

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
