<?php
// File: login.php (CORRECTED VERSION)

// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Only proceed with login logic for POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once __DIR__ . '/db.php';

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

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

    if (empty($identifier) || empty($password)) {
        echo json_encode(['success' => false, 'message' => 'Missing fields']);
        exit;
    }

    try {
        // --- MODIFICATION 1: ADD 'status', 'region', AND 'department' TO THE SELECT QUERY ---
        // We now select all fields necessary for both the session and the frontend response.
        $stmt = $pdo->prepare('SELECT id, username, email, password, role, status, region, department FROM users WHERE username = :username_id OR email = :email_id LIMIT 1');
        $stmt->execute([
            'username_id' => $identifier,
            'email_id' => $identifier
        ]);

        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        // Check if the user exists and the password is correct
        if (!$user || !password_verify($password, $user['password'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid credentials']);
            exit;
        }

        // --- MODIFICATION 2: CHECK THE USER'S STATUS ---
        if ($user['status'] === 'inactive') {
            echo json_encode(['success' => false, 'message' => 'Your account is inactive. Please contact support.']);
            exit;
        }

        // Valid and active user: set session variables
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['user_role'] = $user['role'];
        // --- MODIFICATION 3: STORE REGION AND DEPARTMENT IN THE SESSION ---
        // This is the key change that enables manage_users.php to work.
        if (!empty($user['region'])) {
            $_SESSION['user_region'] = $user['region'];
        }
        if (!empty($user['department'])) {
            $_SESSION['user_department'] = $user['department'];
        }

        $cookie_params = session_get_cookie_params();
        setcookie('auth_token', 'true', [
            // 30 days expiration
            // 'expires' => time() + (86400 * 30),
            'expires' => time() + 86400, // 1 day (86400 seconds)
            'path' => '/',
            'secure' => $cookie_params['secure'],
            'httponly' => $cookie_params['httponly'],
            'samesite' => 'Lax'
        ]);

        // Return user data including role, status, region, and department to the frontend
        $user_data_for_frontend = [
            'id' => $user['id'],
            'username' => $user['username'],
            'email' => $user['email'],
            'role' => $user['role'],
            'status' => $user['status']
        ];
        
        // --- MODIFICATION 4: INCLUDE REGION AND DEPARTMENT IN THE FRONTEND RESPONSE ---
        // Your frontend is already expecting this, as per your console.log.
        if (!empty($user['region'])) {
            $user_data_for_frontend['region'] = $user['region'];
        }
        if (!empty($user['department'])) {
            $user_data_for_frontend['department'] = $user['department'];
        }

        echo json_encode([
            'success' => true,
            'message' => 'Login successful',
            'user' => $user_data_for_frontend
        ]);
        exit;
    } catch (PDOException $e) {
        error_log("PDO Error during login query: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Server error: Database query issue. (' . $e->getMessage() . ')']);
        exit;
    } catch (Throwable $e) {
        error_log("Unhandled Error in login.php: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Server error: An unexpected error occurred. (' . $e->getMessage() . ')']);
        exit;
    }

} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Only POST requests are allowed for login.']);
    exit;
}
?>