<?php
session_start();
require '../assets/db_connect.php';
header('Content-Type: application/json');

$shop_id = $_SESSION['user']['shop_id'] ?? 0;
$user_id = $_SESSION['user']['id'] ?? 0;

if ($shop_id == 0 || $user_id == 0) {
    echo json_encode(['status' => 'error', 'message' => 'Shop or user session missing']);
    exit;
}

$purchase_id  = intval($_POST['purchase_id'] ?? 0);
$supplier_id  = intval($_POST['supplier_id'] ?? 0);
$invoice_no   = trim($_POST['invoice_no'] ?? '');
$purchase_date = $_POST['purchase_date'] ?? date('Y-m-d');
$update_notes = trim($_POST['update_notes'] ?? '');

// Existing items
$line_ids    = $_POST['line_id'] ?? [];
$batch_ids   = $_POST['batch_id'] ?? [];
$product_ids = $_POST['product_id'] ?? [];
$qtys        = $_POST['qty'] ?? [];
$cost_prices = $_POST['cost_price'] ?? [];
$sell_prices = $_POST['sell_price'] ?? [];
$expiry_dates = $_POST['expiry_date'] ?? [];

// New items
$new_product_ids = $_POST['new_product_id'] ?? [];
$new_batch_nos   = $_POST['new_batch_no'] ?? [];
$new_qtys        = $_POST['new_qty'] ?? [];
$new_cost_prices = $_POST['new_cost_price'] ?? [];
$new_sell_prices = $_POST['new_sell_price'] ?? [];
$new_expiry_dates = $_POST['new_expiry_date'] ?? [];

// Items to delete
$delete_line_ids = $_POST['delete_line_id'] ?? [];

if ($purchase_id == 0 || $supplier_id == 0 || empty($invoice_no)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid purchase data']);
    exit;
}

