<?php
require_once '../includes/auth.php';
require_once '../db.php';

header('Content-Type: application/json');

$action = $_POST['action'] ?? $_GET['action'] ?? '';
$inv_id = (int)($_POST['sales_invoice_id'] ?? $_GET['sales_invoice_id'] ?? 0);

if ($inv_id <= 0) { echo json_encode(['status'=>'error','msg'=>'Invalid invoice.']); exit; }

$isAdminLike = in_array($_SESSION['user_role'] ?? '', ['admin', 'master_staff']);
$cidFilter   = $isAdminLike ? '' : "AND company_id=$cid";

// Verify invoice exists and belongs to this company
$inv = $conn->query("
    SELECT id, net_total, received_amount, balance_amount, status
    FROM sales_invoices WHERE id=$inv_id $cidFilter LIMIT 1
")->fetch_assoc();
if (!$inv) { echo json_encode(['status'=>'error','msg'=>'Invoice not found.']); exit; }

// ── LIST ─────────────────────────────────────────────────────────────────────
if ($action === 'list') {
    $payments = [];
    $res = $conn->query("
        SELECT p.id, p.amount, p.payment_mode, p.payment_date, p.note, p.created_at,
               u.name AS created_by_name
        FROM invoice_payments p
        LEFT JOIN users u ON u.id = p.created_by
        WHERE p.sales_invoice_id = $inv_id
        ORDER BY p.payment_date ASC, p.id ASC
    ");
    while ($r = $res->fetch_assoc()) $payments[] = $r;
    echo json_encode([
        'status'          => 'ok',
        'payments'        => $payments,
        'net_total'       => (float)$inv['net_total'],
        'received_amount' => (float)$inv['received_amount'],
        'balance_amount'  => (float)$inv['balance_amount'],
    ]);
    exit;
}

// ── ADD ──────────────────────────────────────────────────────────────────────
if ($action === 'add') {
    if ($inv['status'] === 'cancelled') {
        echo json_encode(['status'=>'error','msg'=>'Cannot add payment to a cancelled invoice.']); exit;
    }

    $amount  = round((float)($_POST['amount'] ?? 0), 2);
    $mode    = trim($_POST['payment_mode'] ?? 'Cash');
    $date    = $_POST['payment_date'] ?? date('Y-m-d');
    $note    = trim($_POST['note'] ?? '');
    $userId  = (int)($_SESSION['user_id'] ?? 0);

    if ($amount <= 0) { echo json_encode(['status'=>'error','msg'=>'Amount must be greater than 0.']); exit; }
    if (!in_array($mode, ['Cash','UPI','Card','Bank'])) $mode = 'Cash';

    $conn->begin_transaction();
    try {
        $stmt = $conn->prepare("
            INSERT INTO invoice_payments (sales_invoice_id, amount, payment_mode, payment_date, note, created_by)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->bind_param("idsssi", $inv_id, $amount, $mode, $date, $note, $userId);
        $stmt->execute();
        $new_id = $stmt->insert_id;

        // Recalculate totals from ledger
        $paid = (float)$conn->query("SELECT COALESCE(SUM(amount),0) AS t FROM invoice_payments WHERE sales_invoice_id=$inv_id")->fetch_assoc()['t'];
        $balance = max(0, round((float)$inv['net_total'] - $paid, 2));

        $conn->query("UPDATE sales_invoices SET received_amount=$paid, balance_amount=$balance WHERE id=$inv_id");

        // Finalize master invoice if this is a sub-invoice
        $master_id = (int)$conn->query("SELECT master_invoice_id FROM sales_invoices WHERE id=$inv_id")->fetch_assoc()['master_invoice_id'];

        $conn->commit();

        echo json_encode([
            'status'          => 'ok',
            'payment_id'      => $new_id,
            'received_amount' => $paid,
            'balance_amount'  => $balance,
            'net_total'       => (float)$inv['net_total'],
            'master_id'       => $master_id,
        ]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status'=>'error','msg'=>$e->getMessage()]);
    }
    exit;
}

// ── DELETE ───────────────────────────────────────────────────────────────────
if ($action === 'delete') {
    $pay_id = (int)($_POST['payment_id'] ?? 0);
    if ($pay_id <= 0) { echo json_encode(['status'=>'error','msg'=>'Invalid payment ID.']); exit; }

    // Verify payment belongs to this invoice
    $pay = $conn->query("SELECT id FROM invoice_payments WHERE id=$pay_id AND sales_invoice_id=$inv_id")->fetch_assoc();
    if (!$pay) { echo json_encode(['status'=>'error','msg'=>'Payment not found.']); exit; }

    $conn->begin_transaction();
    try {
        $conn->query("DELETE FROM invoice_payments WHERE id=$pay_id");

        $paid = (float)$conn->query("SELECT COALESCE(SUM(amount),0) AS t FROM invoice_payments WHERE sales_invoice_id=$inv_id")->fetch_assoc()['t'];
        $balance = max(0, round((float)$inv['net_total'] - $paid, 2));

        $conn->query("UPDATE sales_invoices SET received_amount=$paid, balance_amount=$balance WHERE id=$inv_id");

        $conn->commit();

        echo json_encode([
            'status'          => 'ok',
            'received_amount' => $paid,
            'balance_amount'  => $balance,
            'net_total'       => (float)$inv['net_total'],
        ]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status'=>'error','msg'=>$e->getMessage()]);
    }
    exit;
}

echo json_encode(['status'=>'error','msg'=>'Unknown action.']);
