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

header('Content-Type: application/json');

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

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

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

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

    $token = checkerIssueToken($pdo, $checker['id']);
    logActivity($pdo, 'ticketchecker', $checker['id'], 'login', 'ticketchecker', $checker['id'], 'Checker logged in via app');

    jsonOut(true, 'Login successful', [
        'apitoken' => $token,
        'checkerid' => (int)$checker['id'],
        'name' => $checker['name'],
    ]);
} catch (Exception $e) {
    logDebug('[api_checkerlogin] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
