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

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

    try {
        // Ambil user berdasarkan username
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        // CEK PASSWORD (Tanpa Hash - Sementara agar Anda bisa masuk)
        if ($user && $password === $user['password']) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];

            // Arahkan sesuai Role 
            if ($user['role'] === 'admin') {
                header("Location: ../modules/admin/dashboard.php");
            } else {
                header("Location: ../modules/staff/production_input.php");
            }
            exit();
        } else {
            // Jika salah, balik ke login dengan pesan error
            header("Location: ../index.php?error=1");
            exit();
        }
    } catch (PDOException $e) {
        die("Koneksi Error: " . $e->getMessage());
    }
}