<?php
session_start();
require_once __DIR__ . '/config/app.php';
define('BASE_URL', APP_URL);
include_once "api/AUTh/check_user.php";

$username = isset($_POST["username"]) ? htmlspecialchars($_POST["username"]) : '';
$password = isset($_POST["password"]) ? $_POST["password"] : '';

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

include_once "api/AUTh/check_user.php";
if ($existing_user == "false") {
    header("Location: " . BASE_URL . "login.php?error=invalid&username=" . urlencode($username));
    exit;
} else {
    date_default_timezone_set('Asia/Bangkok'); 
    $_SESSION['user'] = $user->username;
    $_SESSION['staff_id'] = $staff_id;
    $_SESSION['userrole_id'] = $userrole_id;
    $_SESSION['user_rn_siamarch39'] = rand(10000, 100000);
    $_SESSION['profilepicture'] = $profilepicture;
    $_SESSION['userid'] = $userid;
    $_SESSION['start'] = time(); 
    $_SESSION['expire'] = $_SESSION['start'] + (180 * 60 * 18); 

    // Redirect based on user role
    if ($userrole_id == "investor_share") {
        $_SESSION['investor_access'] = true; // Mark investor-specific session
        header("location:" . BASE_URL . "index_share.php");
        exit;
    } else if($userrole_id == 7) {
        $_SESSION['attendance_access'] = true; // Non-investor session
        header("location:" . BASE_URL . "index_attendance.php");
        exit;
    } else {
        $_SESSION['index_access'] = true; // Non-investor session
        header("location:" . BASE_URL . "index.php");
        exit;
    }
}
?>
