<?php
/**
 * Customer Login 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);
}

error_reporting(E_ALL);
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(["success" => false, "message" => "PHP Error: $errstr in $errfile line $errline"], JSON_UNESCAPED_UNICODE);
    exit;
});
set_exception_handler(function($e) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(["success" => false, "message" => "Exception: " . $e->getMessage()], JSON_UNESCAPED_UNICODE);
    exit;
});

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

try {
    $pdo = getDB();
    
    $rawInput = file_get_contents('php://input');
    file_put_contents(__DIR__ . '/login_debug.log', "RAW POST: " . $rawInput . "\n", FILE_APPEND);
    
    $input = json_decode($rawInput, true);

    $identifier = trim($input['identifier'] ?? '');
    $password = $input['password'] ?? '';
    $storeId = intval($input['store_id'] ?? 0);

    if (empty($identifier) || empty($password)) {
        echo json_encode(['success' => false, 'message' => 'Preencha todos os campos']);
        exit;
    }

    // Clean phone number if provided
    $cleanPhone = preg_replace('/\D/', '', $identifier);

    // Try to find customer by email or phone
    $stmt = $pdo->prepare("
        SELECT id, name, email, phone, password
        FROM customers
        WHERE (email = ? OR phone = ?)
        AND store_id = ?
        AND is_active = 1
        LIMIT 1
    ");
    $stmt->execute([$identifier, $cleanPhone, $storeId]);
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$customer) {
        echo json_encode(['success' => false, 'message' => 'Usuário não encontrado']);
        exit;
    }

    // Verify password
    if (!password_verify($password, $customer['password'])) {
        echo json_encode(['success' => false, 'message' => 'Senha incorreta']);
        exit;
    }

    // Start session and set customer data
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

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

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

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