<?php
session_start();
include("../db.php");
include("../journal_entry_handler.php");

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit();
}

// Rights checking removed - will be implemented later

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Get form data
    $store_id = intval($_POST['store_id']);
    $remarks = trim($_POST['remarks'] ?? '');
    $selected_items = $_POST['selected_items'] ?? [];
    $item_names = $_POST['item_names'] ?? [];
    $current_quantities = $_POST['current_quantities'] ?? [];
    $adjustment_quantities = $_POST['adjustment_quantities'] ?? [];
    $cost_prices = $_POST['cost_prices'] ?? [];
    $current_values = $_POST['current_values'] ?? [];
    $adjustment_values = $_POST['adjustment_values'] ?? [];
    $new_quantities = $_POST['new_quantities'] ?? [];
    $new_values = $_POST['new_values'] ?? [];
    
    // Validate required data
    if (empty($selected_items) || empty($store_id)) {
        throw new Exception('Required data is missing');
    }
    
    // Generate adjustment number
    $adjustment_number = 'ADJ-' . date('Ymd') . '-' . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
    
    // Calculate totals
    $total_items = 0;
    $total_adjustment_value = 0;
    $total_current_stock_value = 0;
    $total_new_stock_value = 0;
    
    // Validate and calculate totals
    foreach ($selected_items as $item_id) {
        if (!isset($adjustment_quantities[$item_id]) || !isset($cost_prices[$item_id])) {
            throw new Exception('Missing data for item ID: ' . $item_id);
        }
        
        $adjustment_qty = floatval($adjustment_quantities[$item_id]);
        if ($adjustment_qty == 0) {
            continue; // Skip items with no adjustment
        }
        
        $current_qty = floatval($current_quantities[$item_id]);
        $cost_price = floatval($cost_prices[$item_id]);
        $adjustment_value = $adjustment_qty * $cost_price;
        $current_value = $current_qty * $cost_price;
        $new_value = ($current_qty + $adjustment_qty) * $cost_price;
        
        $total_items++;
        $total_adjustment_value += $adjustment_value;
        $total_current_stock_value += $current_value;
        $total_new_stock_value += $new_value;
    }
    
    if ($total_items == 0) {
        throw new Exception('No valid adjustments found');
    }
    
    // Insert adjustment header
    $insert_adjustment = $conn->prepare("
        INSERT INTO stock_adjustments (
            adjustment_number, store_id, adjustment_date, total_items, 
            total_adjustment_value, total_current_stock_value, total_new_stock_value,
            remarks, created_by
        ) VALUES (?, ?, NOW(), ?, ?, ?, ?, ?, ?)
    ");
    
    $insert_adjustment->bind_param(
        "siddddsi",
        $adjustment_number,
        $store_id,
        $total_items,
        $total_adjustment_value,
        $total_current_stock_value,
        $total_new_stock_value,
        $remarks,
        $_SESSION['user_id']
    );
    
    if (!$insert_adjustment->execute()) {
        throw new Exception('Failed to create adjustment header: ' . $insert_adjustment->error);
    }
    
    $adjustment_id = $conn->insert_id;
    
    // Insert adjustment items and update inventory
    foreach ($selected_items as $item_id) {
        $adjustment_qty = floatval($adjustment_quantities[$item_id]);
        if ($adjustment_qty == 0) {
            continue; // Skip items with no adjustment
        }
        
        // Calculate values for this item
        $current_qty = floatval($current_quantities[$item_id]);
        $cost_price = floatval($cost_prices[$item_id]);
        $new_qty = $current_qty + $adjustment_qty;
        $adjustment_value = $adjustment_qty * $cost_price;
        $current_value = $current_qty * $cost_price;
        $new_value = $new_qty * $cost_price;
        
        // Insert adjustment item
        $insert_item = $conn->prepare("
            INSERT INTO stock_adjustment_items (
                adjustment_id, item_id, item_name, current_quantity, 
                adjustment_quantity, new_quantity, cost_price, 
                current_stock_value, adjustment_value, new_stock_value
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $insert_item->bind_param(
            "iisddddddd",
            $adjustment_id,
            $item_id,
            $item_names[$item_id],
            $current_qty,
            $adjustment_qty,
            $new_qty,
            $cost_price,
            $current_value,
            $adjustment_value,
            $new_value
        );
        
        if (!$insert_item->execute()) {
            throw new Exception('Failed to insert adjustment item: ' . $insert_item->error);
        }
        
        // Insert inventory movement record
        $insert_movement = $conn->prepare("
            INSERT INTO inventory_movements (
                item_id, store_id, movement_type, reference_type, 
                reference_id, quantity
            ) VALUES (?, ?, 'adjustment', 'manual', ?, ?)
        ");
        
        $insert_movement->bind_param(
            "iiid",
            $item_id,
            $store_id,
            $adjustment_id,
            $adjustment_qty
        );
        
        if (!$insert_movement->execute()) {
            throw new Exception('Failed to insert inventory movement: ' . $insert_movement->error);
        }
        
        // Update store inventory
        $update_inventory = $conn->prepare("
            INSERT INTO store_inventory (store_id, item_id, quantity, last_updated) 
            VALUES (?, ?, ?, NOW())
            ON DUPLICATE KEY UPDATE 
            quantity = VALUES(quantity), 
            last_updated = NOW()
        ");
        
        $update_inventory->bind_param(
            "iid",
            $store_id,
            $item_id,
            $new_qty
        );
        
        if (!$update_inventory->execute()) {
            throw new Exception('Failed to update store inventory: ' . $update_inventory->error);
        }
    }
    
    // Create automatic journal entry for the stock adjustment
    // This will now use the Stock Loss account (exp_StockLoss) instead of general Operating Expenses
    $journal_entry_created = false;
    $journal_entry_message = '';
    
    try {
        // Determine adjustment type based on total adjustment value
        $adjustment_type = ($total_adjustment_value >= 0) ? 'addition' : 'reduction';
        
        // Create journal entry
        $journal_entry_id = createStockAdjustmentJournalEntry($conn, $adjustment_id, $adjustment_type, abs($total_adjustment_value), $store_id);
        if ($journal_entry_id) {
            $journal_entry_created = true;
            $journal_entry_message = ' and journal entry created successfully';
            
            // Update stock adjustment with journal entry ID
            $update_journal = $conn->prepare("UPDATE stock_adjustments SET journal_entry_id = ? WHERE id = ?");
            $update_journal->bind_param("ii", $journal_entry_id, $adjustment_id);
            $update_journal->execute();
            $update_journal->close();
        } else {
            $journal_entry_message = ' (journal entry creation failed - check account mappings)';
        }
    } catch (Exception $e) {
        error_log('Journal entry creation error: ' . $e->getMessage());
        $journal_entry_message = ' (journal entry creation failed: ' . $e->getMessage() . ')';
    }
    
    // Commit transaction
    $conn->commit();
    
    // Return success response
    $response = [
        'success' => true,
        'message' => 'Stock adjustment processed successfully' . $journal_entry_message,
        'adjustment_id' => $adjustment_id,
        'adjustment_number' => $adjustment_number,
        'total_items' => $total_items,
        'total_adjustment_value' => $total_adjustment_value,
        'journal_entry_created' => $journal_entry_created
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    // Rollback transaction on error
    if ($conn->connect_errno == 0) {
        $conn->rollback();
    }
    
    error_log('Stock adjustment error: ' . $e->getMessage());
    
    $response = [
        'success' => false,
        'message' => 'Failed to process stock adjustment: ' . $e->getMessage()
    ];
    
    http_response_code(500);
    echo json_encode($response);
    
} finally {
    // Close prepared statements
    if (isset($insert_adjustment)) $insert_adjustment->close();
    if (isset($insert_item)) $insert_item->close();
    if (isset($insert_movement)) $insert_movement->close();
    if (isset($update_inventory)) $update_inventory->close();
}


?>
