<?php
// process_login.php
session_start();
require_once 'config.php';
require_once 'includes/auth.php';
require_once 'classes/User.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if (empty($username) || empty($password)) {
        set_message("Username and password are required.", "danger");
        header("Location: index.php");
        exit();
    }

    $user_manager = new User($pdo);
    $user = $user_manager->authenticateUser($username, $password);

    if ($user) {
        // Login successful
        // Regenerate session ID to prevent session fixation attacks
        session_regenerate_id(true);

        $_SESSION['user_id'] = $user['pkisu_id'];
        $_SESSION['person_id'] = $user['fkisp_id_of'];
        $_SESSION['username'] = $user['isu_name'];
        $_SESSION['user_status'] = $user['isu_status']; // DAC Staff, Data Owner, Data User
        $_SESSION['can_run_r'] = !empty($user['isu_can_run_r']);

        set_message("Welcome back, " . htmlspecialchars($user['isu_name']) . "!", "success");

        if (!empty($_SESSION['oauth_pending_request']) && is_array($_SESSION['oauth_pending_request'])) {
            $pending = $_SESSION['oauth_pending_request'];
            $createdAt = isset($pending['created_at']) ? (int) $pending['created_at'] : 0;
            if ($createdAt && (time() - $createdAt) <= 600 && !empty($pending['params']) && is_array($pending['params'])) {
                $query = http_build_query($pending['params']);
                unset($_SESSION['oauth_pending_request']);
                header("Location: oauth/authorize.php?" . $query);
                exit();
            }
            unset($_SESSION['oauth_pending_request']);
        }

        // Redirect to appropriate dashboard based on role
        switch ($user['isu_status']) {
            case 'DAC Staff':
                header("Location: admin/dashboard.php");
                break;
            case 'Data Contributor':
                header("Location: data_hybrid/dashboard.php");
                break;    
            case 'Data Owner':
                header("Location: data_owner/dashboard.php");
                break;
            case 'Data User':
                header("Location: data_user/dashboard.php");
                break;
            default:
                header("Location: index.php");
                break;
        }
        exit();
    } else {
        // Login failed
        set_message("Invalid username or password.", "danger");
        header("Location: index.php");
        exit();
    }
} else {
    // Not a POST request, redirect to home
    header("Location: index.php");
    exit();
}
?>
