<?php
/**
 * Customer Register API
 * MontaLoja E-commerce
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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

require_once __DIR__ . '/../../includes/config.php';

try {
    $pdo = getDB();
    
    $input = json_decode(file_get_contents('php://input'), true);

    $name = trim($input['name'] ?? '');
    $email = trim($input['email'] ?? '');
    $phone = preg_replace('/\D/', '', $input['phone'] ?? '');
    $password = $input['password'] ?? '';
    $storeId = intval($input['store_id'] ?? 0);
    $address = $input['address'] ?? [];

    // Validations
    if (empty($name) || empty($email) || empty($phone) || empty($password)) {
        echo json_encode(['success' => false, 'message' => 'Preencha todos os campos obrigatórios']);
        exit;
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => 'E-mail inválido']);
        exit;
    }

    if (strlen($password) < 6) {
        echo json_encode(['success' => false, 'message' => 'Senha deve ter pelo menos 6 caracteres']);
        exit;
    }

    // Check if email or phone already exists
    $stmt = $pdo->prepare("SELECT id FROM customers WHERE (email = ? OR phone = ?) AND store_id = ?");
    $stmt->execute([$email, $phone, $storeId]);
    if ($stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'E-mail ou WhatsApp já cadastrado']);
        exit;
    }

    // Hash password
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    // Insert customer
    $stmt = $pdo->prepare("
        INSERT INTO customers (store_id, name, email, phone, password, is_active, created_at)
        VALUES (?, ?, ?, ?, ?, 1, NOW())
    ");
    $stmt->execute([$storeId, $name, $email, $phone, $hashedPassword]);
    $customerId = $pdo->lastInsertId();

    // Insert address if provided
    if (!empty($address['cep']) && !empty($address['street'])) {
        $stmt = $pdo->prepare("
            INSERT INTO customer_addresses
            (customer_id, store_id, label, cep, street, number, complement, neighborhood, city, state, is_default, created_at)
            VALUES (?, ?, 'Casa', ?, ?, ?, ?, ?, ?, ?, 1, NOW())
        ");
        $stmt->execute([
            $customerId,
            $storeId,
            preg_replace('/\D/', '', $address['cep'] ?? ''),
            $address['street'] ?? '',
            $address['number'] ?? '',
            $address['complement'] ?? '',
            $address['neighborhood'] ?? '',
            $address['city'] ?? '',
            $address['state'] ?? ''
        ]);
    }

    // Start session and login automatically
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    $_SESSION['customer_id'] = $customerId;
    $_SESSION['customer_name'] = $name;
    $_SESSION['customer_email'] = $email;
    $_SESSION['customer_phone'] = $phone;
    $_SESSION['customer_store_id'] = $storeId;

    echo json_encode([
        'success' => true,
        'message' => 'Conta criada com sucesso',
        'customer' => [
            'id' => $customerId,
            'name' => $name,
            'email' => $email
        ]
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Erro interno: ' . $e->getMessage()]);
}
