<?php
session_start();
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/api/middleware/Auth.php';

use Middleware\Auth;

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$username = $_POST['usuario'] ?? '';
$password = $_POST['senha'] ?? '';
$capturedIp = $_POST['captured_ip'] ?? '';

if (empty($username) || empty($password)) {
    header('Location: index.php?error=empty');
    exit;
}

try {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE username = ? AND is_active = 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password_hash'])) {
        // Login success
        // Create session in DB
        $sessionId = bin2hex(random_bytes(32));
        $expiresAt = date('Y-m-d H:i:s', strtotime('+24 hours'));

        $stmt = $pdo->prepare("
            INSERT INTO admin_sessions (id, user_id, ip_address, user_agent, expires_at)
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $sessionId,
            $user['id'],
            $capturedIp ?: $_SERVER['REMOTE_ADDR'],
            $_SERVER['HTTP_USER_AGENT'] ?? '',
            $expiresAt
        ]);

        // Update last login
        $pdo->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?")->execute([$user['id']]);
        
        // Create PHP session
        Auth::createSession($user);
        
        header('Location: placeholder.php');
        exit;
    } else {
        header('Location: index.php?error=invalid');
        exit;
    }
} catch (Exception $e) {
    error_log("Login Error: " . $e->getMessage());
    header('Location: index.php?error=db');
    exit;
}
