<?php
// ajax/save_goods_received.php
// Saves a new GRN and atomically updates pharmacy_inventory.current_stock
ob_start();
require_once '../layouts/session.php';
require_once '../layouts/dbconn.php';
ob_end_clean();

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

// Auth guard
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorised']);
    exit;
}

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

// ── Validate required top-level fields ───────────────────────────────────────
$required = ['supplier_id', 'delivery_date', 'items'];
foreach ($required as $f) {
    if (empty($data[$f])) {
        echo json_encode(['success' => false, 'message' => "Missing required field: $f"]);
        exit;
    }
}

$supplier_id         = (int) $data['supplier_id'];
$supplier_invoice_no = trim($data['supplier_invoice_no'] ?? '');
$delivery_note_no    = trim($data['delivery_note_no']    ?? '');
$delivery_date       = $data['delivery_date'];
$notes               = trim($data['notes'] ?? '');
$items               = $data['items'];
$user_id             = (int) $_SESSION['user_id'];

if (empty($items) || !is_array($items)) {
    echo json_encode(['success' => false, 'message' => 'No items provided']);
    exit;
}

// ── Generate GRN number ───────────────────────────────────────────────────────
$today  = date('Ymd');
$res    = $conn->query("SELECT COUNT(*) AS cnt FROM pharmacy_grn WHERE DATE(created_at) = CURDATE()");
$seq    = ($res->fetch_assoc()['cnt'] ?? 0) + 1;
$grn_no = 'GRN-' . $today . '-' . str_pad($seq, 3, '0', STR_PAD_LEFT);

// ── Calculate total (after discounts) ────────────────────────────────────────
$total_amount = 0;
foreach ($items as $item) {
    $qty      = (float)($item['qty_received']    ?? 0);
    $cost     = (float)($item['buying_price']     ?? 0);
    $disc_amt = (float)($item['discount_amount']  ?? 0);
    $total_amount += ($qty * $cost) - $disc_amt;
}

// ── Transaction ───────────────────────────────────────────────────────────────
$conn->begin_transaction();
try {
    // 1. Insert GRN header
    $stmt = $conn->prepare("
        INSERT INTO pharmacy_grn
            (grn_number, supplier_id, supplier_invoice_no, delivery_note_no,
             delivery_date, total_amount, notes, status, received_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, 'RECEIVED', ?)
    ");
    $stmt->bind_param(
        'sisssdsi',
        $grn_no, $supplier_id, $supplier_invoice_no, $delivery_note_no,
        $delivery_date, $total_amount, $notes, $user_id
    );
    $stmt->execute();
    $grn_id = $conn->insert_id;
    $stmt->close();

    // 2. Insert line items + update stock
    $item_stmt = $conn->prepare("
        INSERT INTO pharmacy_grn_items
            (grn_id, inventory_id, batch_number, expiry_date,
             qty_received, buying_price, discount_pct, discount_amount, notes)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stock_stmt = $conn->prepare("
        UPDATE pharmacy_inventory
        SET current_stock = current_stock + ?,
            buying_price  = ?,          -- update to latest net unit cost
            updated_at    = NOW()
        WHERE inventory_id = ?
    ");

    foreach ($items as $item) {
        $inv_id   = (int)   $item['inventory_id'];
        $qty      = (float) $item['qty_received'];
        $cost     = (float) $item['buying_price'];
        $disc_pct = (float)($item['discount_pct']    ?? 0);
        $disc_amt = (float)($item['discount_amount']  ?? 0);
        $batch    = trim($item['batch_number'] ?? '');
        $expiry   = !empty($item['expiry_date']) ? $item['expiry_date'] : null;
        $i_notes  = trim($item['notes'] ?? '');

        if ($inv_id <= 0 || $qty <= 0) continue; // skip invalid

        // Net unit cost after per-unit discount
        $net_unit_cost = $qty > 0 ? ($cost - ($disc_amt / $qty)) : $cost;

        // Insert item row (now includes discount columns)
        $item_stmt->bind_param(
            'iissdddds',
            $grn_id, $inv_id, $batch, $expiry,
            $qty, $cost, $disc_pct, $disc_amt, $i_notes
        );
        $item_stmt->execute();

        // Bump stock; store net unit cost as the latest buying price
        $stock_stmt->bind_param('ddi', $qty, $net_unit_cost, $inv_id);
        $stock_stmt->execute();
    }

    $item_stmt->close();
    $stock_stmt->close();

    // 3. Activity log
    $log_stmt = $conn->prepare("
        INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address)
        VALUES (?, 'CREATE', 'pharmacy_grn', ?, 'pharmacy_grn', ?)
    ");
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $log_stmt->bind_param('iis', $user_id, $grn_id, $ip);
    $log_stmt->execute();
    $log_stmt->close();

    $conn->commit();

    echo json_encode([
        'success'    => true,
        'grn_id'     => $grn_id,
        'grn_number' => $grn_no,
        'message'    => 'GRN saved and stock updated successfully'
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}