<?php
session_start();
require_once '../assets/db_connect.php';

// Check if user is logged in
if (!isset($_SESSION['user'])) {
    echo json_encode(['status' => 'error', 'message' => 'User not logged in']);
    exit;
}

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

// Debug: Log received data
error_log("=== save_purchase.php called ===");
error_log("POST data: " . print_r($_POST, true));

// Get POST data
$supplier_id = isset($_POST['supplier_id']) ? intval($_POST['supplier_id']) : null;
$invoice_no = isset($_POST['invoice_no']) ? trim($_POST['invoice_no']) : '';
$purchase_date = isset($_POST['purchase_date']) ? $_POST['purchase_date'] : date('Y-m-d');
$shop_id = isset($_POST['shop_id']) ? intval($_POST['shop_id']) : $shop_id;
$created_by = isset($_POST['created_by']) ? intval($_POST['created_by']) : $user_id;

// Get items data
$product_ids = isset($_POST['product_id']) ? $_POST['product_id'] : [];
$batch_nos = isset($_POST['batch_no']) ? $_POST['batch_no'] : [];
$qtys = isset($_POST['qty']) ? $_POST['qty'] : [];
$cost_prices = isset($_POST['cost_price']) ? $_POST['cost_price'] : [];
$sell_prices = isset($_POST['sell_price']) ? $_POST['sell_price'] : [];
$expiry_dates = isset($_POST['expiry_date']) ? $_POST['expiry_date'] : [];

// Debug log
error_log("Invoice No: " . $invoice_no);
error_log("Supplier ID: " . $supplier_id);
error_log("Product IDs count: " . count($product_ids));

// Validate required fields
if (empty($invoice_no)) {
    echo json_encode(['status' => 'error', 'message' => 'Invoice number is required']);
    exit;
}

if (empty($product_ids) || !is_array($product_ids) || count($product_ids) === 0) {
    echo json_encode(['status' => 'error', 'message' => 'No products added']);
    exit;
}

try {
    $pdo->beginTransaction();
    
    // Calculate total purchase amount
    $total_amount = 0;
    for ($i = 0; $i < count($product_ids); $i++) {
        $qty = intval($qtys[$i] ?? 0);
        $cost = floatval($cost_prices[$i] ?? 0);
        $total_amount += ($qty * $cost);
    }
    
    // 1. Create purchase record
    $purchase_sql = "INSERT INTO purchases 
        (supplier_id, invoice_no, purchase_date, total, created_by, shop_id, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, NOW())";
    
    $purchase_stmt = $pdo->prepare($purchase_sql);
    $purchase_stmt->execute([
        $supplier_id ?: null,
        $invoice_no,
        $purchase_date,
        $total_amount,
        $created_by,
        $shop_id
    ]);
    
    $purchase_id = $pdo->lastInsertId();
    
    error_log("Purchase created with ID: " . $purchase_id . ", Total: " . $total_amount);
    
    // 2. Process each item
    $batch_ids = [];
    for ($i = 0; $i < count($product_ids); $i++) {
        $product_id = intval($product_ids[$i]);
        $batch_no = trim($batch_nos[$i] ?? '');
        $qty = intval($qtys[$i] ?? 0);
        $cost_price = floatval($cost_prices[$i] ?? 0);
        $sell_price = floatval($sell_prices[$i] ?? 0);
        $expiry_date = !empty($expiry_dates[$i]) ? $expiry_dates[$i] : null;
        
        if ($product_id <= 0 || $qty <= 0 || $cost_price <= 0) {
            error_log("Skipping invalid item: product_id=$product_id, qty=$qty, cost=$cost_price");
            continue; // Skip invalid items
        }
        
        error_log("Processing item $i: product_id=$product_id, batch=$batch_no, qty=$qty");
        
        // Create product batch
        $batch_sql = "INSERT INTO product_batches
            (product_id, batch_no, qty, cost_price, sell_price, expiry_date, supplier_id,
             created_by, created_at, updated_by, updated_at, shop_id, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, NOW(), ?, 1)";
        
        $batch_stmt = $pdo->prepare($batch_sql);
        $batch_stmt->execute([
            $product_id,
            $batch_no,
            $qty,
            $cost_price,
            $sell_price,
            $expiry_date,
            $supplier_id ?: null,
            $created_by,
            $created_by, // updated_by
            $shop_id
        ]);
        
        $batch_id = $pdo->lastInsertId();
        $batch_ids[] = $batch_id;
        
        // Create purchase line
        $purchase_line_sql = "INSERT INTO purchase_lines
            (purchase_id, batch_id, qty, cost_price)
            VALUES (?, ?, ?, ?)";
        
        $purchase_line_stmt = $pdo->prepare($purchase_line_sql);
        $purchase_line_stmt->execute([
            $purchase_id,
            $batch_id,
            $qty,
            $cost_price
        ]);
        
        // Create inventory movement
        $movement_sql = "INSERT INTO inventory_movements 
            (product_id, batch_id, change_qty, movement_type, reference_id,
             note, created_by, shop_id, created_at)
            VALUES (?, ?, ?, 'PURCHASE', ?, ?, ?, ?, NOW())";
        
        $movement_note = "Purchase #{$purchase_id} - {$batch_no}";
        
        $movement_stmt = $pdo->prepare($movement_sql);
        $movement_stmt->execute([
            $product_id,
            $batch_id,
            $qty,
            $purchase_id,
            $movement_note,
            $created_by,
            $shop_id
        ]);
        
        // Update product prices
        $update_product_sql = "UPDATE products SET 
            buying_price = ?, 
            selling_price = ? 
            WHERE id = ? AND shop_id = ?";
        
        $update_stmt = $pdo->prepare($update_product_sql);
        $update_stmt->execute([
            $cost_price,
            $sell_price,
            $product_id,
            $shop_id
        ]);
    }
    
    $pdo->commit();
    
    error_log("Purchase saved successfully: ID $purchase_id, " . count($batch_ids) . " items");
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Purchase saved successfully!',
        'purchase_id' => $purchase_id,
        'total_amount' => $total_amount,
        'item_count' => count($batch_ids)
    ]);
    
} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    error_log("Save Purchase Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}