<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: POST, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

require __DIR__ . '/database.php';

function respond(int $status, array $payload): void
{
    http_response_code($status);
    echo json_encode($payload);
    exit;
}

function data_store_path(): string
{
    return dirname(__DIR__) . '/data/submissions.json';
}

function read_json_store(): array
{
    $path = data_store_path();
    if (!file_exists($path)) {
        return ['signups' => [], 'contacts' => []];
    }
    $raw = file_get_contents($path);
    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        return ['signups' => [], 'contacts' => []];
    }
    return [
        'signups' => $decoded['signups'] ?? [],
        'contacts' => $decoded['contacts'] ?? [],
    ];
}

function append_json_store(string $type, array $payload): void
{
    $path = data_store_path();
    $dir = dirname($path);
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }
    $store = read_json_store();
    if (!isset($store[$type]) || !is_array($store[$type])) {
        $store[$type] = [];
    }
    $store[$type][] = $payload;
    file_put_contents($path, json_encode($store, JSON_PRETTY_PRINT));
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(405, ['message' => 'Method not allowed.']);
}

$action = $_GET['action'] ?? '';
$rawBody = file_get_contents('php://input');
$payload = json_decode($rawBody, true);
if (!is_array($payload)) {
    $payload = $_POST ?? [];
}

$payload = array_map(static function ($value) {
    if (is_string($value)) {
        return trim($value);
    }
    return $value;
}, $payload);

try {
    $pdo = db();
    ensure_tables($pdo);
} catch (Throwable $exception) {
    respond(500, ['message' => 'Unable to connect to the database.', 'error' => $exception->getMessage()]);
}

switch ($action) {
    case 'contact':
        handle_contact($pdo, $payload);
        break;
    case 'signup':
        handle_signup($pdo, $payload);
        break;
    case 'signin':
        handle_signin($pdo, $payload);
        break;
    default:
        respond(404, ['message' => 'Unknown action.']);
}

function handle_contact(PDO $pdo, array $payload): void
{
    $name = $payload['name'] ?? '';
    $email = filter_var($payload['email'] ?? '', FILTER_VALIDATE_EMAIL);
    if (!$name || !$email) {
        respond(400, ['message' => 'Name and a valid email are required.']);
    }

    $stmt = $pdo->prepare('INSERT INTO contact_requests (name, email, company, team, message) VALUES (?, ?, ?, ?, ?)');
    $stmt->execute([
        $name,
        $email,
        $payload['company'] ?? null,
        $payload['team'] ?? null,
        $payload['message'] ?? null,
    ]);

    append_json_store('contacts', [
        'id' => uniqid('contact_', true),
        'name' => $name,
        'email' => $email,
        'company' => $payload['company'] ?? '',
        'team' => $payload['team'] ?? '',
        'message' => $payload['message'] ?? '',
        'receivedAt' => date('c'),
    ]);

    respond(200, ['message' => 'Thanks! A LeadSniper specialist will reply from the main domain shortly.']);
}

function handle_signup(PDO $pdo, array $payload): void
{
    $email = filter_var($payload['email'] ?? '', FILTER_VALIDATE_EMAIL);
    $password = $payload['password'] ?? '';

    if (!$email || strlen($password) < 8) {
        respond(400, ['message' => 'Provide a valid email and an 8+ character password.']);
    }

    $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        respond(409, ['message' => 'An account with this email already exists.']);
    }

    $hash = password_hash($password, PASSWORD_DEFAULT);
    $workspace = $payload['workspace'] ?? '';
    if (!$workspace) {
        $workspace = api_config()['default_workspace'] ?? '/domains/app/index.html';
    }

    $stmt = $pdo->prepare('INSERT INTO users (email, password_hash, team, goal, workspace_url) VALUES (?, ?, ?, ?, ?)');
    $stmt->execute([
        $email,
        $hash,
        $payload['team'] ?? null,
        $payload['goal'] ?? null,
        $workspace,
    ]);

    append_json_store('signups', [
        'id' => uniqid('signup_', true),
        'email' => $email,
        'team' => $payload['team'] ?? '',
        'goal' => $payload['goal'] ?? '',
        'workspace' => $workspace,
        'receivedAt' => date('c'),
    ]);

    respond(200, ['message' => 'Signup stored. Watch your inbox for routing instructions.', 'redirect' => $workspace]);
}

function handle_signin(PDO $pdo, array $payload): void
{
    $email = filter_var($payload['email'] ?? '', FILTER_VALIDATE_EMAIL);
    $password = $payload['password'] ?? '';

    if (!$email || !$password) {
        respond(400, ['message' => 'Email and password are required.']);
    }

    $stmt = $pdo->prepare('SELECT id, password_hash, workspace_url FROM users WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    if (!$user || !password_verify($password, $user['password_hash'])) {
        respond(401, ['message' => 'Invalid credentials.']);
    }

    $workspace = $user['workspace_url'] ?: (api_config()['default_workspace'] ?? '/domains/app/index.html');

    respond(200, ['message' => 'Signed in. Redirecting you to your workspace.', 'redirect' => $workspace]);
}
