<?php
session_start();
require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $accessCode = trim($_POST['access_code']);
    
    if (empty($accessCode)) {
        header('Location: member.php?error=empty');
        exit();
    }
    
    if (!preg_match('/^[0-9]+$/', $accessCode)) {
        header('Location: member.php?error=invalid');
        exit();
    }
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE code = :code LIMIT 1");
        $stmt->bindParam(':code', $accessCode);
        $stmt->execute();
        
        $user = $stmt->fetch();
        
        if ($user) {
            $_SESSION['user_logged_in'] = true;
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_code'] = $user['code'];
            $_SESSION['login_time'] = time();
            
            header('Location: dashboard.php');
            exit();
        } else {
            header('Location: member.php?error=invalid');
            exit();
        }
        
    } catch (PDOException $e) {
        error_log("Login error: " . $e->getMessage());
        header('Location: member.php?error=invalid');
        exit();
    }
    
} else {
    header('Location: member.php');
    exit();
}
?>