<?php

/**
 * Admin Login API
 * Endpoint: /admin/adminapi/login.php
 * 
 * Returns a session token on successful login.
 * Token must be sent with all subsequent API requests.
 * Token expires after 30 minutes of inactivity.
 * 
 * Supports both hashed and legacy plaintext passwords (auto-migrates to hashed).
 */

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/activity_logger.php';

header('Content-Type: application/json');

// Rate limiting: simple IP-based (5 attempts per minute)
$rateLimitFile = sys_get_temp_dir() . '/admin_login_' . md5($_SERVER['REMOTE_ADDR'] ?? 'unknown') . '.json';
$maxAttempts = 5;
$windowSeconds = 60;

if (file_exists($rateLimitFile)) {
    $rateData = json_decode(file_get_contents($rateLimitFile), true);
    if ($rateData && isset($rateData['count']) && isset($rateData['first_attempt'])) {
        if ((time() - $rateData['first_attempt']) < $windowSeconds) {
            if ($rateData['count'] >= $maxAttempts) {
                http_response_code(429);
                echo json_encode(['success' => false, 'message' => 'Too many login attempts. Try again later.']);
                exit;
            }
        } else {
            // Window expired, reset
            $rateData = ['count' => 0, 'first_attempt' => time()];
        }
    }
} else {
    $rateData = ['count' => 0, 'first_attempt' => time()];
}

$email = 'admin@admin.com';  // Hardcoded - always same
$password = $_POST['password'] ?? '';
$deviceName = $_POST['device_name'] ?? '';    // Phone model e.g. "Samsung Galaxy S23"

if ($password === '') {
    echo json_encode(['success' => false, 'message' => 'Password required']);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT id, email, password, expiry_date FROM admin WHERE email = ? LIMIT 1");
    $stmt->execute([$email]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$admin) {
        // Increment rate limit
        $rateData['count']++;
        @file_put_contents($rateLimitFile, json_encode($rateData), LOCK_EX);
        
        // Log failed attempt
        logLoginFailed($email, 'Account not found');
        
        sleep(1); // Slow down brute force
        echo json_encode(['success' => false, 'message' => 'Invalid credentials']);
        exit;
    }

    // Check expiry
    $expiry = $admin['expiry_date'] ?? null;
    if ($expiry && strtotime($expiry) < time()) {
        echo json_encode(['success' => false, 'message' => 'Admin access expired', 'expired' => true]);
        exit;
    }

    // Password verification - plaintext comparison
    $passwordValid = ($password === $admin['password']);

    if (!$passwordValid) {
        // Increment rate limit
        $rateData['count']++;
        @file_put_contents($rateLimitFile, json_encode($rateData), LOCK_EX);
        
        // Log failed attempt
        logLoginFailed($email, 'Wrong password');
        
        sleep(1); // Slow down brute force
        echo json_encode(['success' => false, 'message' => 'Invalid credentials']);
        exit;
    }

    // Login successful - reset rate limit
    @unlink($rateLimitFile);

    // Generate auth token (with device name)
    $token = generateAuthToken($admin['id'], $deviceName);

    // Log successful login (with device name)
    logLogin($admin['id'], $admin['email'], $deviceName);

    // Return response (same format as before + token)
    echo json_encode([
        'success' => true,
        'status' => true,
        'message' => 'Login successful',
        'token' => $token,
        'token_expiry_minutes' => TOKEN_EXPIRY_SECONDS / 60,
        'admin' => [
            'id' => $admin['id'],
            'email' => $admin['email'],
            'expiry_date' => $admin['expiry_date'] ?? null
        ]
    ]);

} catch (Exception $e) {
    error_log("Login error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Server error']);
}
