<?php
declare(strict_types=1);
/**
 * Login Processing API - FIXED REDIRECT VERSION
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';

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

// Enable debugging
error_log("=== LOGIN REQUEST START ===");
error_log("Request Time: " . date('Y-m-d H:i:s'));
error_log("IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
error_log("User Agent: " . ($_SERVER['HTTP_USER_AGENT'] ?? 'unknown'));

function dev_error(string $msg): array {
    if (defined('APP_ENV') && APP_ENV === 'development') {
        return ['success' => false, 'message' => $msg];
    }
    return ['success' => false, 'message' => 'Server error. Please try again.'];
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$email    = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = (string)($_POST['password'] ?? '');

error_log("Login attempt for email: " . ($email ?: 'empty'));

if (!$email || $password === '') {
    echo json_encode(['success' => false, 'message' => 'Email and password are required']);
    exit;
}

try {
    $pdo = Database::getInstance()->getConnection();

    $stmt = $pdo->prepare("
        SELECT u.*, un.name AS unit_name
        FROM users u
        LEFT JOIN units un ON u.unit_id = un.id
        WHERE u.email = ? AND u.status = 'active'
        LIMIT 1
    ");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || !isset($user['password']) || !password_verify($password, $user['password'])) {
        error_log("Login failed for email: $email - Invalid credentials");
        try {
            $log = $pdo->prepare("
                INSERT INTO activity_log (unit_id, created_by, type, label, description, ip_address)
                VALUES (?, ?, 'security', 'Failed login attempt', ?, ?)
            ");
            $log->execute([
                $user['unit_id'] ?? null,
                $user['id'] ?? null,
                "Failed login for email: $email",
                $_SERVER['REMOTE_ADDR'] ?? 'Unknown'
            ]);
        } catch (Throwable $ignored) {}
        echo json_encode(['success' => false, 'message' => 'Invalid email or password']);
        exit;
    }

    // DATABASE SESSION AUTHENTICATION
    $auth_token = bin2hex(random_bytes(32));
    
    $user_session_data = [
        'user_id' => $user['id'],
        'user_email' => $user['email'],
        'user_full_name' => $user['full_name'] ?? '',
        'user_role' => $user['role'] ?? 'user',
        'user_status' => $user['status'] ?? 'active',
        'unit_id' => $user['unit_id'] ?? null,
        'unit_name' => $user['unit_name'] ?? null,
        'login_time' => time(),
        'last_activity' => time()
    ];

    // Store session in database
    $sessionStmt = $pdo->prepare("
        INSERT INTO user_sessions (session_id, session_data, expires_at) 
        VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 2 HOUR))
    ");
    $sessionStmt->execute([$auth_token, json_encode($user_session_data)]);

    // DEBUG: Log session creation
    error_log("Session created for user ID: " . $user['id']);
    error_log("Auth token: $auth_token");

    // Set secure cookie with dynamic domain
    $current_domain = $_SERVER['HTTP_HOST'];
    // Remove 'www.' prefix if present
    if (strpos($current_domain, 'www.') === 0) {
        $current_domain = substr($current_domain, 4);
    }
    $cookie_domain = '.' . $current_domain;
    
    error_log("Setting cookie for domain: $cookie_domain");
    
    $cookie_set = setcookie('rcp_auth', $auth_token, [
        'expires' => time() + 7200,
        'path' => '/',
        'domain' => $cookie_domain,
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
    
    if (!$cookie_set) {
        error_log("WARNING: Cookie might not have been set properly");
    }

    // Log successful login
    try {
        $logStmt = $pdo->prepare("
            INSERT INTO activity_log (unit_id, created_by, type, label, ip_address, user_agent)
            VALUES (?, ?, 'login', 'User logged in', ?, ?)
        ");
        $logStmt->execute([
            $user['unit_id'] ?? null,
            $user['id'] ?? null,
            $_SERVER['REMOTE_ADDR'] ?? 'Unknown',
            $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
        ]);
    } catch (Throwable $ignored) {}

    // Calculate redirect URL
    $redirect_url = WEB_BASE . 'pages/dashboard.php';
    error_log("Redirect URL calculated: $redirect_url");
    
    // Immediate response
    echo json_encode([
        'success' => true,
        'message' => 'Login successful',
        'redirect_url' => $redirect_url,
        'debug' => [
            'cookie_set' => $cookie_set,
            'user_id' => $user['id'],
            'session_id' => $auth_token,
            'redirect_to' => $redirect_url,
            'cookie_domain' => $cookie_domain,
            'server_host' => $_SERVER['HTTP_HOST']
        ]
    ]);
    
    error_log("=== LOGIN SUCCESSFUL ===");
    exit;

} catch (Throwable $t) {
    error_log("Login error: " . $t->getMessage() . " at " . $t->getFile() . ":" . $t->getLine());
    echo json_encode(dev_error("Login exception: " . $t->getMessage()));
    exit;
}
?>