<?php
session_start();
require 'db/config.php';

function loginWorker($userId) {
    $db = db();
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ? AND role = 'worker'");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    if ($user) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['role'] = 'worker';
        return true;
    }
    return false;
}

function loginAdmin($userId, $pin) {
    $db = db();
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ? AND role = 'admin'");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    if ($user) {
        // If no PIN set, allow setup (bootstrap mode)
        if ($user['pin_hash'] === null) {
            // This is special case, first time login
            $_SESSION['pending_setup_user_id'] = $user['id'];
            return 'setup';
        }
        
        if (password_verify($pin, $user['pin_hash'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['role'] = 'admin';
            return true;
        }
    }
    return false;
}

function setupAdminPin($userId, $pin) {
    $db = db();
    $hash = password_hash($pin, PASSWORD_BCRYPT);
    $stmt = $db->prepare("UPDATE users SET pin_hash = ? WHERE id = ? AND role = 'admin'");
    return $stmt->execute([$hash, $userId]);
}

// Check POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'login_worker') {
        if (loginWorker($_POST['user_id'])) {
            header('Location: dashboard.php');
            exit;
        }
    } elseif ($action === 'login_admin') {
        $res = loginAdmin($_POST['user_id'], $_POST['pin']);
        if ($res === true) {
            header('Location: dashboard.php');
            exit;
        } elseif ($res === 'setup') {
            header('Location: index.php?setup=1');
            exit;
        }
    } elseif ($action === 'setup_pin') {
        $userId = $_SESSION['pending_setup_user_id'] ?? null;
        if ($userId && !empty($_POST['pin'])) {
            if (setupAdminPin($userId, $_POST['pin'])) {
                unset($_SESSION['pending_setup_user_id']);
                // Auto login after setup
                $db = db();
                $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
                $stmt->execute([$userId]);
                $user = $stmt->fetch();
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_name'] = $user['name'];
                $_SESSION['role'] = 'admin';
                header('Location: dashboard.php');
                exit;
            }
        }
    }
    
    header('Location: index.php?error=1');
    exit;
}
