<?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 = $data['email'] ?? '';
$password = $data['password'] ?? '';

$stmt = $pdo->prepare("SELECT id, email, password, status FROM 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', 403);
}

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

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

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

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