<?php
// api/auth.php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

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

    if (empty($username) || empty($password)) {
        redirect('../index.php?page=login&error=Please fill in all fields');
    }

    // Prepare SQL to fetch user
    // We check both username and email (if we mapped it, but for now `users` table only has `username`.
    // The plan said we'd look up linked member for email, but let's stick to username first to match existing data.
    // If we want email login, we need to JOIN members or check if username matches logic.
    // Let's modify query to checking username OR (users.member_id IS NOT NULL AND members.email = ?)
    
    // Simplest: Check username column first.
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? LIMIT 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    // If not found by username, try finding by email in members table linked to user
    if (!$user) {
         // Query: Find user where linked member has this email
         $stmt = $pdo->prepare("
            SELECT u.* 
            FROM users u 
            JOIN members m ON u.member_id = m.id 
            WHERE m.email = ? 
            LIMIT 1
         ");
         $stmt->execute([$username]);
         $user = $stmt->fetch();
    }

    if ($user && password_verify($password, $user['password_hash'])) {
        // Login Success
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['user_role'] = $user['role'];
        $_SESSION['member_id'] = $user['member_id'] ?? null; // Store linked member ID if any
        
        logActivity($user['id'], 'LOGIN', 'User logged in');

        redirect('../index.php?page=dashboard');
    } else {
        // Login Failed
        redirect('../index.php?page=login&error=Invalid credentials');
    }
} else {
    redirect('../index.php?page=login');
}
