<?php
require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';

$data = json_decode(file_get_contents('php://input'), true);
$email = filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL);
$password = $data['password'] ?? '';

if (!$email || !$password) {
    sendError('Email and password required', 400);
}

$stmt = $pdo->prepare("SELECT id, email, password, status, display_name FROM public_users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();

if (!$user || !password_verify($password, $user['password'])) {
    sendError('Invalid email or password', 401);
}

if ($user['status'] !== 'active') {
    sendError('Account is not active. Please contact support.', 403);
}

// Delete old tokens
$stmt = $pdo->prepare("DELETE FROM public_user_tokens WHERE user_id = ?");
$stmt->execute([$user['id']]);

// Generate new token
$token = bin2hex(random_bytes(32));
$expires = date('Y-m-d H:i:s', strtotime('+30 days'));

$stmt = $pdo->prepare("INSERT INTO public_user_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
$stmt->execute([$user['id'], $token, $expires]);

sendSuccess([
    'token' => $token,
    'user_id' => $user['id'],
    'email' => $user['email'],
    'display_name' => $user['display_name']
], 'Login successful');
?>