<?php
session_start();
require_once("../config/db.php");

$username = trim($_POST['username'] ?? '');
$password = trim($_POST['password'] ?? '');

if ($username === '' || $password === '') {
    header("Location: ../login.php?error=Missing fields");
    exit;
}

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

if (!$user) {
    header("Location: ../login.php?error=Invalid username or password");
    exit;
}

if (!password_verify($password, $user['password'])) {
    header("Location: ../login.php?error=Invalid username or password");
    exit;
}

// SUCCESS
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role'];

header("Location: ../index.php");
exit;
