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

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

try {
    if ($action === 'list') {
        $rows = $pdo->query("SELECT id, name, code, isdeleted FROM panchayat ORDER BY name")->fetchAll();
        jsonOut(true, '', $rows);
    }

    if ($action === 'listall') {
        $rows = $pdo->query("SELECT id, name FROM panchayat WHERE isdeleted = 0 ORDER BY name")->fetchAll();
        jsonOut(true, '', $rows);
    }

    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $name = cleanInput($_POST['name'] ?? '');
        $code = strtoupper(cleanInput($_POST['code'] ?? ''));

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

        if ($id > 0) {
            $stmt = $pdo->prepare("UPDATE panchayat SET name = ?, code = ? WHERE id = ?");
            $stmt->execute([$name, $code, $id]);
            logActivity($pdo, 'panchayat', $id, 'update', 'admin', currentUserId(), 'Panchayat updated');
            jsonOut(true, 'Panchayat updated successfully');
        } else {
            $stmt = $pdo->prepare("INSERT INTO panchayat (name, code) VALUES (?, ?)");
            $stmt->execute([$name, $code]);
            $newid = $pdo->lastInsertId();
            logActivity($pdo, 'panchayat', $newid, 'create', 'admin', currentUserId(), 'Panchayat created');
            jsonOut(true, 'Panchayat added successfully');
        }
    }

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

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

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

        if ($name === '' || $username === '' || $phone === '' || $panchayatid <= 0) {
            jsonOut(false, 'All fields are required');
        }

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

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

    jsonOut(false, 'Invalid action');
} catch (PDOException $e) {
    logDebug('[ajax_admin_panchayat] ' . $e->getMessage());
    if ($e->getCode() == 23000) {
        jsonOut(false, 'Duplicate value - code/username must be unique');
    }
    jsonOut(false, 'Something went wrong. Please try again.');
}
