<?php
require 'db.php';
require 'functions.php';
requireRole(['admin']);

$action = cleanInput($_POST['action'] ?? $_GET['action'] ?? '');

try {
    if ($action === 'list') {
        $rows = $pdo->query("SELECT tc.id, tc.name, tc.phone, tc.username, tc.panchayatid, tc.isactive, p.name AS panchayatname
            FROM ticketchecker tc LEFT JOIN panchayat p ON p.id = tc.panchayatid
            WHERE tc.isdeleted = 0 ORDER BY tc.name")->fetchAll();
        jsonOut(true, '', $rows);
    }

    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $name = cleanInput($_POST['name'] ?? '');
        $phone = cleanInput($_POST['phone'] ?? '');
        $username = cleanInput($_POST['username'] ?? '');
        $panchayatid = cleanInput($_POST['panchayatid'] ?? '');
        $panchayatid = $panchayatid === '' ? null : (int)$panchayatid;
        $password = cleanInput($_POST['password'] ?? '');

        if ($name === '' || $phone === '' || $username === '') {
            jsonOut(false, 'Name, phone and username are required');
        }

        if ($id > 0) {
            if ($password !== '') {
                $stmt = $pdo->prepare("UPDATE ticketchecker SET name=?, phone=?, username=?, panchayatid=?, password=? WHERE id=?");
                $stmt->execute([$name, $phone, $username, $panchayatid, hashPassword($password), $id]);
            } else {
                $stmt = $pdo->prepare("UPDATE ticketchecker SET name=?, phone=?, username=?, panchayatid=? WHERE id=?");
                $stmt->execute([$name, $phone, $username, $panchayatid, $id]);
            }
            logActivity($pdo, 'ticketchecker', $id, 'update', 'admin', currentUserId(), 'Checker updated');
            jsonOut(true, 'Checker updated successfully');
        } else {
            if ($password === '') {
                jsonOut(false, 'Password is required for a new checker');
            }
            $stmt = $pdo->prepare("INSERT INTO ticketchecker (name, phone, username, panchayatid, password) VALUES (?,?,?,?,?)");
            $stmt->execute([$name, $phone, $username, $panchayatid, hashPassword($password)]);
            $newid = $pdo->lastInsertId();
            logActivity($pdo, 'ticketchecker', $newid, 'create', 'admin', currentUserId(), 'Checker created');
            jsonOut(true, 'Checker added successfully');
        }
    }

    if ($action === 'togglestatus') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $pdo->prepare("UPDATE ticketchecker SET isactive = 1 - isactive WHERE id = ?");
        $stmt->execute([$id]);
        logActivity($pdo, 'ticketchecker', $id, 'togglestatus', 'admin', currentUserId(), 'Checker status toggled');
        jsonOut(true, 'Status updated successfully');
    }

    jsonOut(false, 'Invalid action');
} catch (PDOException $e) {
    logDebug('[ajax_admin_ticketchecker] ' . $e->getMessage());
    if ($e->getCode() == 23000) {
        jsonOut(false, 'Phone number already exists');
    }
    jsonOut(false, 'Something went wrong. Please try again.');
}
