<?php
/**
 * locker_profit_pay.php — লকারকে ভাড়া/লাভ পেমেন্ট
 * - cash_transactions এ OUT entry (category: LOCKER_PROFIT_SHARE)
 * - locker_profit_payments এ record
 * - locker_investors এ total_profit_paid আপডেট
 */

header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../_finance.php';

function send($ok, $msg, $data = [], $code = 200) {
    http_response_code($code);
    echo json_encode(['success' => $ok, 'message' => $msg, 'data' => $data],
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (function_exists('session_start_if_not_started')) session_start_if_not_started();
if (function_exists('is_logged_in') && !is_logged_in()) send(false, 'লগইন প্রয়োজন', [], 401);

try {
    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') send(false, 'Invalid method', [], 405);
    $in = json_decode(file_get_contents('php://input'), true);
    if (!is_array($in)) send(false, 'Invalid JSON', [], 400);

    $locker_party_id = (int)($in['locker_party_id'] ?? 0);
    $payment_date    = trim((string)($in['payment_date'] ?? ''));
    $amount          = round((float)($in['amount'] ?? 0), 2);
    $cash_account_id = (int)($in['cash_account_id'] ?? 0);
    $note            = trim((string)($in['note'] ?? ''));

    if ($locker_party_id <= 0) send(false, 'Locker পার্টি দিন', [], 422);
    if ($payment_date === '')  send(false, 'তারিখ দিন', [], 422);
    if ($amount <= 0)           send(false, 'টাকার পরিমাণ দিন', [], 422);
    if ($cash_account_id <= 0)  send(false, 'Cash account select করুন', [], 422);

    $pdo->beginTransaction();

    $ca = $pdo->prepare('SELECT id, account_name FROM cash_accounts WHERE id=? AND is_active=1 LIMIT 1');
    $ca->execute([$cash_account_id]);
    $acc = $ca->fetch(PDO::FETCH_ASSOC);
    if (!$acc) send(false, 'Cash account পাওয়া যায়নি', [], 404);

    // locker name (note এর জন্য)
    $hasPartyId = gs_column_exists($pdo, 'lockers', 'party_id');
    $whereCol = $hasPartyId ? 'party_id' : 'id';
    $ln = $pdo->prepare("SELECT name FROM lockers WHERE {$whereCol} = ? LIMIT 1");
    $ln->execute([$locker_party_id]);
    $locker_name = (string)($ln->fetchColumn() ?: ('লকার #' . $locker_party_id));

    $cash_note = 'লকার ভাড়া/লাভ পরিশোধ - ' . $locker_name;
    if ($note !== '') $cash_note .= ' | ' . $note;

    $txnId = gs_insert_cash_transaction($pdo, [
        'transaction_date' => $payment_date,
        'cash_account_id'  => $cash_account_id,
        'category_code'    => 'LOCKER_PROFIT_SHARE',
        'amount'           => $amount,
        'note'             => $cash_note,
        'reference_type'   => 'LOCKER_PROFIT_PAYMENT',
        'reference_id'     => $locker_party_id,
        'party_id'         => $locker_party_id
    ]);

    gs_recalc_cash_account($pdo, $cash_account_id);

    $lpp = $pdo->prepare("
        INSERT INTO locker_profit_payments
            (locker_party_id, payment_date, amount, cash_account_id, cash_transaction_id, note, created_by)
        VALUES (?,?,?,?,?,?,?)
    ");
    $lpp->execute([
        $locker_party_id, $payment_date, $amount, $cash_account_id, $txnId, $note,
        $_SESSION['user_id'] ?? null
    ]);

    // locker_investors আপডেট (যদি row থাকে)
    if (gs_table_exists($pdo, 'locker_investors')) {
        $upd = $pdo->prepare("
            UPDATE locker_investors
            SET total_profit_paid = total_profit_paid + ?,
                last_transaction_date = ?
            WHERE party_id = ?
        ");
        $upd->execute([$amount, $payment_date, $locker_party_id]);
    }

    $pdo->commit();

    send(true, 'পেমেন্ট সফল হয়েছে', [
        'locker_party_id' => $locker_party_id,
        'amount'          => $amount,
        'cash_account'    => $acc['account_name'],
        'cash_txn_id'     => $txnId
    ]);

} catch (Throwable $e) {
    if ($pdo instanceof PDO && $pdo->inTransaction()) $pdo->rollBack();
    send(false, 'Server error: ' . $e->getMessage(), [], 500);
}