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

header('Content-Type: application/json');
$villager = requireVillagerToken($pdo);

try {
    $stmt = $pdo->prepare("SELECT status, paymentstatus FROM villager WHERE id = ? AND isdeleted = 0");
    $stmt->execute([$villager['id']]);
    $v = $stmt->fetch();

    if (!$v || $v['status'] !== 'approved' || $v['paymentstatus'] !== 'unpaid') {
        jsonOut(false, 'You are not eligible for a new payment order at this time');
    }

    // Reuse an existing unpaid order if one was already created (avoid duplicate Razorpay orders)
    $existingstmt = $pdo->prepare("SELECT razorpayorderid, amount FROM paymentorder
        WHERE villagerid = ? AND isdeleted = 0 AND status = 'created' ORDER BY id DESC LIMIT 1");
    $existingstmt->execute([$villager['id']]);
    $existing = $existingstmt->fetch();
    if ($existing) {
        jsonOut(true, 'Existing order retrieved', [
            'orderid' => $existing['razorpayorderid'],
            'amount' => (int)bcmul(moneyStr($existing['amount']), '100', 0),
            'currency' => 'INR',
            'keyid' => RAZORPAYKEYID,
        ]);
    }

    $fee = getSetting($pdo, 'registrationfee', '100.00');
    $receipt = 'DFP-' . $villager['id'] . '-' . time();

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

    $orderid = $result['order']['id'];

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

    logActivity($pdo, 'villager', $villager['id'], 'createpaymentorder', 'villager', $villager['id'], 'Order created via app: ' . $orderid);

    jsonOut(true, 'Payment order created', [
        'orderid' => $orderid,
        'amount' => (int)bcmul(moneyStr($fee), '100', 0),
        'currency' => 'INR',
        'keyid' => RAZORPAYKEYID,
    ]);
} catch (Exception $e) {
    logDebug('[api_createorder] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
