<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$password = isset($_POST['password']) ? trim($_POST['password']) : '';

if ($name === '' || $password === '') {
    echo json_encode(['success' => false, 'message' => 'Please provide name and password']);
    exit;
}

require __DIR__ . '/db_config.php';

$stmt = $conn->prepare("SELECT `id`,`username`,`email`,`password_hash` FROM `users` WHERE `username` = ? OR `email` = ? LIMIT 1");
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'DB prepare error']);
    exit;
}
$stmt->bind_param('ss', $name, $name);
$stmt->execute();
$res = $stmt->get_result();

if ($res && $res->num_rows > 0) {
    $row = $res->fetch_assoc();
    $stored = $row['password_hash'];
    // If configured for plaintext storage, compare directly; else use password_verify
    $usePlain = (isset($STORE_PLAINTEXT_PASSWORDS) && $STORE_PLAINTEXT_PASSWORDS === true);
    $ok = false;
    if ($usePlain) {
        $ok = hash_equals((string)$stored, (string)$password);
    } else {
        $ok = password_verify($password, $stored);
    }
    if ($ok) {
        session_start();
        $_SESSION['user_id'] = $row['id'];
        $_SESSION['username'] = $row['username'];
        // check admin table
        $isAdmin = false;
        $adminStmt = $conn->prepare("SELECT id, role_name FROM admins WHERE user_id = ? LIMIT 1");
        if ($adminStmt) {
            $adminStmt->bind_param('i', $row['id']);
            $adminStmt->execute();
            $ares = $adminStmt->get_result();
            if ($ares && $ares->num_rows > 0) {
                $aRow = $ares->fetch_assoc();
                $isAdmin = true;
                $_SESSION['is_admin'] = true;
                $_SESSION['admin_role'] = $aRow['role_name'];
            }
            $adminStmt->close();
        }

        echo json_encode(['success' => true, 'is_admin' => $isAdmin, 'redirect' => 'dashboard.php']);
    } else {
        echo json_encode(['success' => false, 'message' => 'wrong_password']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'not_found']);
}

$stmt->close();
$conn->close();
