<?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_once __DIR__ . '/db_config.php';

$conn = $conn;  // Already set by db_config.php
if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'DB connection error']);

$stmt = $conn->prepare("SELECT `password` FROM `login-t` WHERE `name` = ?");
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'DB prepare error']);
    exit;
}
$stmt->bind_param('s', $name);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows > 0) {
    $row = $res->fetch_assoc();
    $stored = $row['password'];
    // plain-text comparison (app stores plain text as per current setup)
    if ($password === $stored) {
        echo json_encode(['success' => true, 'redirect' => 'home.php']);
    } else {
        echo json_encode(['success' => false, 'message' => 'wrong_password']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'not_found']);
}

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