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

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

function buildPayLink($orderid) {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    return $scheme . '://' . $host . '/payment_pay.php?order=' . urlencode($orderid);
}

try {
    if ($action === 'list') {
        $rows = $pdo->query("SELECT po.id, po.razorpayorderid, po.razorpaypaymentid, po.amount, po.status,
            po.createdbytype, po.createdat, po.paidat, v.fullname
            FROM paymentorder po JOIN villager v ON v.id = po.villagerid
            WHERE po.isdeleted = 0 ORDER BY po.id DESC")->fetchAll();
        foreach ($rows as &$r) {
            $r['amountformatted'] = formatINR($r['amount']);
        }
        jsonOut(true, '', $rows);
    }

    if ($action === 'listunpaid') {
        $rows = $pdo->query("SELECT id, fullname, phone FROM villager
            WHERE isdeleted = 0 AND status = 'approved' AND paymentstatus = 'unpaid' ORDER BY fullname")->fetchAll();
        jsonOut(true, '', $rows);
    }

    if ($action === 'createorder') {
        $villagerid = (int)($_POST['villagerid'] ?? 0);
        if ($villagerid <= 0) {
            jsonOut(false, 'Please select a villager');
        }

        $stmt = $pdo->prepare("SELECT id, fullname, phone, status, paymentstatus FROM villager WHERE id = ? AND isdeleted = 0");
        $stmt->execute([$villagerid]);
        $villager = $stmt->fetch();

        if (!$villager || $villager['status'] !== 'approved' || $villager['paymentstatus'] !== 'unpaid') {
            jsonOut(false, 'Villager is not eligible for a new payment order');
        }

        $fee = getSetting($pdo, 'registrationfee', '100.00');
        $receipt = 'DFP-' . $villagerid . '-' . time();

        $result = razorpayCreateOrder($fee, $receipt, ['villagerid' => $villagerid]);
        if (!$result['success']) {
            jsonOut(false, $result['message']);
        }

        $orderid = $result['order']['id'];
        $paylink = buildPayLink($orderid);

        $ins = $pdo->prepare("INSERT INTO paymentorder (villagerid, razorpayorderid, amount, currency, status, createdbytype, createdbyid, paylink)
            VALUES (?, ?, ?, 'INR', 'created', 'admin', ?, ?)");
        $ins->execute([$villagerid, $orderid, moneyStr($fee), currentUserId(), $paylink]);

        logActivity($pdo, 'villager', $villagerid, 'createpaymentorder', 'admin', currentUserId(), 'Manual payment order created: ' . $orderid);

        jsonOut(true, 'Payment order created successfully', ['orderid' => $orderid, 'paylink' => $paylink]);
    }

    if ($action === 'sendlink') {
        $villagerid = (int)($_POST['villagerid'] ?? 0);
        $via = cleanInput($_POST['via'] ?? '');

        $stmt = $pdo->prepare("SELECT v.phone, po.paylink FROM villager v
            JOIN paymentorder po ON po.villagerid = v.id
            WHERE v.id = ? AND po.isdeleted = 0 ORDER BY po.id DESC LIMIT 1");
        $stmt->execute([$villagerid]);
        $row = $stmt->fetch();

        if (!$row) {
            jsonOut(false, 'No payment order found for this villager');
        }

        $message = "Complete your Divar Ferry Pass payment here: " . $row['paylink'];
        if ($via === 'whatsapp') {
            sendWhatsapp($pdo, $row['phone'], $message, 'paymentlink');
        } else {
            sendSms($pdo, $row['phone'], $message, 'paymentlink');
        }

        jsonOut(true, 'Payment link sent successfully (stub - see logs table)');
    }

    jsonOut(false, 'Invalid action');
} catch (Exception $e) {
    logDebug('[ajax_admin_payment] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
