<?php
require_once '../config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST method allowed', null, 405);
}

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    $input = $_POST;
}

$email_username = sanitizeInput($input['email_username'] ?? '');
$password = $input['password'] ?? '';

if (empty($email_username) || empty($password)) {
    sendResponse(false, 'Email/Username and password are required', null, 400);
}

try {
    // Check user by email or username
    $stmt = $conn->prepare("SELECT id, name, email, password, api_token FROM users WHERE email=? OR name=? LIMIT 1");
    $stmt->bind_param("ss", $email_username, $email_username);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($user = $result->fetch_assoc()) {
        if (password_verify($password, $user['password'])) {
            // Generate new token if not exists
            if (empty($user['api_token'])) {
                $newToken = generateToken();
                $updateStmt = $conn->prepare("UPDATE users SET api_token = ? WHERE id = ?");
                $updateStmt->bind_param("si", $newToken, $user['id']);
                $updateStmt->execute();
                $user['api_token'] = $newToken;
            }
            
            // Remove password from response
            unset($user['password']);
            
            sendResponse(true, 'Login successful', [
                'user' => $user,
                'token' => $user['api_token']
            ]);
        } else {
            sendResponse(false, 'Invalid password', null, 401);
        }
    } else {
        sendResponse(false, 'User not found', null, 404);
    }
    
    $stmt->close();
} catch (Exception $e) {
    sendResponse(false, 'Login failed: ' . $e->getMessage(), null, 500);
}
?>
