<?php
/**
 * File: api/karigar/pay_labor.php
 * Purpose: Karigar কে labor payment — cash account থেকে কেটে ledger এ entry
 * Method : POST
 * Input  : { karigar_party_id, payment_date, cash_account_id, amount, note }
 * Side-effects:
 *   1) karigar_ledger INSERT (LABOR_PAYMENT)
 *   2) cash_transactions INSERT (OUT, reference=karigar_payment)
 *   3) cash_accounts.current_balance UPDATE
 *   4) audit_log
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';

function out_json($code, $success, $message, $data = null) {
    http_response_code($code);
    echo json_encode([
        'success' => (bool)$success,
        'status'  => (bool)$success,
        'message' => $message,
        'data'    => $data
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (function_exists('is_logged_in') && !is_logged_in()) {
    out_json(401, false, 'লগইন প্রয়োজন', null);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    out_json(405, false, 'শুধু POST অনুরোধ গ্রহণযোগ্য', null);
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    out_json(500, false, 'Database connection পাওয়া যায়নি', null);
}

$raw  = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data)) $data = $_POST;

$karigar_id      = (int)($data['karigar_party_id'] ?? 0);
$payment_date    = trim((string)($data['payment_date'] ?? date('Y-m-d')));
$cash_account_id = (int)($data['cash_account_id'] ?? 0);
$amount          = (float)($data['amount'] ?? 0);
$note            = trim((string)($data['note'] ?? ''));

if ($karigar_id <= 0)      out_json(400, false, 'Karigar select করুন', null);
if ($cash_account_id <= 0) out_json(400, false, 'Cash account select করুন', null);
if ($amount <= 0)          out_json(400, false, 'Amount ০-এর বেশি দিন', null);

try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // ===== Validate karigar =====
    $kc = $pdo->prepare("SELECT id, name, is_karigar, deleted_at FROM parties WHERE id = ? LIMIT 1");
    $kc->execute([$karigar_id]);
    $karigar = $kc->fetch(PDO::FETCH_ASSOC);

    if (!$karigar)                              out_json(404, false, 'Karigar পাওয়া যায়নি', null);
    if ((int)$karigar['is_karigar'] !== 1)      out_json(400, false, 'এই party karigar না', null);
    if ($karigar['deleted_at'] !== null)        out_json(400, false, 'Karigar deleted', null);

    // ===== Validate cash account =====
    $ca = $pdo->prepare("SELECT id, account_name, current_balance FROM cash_accounts WHERE id = ? LIMIT 1");
    $ca->execute([$cash_account_id]);
    $cash = $ca->fetch(PDO::FETCH_ASSOC);

    if (!$cash) out_json(404, false, 'Cash account পাওয়া যায়নি', null);

    // ===== Begin transaction =====
    $pdo->beginTransaction();

    $user_id = (int)($_SESSION['user_id'] ?? 0);
    $ip      = $_SERVER['REMOTE_ADDR'] ?? '';

    // 1) cash_transactions INSERT (OUT)
    // cash_transaction_types থেকে type_id খুঁজি (or fallback to 1)
    $tt = $pdo->prepare("SELECT id FROM cash_transaction_types
                         WHERE transaction_type='OUT' AND is_active=1
                         ORDER BY id ASC LIMIT 1");
    $tt->execute();
    $ttId = (int)($tt->fetchColumn() ?: 1);

    $ctIns = $pdo->prepare("
        INSERT INTO cash_transactions
            (transaction_date, cash_account_id, transaction_type_id, transaction_type,
             amount, description, reference_type, reference_id,
             is_reversal, created_at)
        VALUES
            (:dt, :acc, :ttid, 'OUT', :amt, :desc, 'KARIGAR_PAYMENT', :ref,
             0, NOW())
    ");
    $ctIns->execute([
        ':dt'   => $payment_date,
        ':acc'  => $cash_account_id,
        ':ttid' => $ttId,
        ':amt'  => $amount,
        ':desc' => 'Karigar labor payment — ' . $karigar['name'] . ($note ? ' — ' . $note : ''),
        ':ref'  => $karigar_id
    ]);
    $ct_id = (int)$pdo->lastInsertId();

    // 2) cash_accounts balance update
    $pdo->prepare("UPDATE cash_accounts SET current_balance = current_balance - ? WHERE id = ?")
        ->execute([$amount, $cash_account_id]);

    // 3) karigar_ledger LABOR_PAYMENT
    $ledIns = $pdo->prepare("
        INSERT INTO karigar_ledger
            (entry_date, karigar_party_id, entry_type, reference_table, reference_id,
             gold_in_pure_gram, gold_out_pure_gram, cash_in, cash_out,
             note, created_by, created_at)
        VALUES
            (:dt, :kid, 'LABOR_PAYMENT', 'cash_transactions', :ref,
             0, 0, 0, :amt,
             :note, :cby, NOW())
    ");
    $ledIns->execute([
        ':dt'   => $payment_date,
        ':kid'  => $karigar_id,
        ':ref'  => $ct_id,
        ':amt'  => $amount,
        ':note' => 'Labor payment — ' . $cash['account_name'] . ($note ? ' — ' . $note : ''),
        ':cby'  => $user_id
    ]);

    // ⚠️ Note: cash_out এখানে negative (আমাদের labor due কমলো)
    // karigar_ledger এ entry_type='LABOR_PAYMENT' মানে আমরা দিলাম
    // ledger calculation এ এটা labor_paid এ যোগ হবে → labor_due কমবে
    // কিন্তু running_cash এ এটা ভুল direction যাবে (cout এ আছে, but it's a payment OUT from us)
    // Actually correct: cash_out = আমরা দিলাম = labor balance কমলো ✅

    // 4) Audit log
    try {
        $alog = $pdo->prepare("
            INSERT INTO audit_log
                (table_name, record_id, action, changed_by, changed_at, ip_address, new_values, note)
            VALUES
                ('karigar_ledger', LAST_INSERT_ID(), 'INSERT', ?, NOW(), ?, ?, ?)
        ");
        $alog->execute([
            $user_id,
            $ip,
            json_encode([
                'karigar' => $karigar['name'],
                'amount'  => $amount,
                'cash_account' => $cash['account_name'],
                'cash_txn_id'  => $ct_id
            ], JSON_UNESCAPED_UNICODE),
            'Karigar labor payment'
        ]);
    } catch (Throwable $e) { /* silent */ }

    $pdo->commit();

    out_json(200, true, '✅ Labor payment সফল — ৳' . number_format($amount, 2) . ' কাটা হলো ' . $cash['account_name'] . ' থেকে', [
        'karigar_name'   => $karigar['name'],
        'amount'         => $amount,
        'cash_account'   => $cash['account_name'],
        'cash_txn_id'    => $ct_id,
        'payment_date'   => $payment_date
    ]);

} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    out_json(500, false, 'সার্ভার ত্রুটি: ' . $e->getMessage(), null);
}
