<?php
/**
 * API: Login
 * Authenticate user and return API token
 * Method: POST
 */

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

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

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Get input data
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

$username = $input['username'] ?? '';
$password = $input['password'] ?? '';

if (empty($username) || empty($password)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Username and password required']);
    exit;
}

$pdo = getDB();

// Find user
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? OR email = ? LIMIT 1");
$stmt->execute([$username, $username]);
$user = $stmt->fetch();

if (!$user || !password_verify($password, $user['password_hash'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Invalid credentials']);
    exit;
}

if (!$user['is_active']) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Account is deactivated']);
    exit;
}

// Generate API key if not exists
if (empty($user['api_key'])) {
    $apiKey = 'hom_' . bin2hex(random_bytes(32));
    $stmt = $pdo->prepare("UPDATE users SET api_key = ? WHERE id = ?");
    $stmt->execute([$apiKey, $user['id']]);
    $user['api_key'] = $apiKey;
}

// Generate session token (JWT-like simple token)
$sessionToken = bin2hex(random_bytes(64));
$expiresAt = date('Y-m-d H:i:s', strtotime('+30 days'));

// Store session token
$stmt = $pdo->prepare("INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent) 
                      VALUES (?, ?, ?, ?, ?)");
$stmt->execute([
    $user['id'], 
    $sessionToken, 
    $expiresAt,
    $_SERVER['REMOTE_ADDR'] ?? '',
    $_SERVER['HTTP_USER_AGENT'] ?? ''
]);

// Update last login
$stmt = $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
$stmt->execute([$user['id']]);

echo json_encode([
    'success' => true,
    'data' => [
        'user_id' => $user['id'],
        'username' => $user['username'],
        'full_name' => $user['full_name'],
        'email' => $user['email'],
        'role' => $user['role'],
        'api_key' => $user['api_key'],
        'session_token' => $sessionToken,
        'expires_at' => $expiresAt
    ]
]);
?>