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

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

// One-time migration: create table + add columns if missing
$conn->query("
    CREATE TABLE IF NOT EXISTS purchase_payments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        purchase_order_id INT NOT NULL,
        amount DECIMAL(12,2) NOT NULL,
        payment_mode VARCHAR(30) DEFAULT 'Cash',
        payment_date DATE NOT NULL,
        note VARCHAR(255) DEFAULT '',
        created_by INT DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
");
$existingCols = array_column(
    $conn->query("SHOW COLUMNS FROM purchase_orders")->fetch_all(MYSQLI_ASSOC), 'Field'
);
if (!in_array('received_amount', $existingCols))
    $conn->query("ALTER TABLE purchase_orders ADD COLUMN received_amount DECIMAL(12,2) NOT NULL DEFAULT 0");
if (!in_array('balance_amount', $existingCols))
    $conn->query("ALTER TABLE purchase_orders ADD COLUMN balance_amount DECIMAL(12,2) NOT NULL DEFAULT 0");

// Initialize balance for POs where it defaulted to 0 but hasn't been set yet
$conn->query("UPDATE purchase_orders SET balance_amount = net_amount - received_amount WHERE balance_amount = 0 AND received_amount = 0 AND net_amount > 0");

$action = $_POST['action'] ?? $_GET['action'] ?? '';
$po_id  = (int)($_POST['purchase_order_id'] ?? $_GET['purchase_order_id'] ?? 0);

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

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

$po = $conn->query("
    SELECT id, net_amount, received_amount, balance_amount, status
    FROM purchase_orders WHERE id=$po_id $cidFilter LIMIT 1
")->fetch_assoc();
if (!$po) { echo json_encode(['status'=>'error','msg'=>'Purchase order 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 purchase_payments p
        LEFT JOIN users u ON u.id = p.created_by
        WHERE p.purchase_order_id = $po_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_amount'      => (float)$po['net_amount'],
        'received_amount' => (float)$po['received_amount'],
        'balance_amount'  => (float)$po['balance_amount'],
    ]);
    exit;
}

// ── ADD ──────────────────────────────────────────────────────────────────────
if ($action === 'add') {
    if ($po['status'] === 'cancelled') {
        echo json_encode(['status'=>'error','msg'=>'Cannot add payment to a cancelled purchase order.']); 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 purchase_payments (purchase_order_id, amount, payment_mode, payment_date, note, created_by)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->bind_param("idsssi", $po_id, $amount, $mode, $date, $note, $userId);
        $stmt->execute();
        $new_id = $stmt->insert_id;

        $paid    = (float)$conn->query("SELECT COALESCE(SUM(amount),0) AS t FROM purchase_payments WHERE purchase_order_id=$po_id")->fetch_assoc()['t'];
        $balance = max(0, round((float)$po['net_amount'] - $paid, 2));

        $conn->query("UPDATE purchase_orders SET received_amount=$paid, balance_amount=$balance WHERE id=$po_id");
        $conn->commit();

        echo json_encode([
            'status'          => 'ok',
            'payment_id'      => $new_id,
            'received_amount' => $paid,
            'balance_amount'  => $balance,
            'net_amount'      => (float)$po['net_amount'],
        ]);
    } 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; }

    $pay = $conn->query("SELECT id FROM purchase_payments WHERE id=$pay_id AND purchase_order_id=$po_id")->fetch_assoc();
    if (!$pay) { echo json_encode(['status'=>'error','msg'=>'Payment not found.']); exit; }

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

        $paid    = (float)$conn->query("SELECT COALESCE(SUM(amount),0) AS t FROM purchase_payments WHERE purchase_order_id=$po_id")->fetch_assoc()['t'];
        $balance = max(0, round((float)$po['net_amount'] - $paid, 2));

        $conn->query("UPDATE purchase_orders SET received_amount=$paid, balance_amount=$balance WHERE id=$po_id");
        $conn->commit();

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

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