try {
    $pdo->beginTransaction();
    
    // First, check if purchase exists and belongs to this shop
    $checkPurchase = $pdo->prepare("SELECT id, supplier_id FROM purchases WHERE id = ? AND shop_id = ?");
    $checkPurchase->execute([$purchase_id, $shop_id]);
    if (!$checkPurchase->fetch()) {
        throw new Exception("Purchase not found or not authorized");
    }
    
    // Update purchase header - REMOVED updated_at
    $updatePurchase = $pdo->prepare("
        UPDATE purchases 
        SET supplier_id = ?, 
            invoice_no = ?, 
            purchase_date = ?, 
            total = ?, 
            updated_by = ?
        WHERE id = ? AND shop_id = ?
    ");
    
    $total = 0;
    
    // Process existing items
    for ($i = 0; $i < count($line_ids); $i++) {
        $line_id = intval($line_ids[$i]);
        $batch_id = intval($batch_ids[$i]);
        $product_id = intval($product_ids[$i]);
        $qty = intval($qtys[$i]);
        $cost_price = floatval($cost_prices[$i]);
        $sell_price = floatval($sell_prices[$i]);
        $expiry_date = !empty($expiry_dates[$i]) ? $expiry_dates[$i] : null;
        
        // Check if item can be modified (not sold)
        $checkSold = $pdo->prepare("
            SELECT COUNT(*) as sold_count 
            FROM sale_lines 
            WHERE batch_id = ?
        ");
        $checkSold->execute([$batch_id]);
        $soldData = $checkSold->fetch(PDO::FETCH_ASSOC);
        $hasSales = $soldData && $soldData['sold_count'] > 0;
        
        // Get original quantity for inventory adjustment
        $getOriginal = $pdo->prepare("
            SELECT pl.qty as original_qty
            FROM purchase_lines pl
            WHERE pl.id = ? AND pl.purchase_id = ?
        ");
        $getOriginal->execute([$line_id, $purchase_id]);
        $originalData = $getOriginal->fetch(PDO::FETCH_ASSOC);
        
        if ($originalData) {
            $original_qty = intval($originalData['original_qty']);
            
            if (!$hasSales) {
                // Update purchase line
                $updateLine = $pdo->prepare("
                    UPDATE purchase_lines 
                    SET qty = ?, cost_price = ? 
                    WHERE id = ?
                ");
                $updateLine->execute([$qty, $cost_price, $line_id]);
                
                // Update product batch
                $qty_diff = $qty - $original_qty;
                $updateBatch = $pdo->prepare("
                    UPDATE product_batches 
                    SET qty = qty + ?, 
                        cost_price = ?, 
                        sell_price = ?, 
                        expiry_date = COALESCE(?, expiry_date),
                        updated_by = ?, 
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $updateBatch->execute([$qty_diff, $cost_price, $sell_price, $expiry_date, $user_id, $batch_id]);
                
                // Add inventory movement for the difference
                if ($qty_diff != 0) {
                    $movementStmt = $pdo->prepare("
                        INSERT INTO inventory_movements 
                        (product_id, batch_id, change_qty, movement_type, reference_id, 
                         created_by, shop_id, created_at, note)
                        VALUES (?, ?, ?, 'ADJUSTMENT', ?, ?, ?, NOW(), ?)
                    ");
                    $note = "Purchase #$purchase_id update: Changed from $original_qty to $qty units";
                    if ($update_notes) {
                        $note .= " - $update_notes";
                    }
                    $movementStmt->execute([$product_id, $batch_id, $qty_diff, $purchase_id, $user_id, $shop_id, $note]);
                }
                
                $total += $qty * $cost_price;
            } else {
                // Item has sales, only update cost price if quantity hasn't changed
                if ($qty == $original_qty) {
                    // Update purchase line cost price only
                    $updateLine = $pdo->prepare("
                        UPDATE purchase_lines 
                        SET cost_price = ? 
                        WHERE id = ?
                    ");
                    $updateLine->execute([$cost_price, $line_id]);
                    
                    // Update batch cost price
                    $updateBatch = $pdo->prepare("
                        UPDATE product_batches 
                        SET cost_price = ?, 
                            updated_by = ?, 
                            updated_at = NOW()
                        WHERE id = ?
                    ");
                    $updateBatch->execute([$cost_price, $user_id, $batch_id]);
                    
                    $total += $qty * $cost_price;
                } else {
                    // Can't change quantity of sold items, use original for total
                    $total += $original_qty * $cost_price;
                }
            }
        }
    }
    
    // Add new items
    for ($i = 0; $i < count($new_product_ids); $i++) {
        $product_id = intval($new_product_ids[$i]);
        $batch_no = trim($new_batch_nos[$i]);
        $qty = intval($new_qtys[$i]);
        $cost_price = floatval($new_cost_prices[$i]);
        $sell_price = floatval($new_sell_prices[$i]);
        $expiry_date = !empty($new_expiry_dates[$i]) ? $new_expiry_dates[$i] : null;
        
        if ($product_id == 0 || $qty <= 0 || $cost_price <= 0) {
            continue;
        }
        
        // Check if product exists
        $checkProduct = $pdo->prepare("SELECT id FROM products WHERE id = ? AND shop_id = ?");
        $checkProduct->execute([$product_id, $shop_id]);
        if (!$checkProduct->fetch()) {
            throw new Exception("Product ID $product_id not found");
        }
        
        // Check if batch exists
        $checkBatch = $pdo->prepare("
            SELECT id FROM product_batches 
            WHERE product_id = ? AND batch_no = ? AND shop_id = ?
        ");
        $checkBatch->execute([$product_id, $batch_no, $shop_id]);
        $existingBatch = $checkBatch->fetch(PDO::FETCH_ASSOC);
        
        if ($existingBatch) {
            // Update existing batch
            $batch_id = $existingBatch['id'];
            $updateBatch = $pdo->prepare("
                UPDATE product_batches 
                SET qty = qty + ?, 
                    cost_price = ?, 
                    sell_price = ?, 
                    expiry_date = COALESCE(?, expiry_date),
                    updated_by = ?, 
                    updated_at = NOW()
                WHERE id = ?
            ");
            $updateBatch->execute([$qty, $cost_price, $sell_price, $expiry_date, $user_id, $batch_id]);
        } else {
            // Create new batch
            $batchStmt = $pdo->prepare("
                INSERT INTO product_batches
                (product_id, batch_no, qty, cost_price, sell_price, expiry_date, 
                 supplier_id, created_by, updated_by, shop_id, created_at, updated_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");
            $batchStmt->execute([$product_id, $batch_no, $qty, $cost_price, $sell_price, $expiry_date, 
                                 $supplier_id, $user_id, $user_id, $shop_id]);
            $batch_id = $pdo->lastInsertId();
        }
        
        // Add purchase line
        $lineStmt = $pdo->prepare("
            INSERT INTO purchase_lines (purchase_id, batch_id, qty, cost_price)
            VALUES (?, ?, ?, ?)
        ");
        $lineStmt->execute([$purchase_id, $batch_id, $qty, $cost_price]);
        
        // Add inventory movement
        $movementStmt = $pdo->prepare("
            INSERT INTO inventory_movements 
            (product_id, batch_id, change_qty, movement_type, reference_id, 
             created_by, shop_id, created_at, note)
            VALUES (?, ?, ?, 'PURCHASE', ?, ?, ?, NOW(), ?)
        ");
        $note = "Added to purchase #$purchase_id";
        if ($update_notes) {
            $note .= " - $update_notes";
        }
        $movementStmt->execute([$product_id, $batch_id, $qty, $purchase_id, $user_id, $shop_id, $note]);
        
        $total += $qty * $cost_price;
    }
    
    // Delete marked items
    foreach ($delete_line_ids as $delete_line_id) {
        $line_id = intval($delete_line_id);
        
        // Get batch info before deletion
        $getBatchInfo = $pdo->prepare("
            SELECT pl.batch_id, pl.qty, pb.product_id 
            FROM purchase_lines pl
            LEFT JOIN product_batches pb ON pl.batch_id = pb.id
            WHERE pl.id = ? AND pl.purchase_id = ?
        ");
        $getBatchInfo->execute([$line_id, $purchase_id]);
        $batchInfo = $getBatchInfo->fetch(PDO::FETCH_ASSOC);
        
        if ($batchInfo) {
            $batch_id = $batchInfo['batch_id'];
            $deleted_qty = $batchInfo['qty'];
            $product_id = $batchInfo['product_id'];
            
            // Check if item has been sold
            $checkSold = $pdo->prepare("
                SELECT COUNT(*) as sold_count 
                FROM sale_lines 
                WHERE batch_id = ?
            ");
            $checkSold->execute([$batch_id]);
            $soldData = $checkSold->fetch(PDO::FETCH_ASSOC);
            
            if (!$soldData || $soldData['sold_count'] == 0) {
                // Reduce batch quantity
                $updateBatch = $pdo->prepare("
                    UPDATE product_batches 
                    SET qty = qty - ?, 
                        updated_by = ?, 
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $updateBatch->execute([$deleted_qty, $user_id, $batch_id]);
                
                // Add inventory movement (negative adjustment)
                $movementStmt = $pdo->prepare("
                    INSERT INTO inventory_movements 
                    (product_id, batch_id, change_qty, movement_type, reference_id, 
                     created_by, shop_id, created_at, note)
                    VALUES (?, ?, ?, 'ADJUSTMENT', ?, ?, ?, NOW(), ?)
                ");
                $note = "Removed from purchase #$purchase_id: -$deleted_qty units";
                if ($update_notes) {
                    $note .= " - $update_notes";
                }
                $movementStmt->execute([$product_id, $batch_id, -$deleted_qty, $purchase_id, $user_id, $shop_id, $note]);
                
                // Delete purchase line
                $deleteLine = $pdo->prepare("DELETE FROM purchase_lines WHERE id = ?");
                $deleteLine->execute([$line_id]);
            } else {
                throw new Exception("Cannot delete item that has been sold");
            }
        }
    }
    
    // Update purchase total
    $updatePurchase->execute([$supplier_id, $invoice_no, $purchase_date, $total, $user_id, $purchase_id, $shop_id]);
    
    $pdo->commit();
    
    // Store success message in session
    $_SESSION['success_message'] = "Purchase #$purchase_id (Invoice: $invoice_no) updated successfully! New Total: TSh " . number_format($total, 2);
    
    echo json_encode([
        'status' => 'success',
        'message' => "Purchase updated successfully!",
        'purchase_id' => $purchase_id,
        'invoice_no' => $invoice_no,
        'total' => $total
    ]);
    
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode([
        'status' => 'error',
        'message' => "Failed to update purchase: " . $e->getMessage()
    ]);
}