<?php
require 'db.php';
require 'functions.php';

$username = cleanInput($_POST['username'] ?? '');
$password = cleanInput($_POST['password'] ?? '');
$redirect = basename($_POST['redirect'] ?? '');

if ($username === '' || $password === '') {
    jsonOut(false, 'Username and password are required');
}

try {
    $stmt = $pdo->prepare("SELECT id, name, username, password, panchayatid FROM panchayatuser
        WHERE username = ? AND isactive = 1 AND isdeleted = 0");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if (!$user || !verifyPassword($password, $user['password'])) {
        jsonOut(false, 'Invalid username or password');
    }

    $_SESSION['userid'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['name'] = $user['name'];
    $_SESSION['role'] = 'panchayatuser';
    $_SESSION['panchayatid'] = $user['panchayatid'];

    logActivity($pdo, 'panchayatuser', $user['id'], 'login', 'panchayatuser', $user['id'], 'Panchayat user logged in');

    jsonOut(true, 'Login successful', ['redirect' => $redirect !== '' ? $redirect : 'panchayat_dashboard.php']);
} catch (Exception $e) {
    logDebug('[ajax_panchayat_login] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
