<?php
/**
 * signup-handler.php — receives the signup form's POST, validates every
 * field server-side (never trust the browser), and runs the full
 * provisioning flow. Returns JSON either way, matching what signup.html's
 * JavaScript expects.
 *
 * SECURITY NOTE: rate limiting is NOT implemented here — add one before
 * going live (e.g. limit to 3 signups per IP per hour), otherwise this
 * endpoint can be used to spam-create databases. A simple approach: log
 * attempts by IP in a small table and reject once a threshold is hit,
 * the same pattern this codebase already uses for admin login attempts
 * (`login_attempt` table) in every individual store.
 */
require_once __DIR__ . '/../lib/StoreProvisioner.php';
require_once __DIR__ . '/../config/master-db.php';   // returns connected PDO as $masterDb
require_once __DIR__ . '/../config/cpanel-config.php'; // returns configured CpanelApi as $cpanelApi
require_once __DIR__ . '/../config/provisioner-config.php'; // paths/domain constants

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// ---------------------------------------------------------------------
// Validation — every field checked server-side regardless of what the
// browser's own HTML5 validation already did.
// ---------------------------------------------------------------------
function fail(string $message, int $code = 422): void
{
    http_response_code($code);
    echo json_encode(['success' => false, 'error' => $message]);
    exit;
}

$storeName    = trim($_POST['store_name'] ?? '');
$subdomain    = trim($_POST['subdomain'] ?? '');
$businessType = trim($_POST['business_type'] ?? 'general');
$ownerName    = trim($_POST['owner_name'] ?? '');
$ownerEmail   = trim($_POST['owner_email'] ?? '');
$ownerPhone   = trim($_POST['owner_phone'] ?? '');
$adminPass    = (string)($_POST['admin_password'] ?? '');

if ($storeName === '' || mb_strlen($storeName) > 255) {
    fail('Please enter a valid store name.');
}
if ($subdomain === '') {
    fail('Please choose a store address.');
}
if ($ownerName === '' || mb_strlen($ownerName) > 255) {
    fail('Please enter your name.');
}
if (!filter_var($ownerEmail, FILTER_VALIDATE_EMAIL)) {
    fail('Please enter a valid email address.');
}
if (strlen($adminPass) < 8) {
    fail('Password must be at least 8 characters.');
}

// Basic duplicate-email guard — one email shouldn't rack up unlimited
// free stores. Adjust the limit to whatever policy you actually want.
$existingCount = $masterDb->prepare(
    "SELECT COUNT(*) FROM stores WHERE owner_email = ? AND status NOT IN ('deleted','expired')"
);
$existingCount->execute([$ownerEmail]);
if ((int)$existingCount->fetchColumn() >= 3) {
    fail('This email already has the maximum number of active stores. Contact support if you need more.');
}

// ---------------------------------------------------------------------
// Provision
// ---------------------------------------------------------------------
$provisioner = new StoreProvisioner(
    $cpanelApi,
    $masterDb,
    QC_ROOT_DOMAIN,
    QC_CPANEL_HOME_DIR,
    QC_TEMPLATE_PATH,
    QC_STORES_SUBDIR
);

try {
    $result = $provisioner->provision([
        'store_name'     => $storeName,
        'subdomain'      => $subdomain,
        'business_type'  => $businessType,
        'owner_name'     => $ownerName,
        'owner_email'    => $ownerEmail,
        'owner_phone'    => $ownerPhone ?: null,
        'admin_password' => $adminPass,
    ]);

    // TODO: send a welcome email here with $result['store_url'],
    // $result['admin_url'], and $result['admin_username'] — the password
    // is intentionally NOT re-sent by email; the owner just set it themselves.

    echo json_encode([
        'success'   => true,
        'store_url' => $result['store_url'],
        'admin_url' => $result['admin_url'],
    ]);
} catch (ProvisioningException $e) {
    fail($e->getMessage(), 500);
} catch (\Throwable $e) {
    error_log('[signup-handler] Unexpected error: ' . $e->getMessage());
    fail('Something went wrong on our end. Please try again in a moment.', 500);
}
