<?php
include('includes/db.php');

header('Content-Type: application/json');

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => 'Invalid data']);
    exit;
}

// Debug logging
error_log("Received invoice data: " . print_r($data, true));

// Start transaction
mysqli_begin_transaction($conn);

try {
    // 1. Save customer information
    $customerName = mysqli_real_escape_string($conn, $data['customer_name'] ?? 'Walk-in Customer');
    $customerPhone = mysqli_real_escape_string($conn, $data['customer_phone'] ?? '');
    
    // Check if customer exists by phone (if phone provided)
    $customerId = null;
    if (!empty($customerPhone)) {
        $checkCustomer = mysqli_query($conn, "SELECT id FROM customers WHERE phone = '$customerPhone' LIMIT 1");
        if ($checkCustomer && mysqli_num_rows($checkCustomer) > 0) {
            $customerRow = mysqli_fetch_assoc($checkCustomer);
            $customerId = $customerRow['id'];
        }
    }
    
    // If customer doesn't exist, create new
    if (!$customerId) {
        $insertCustomer = mysqli_query($conn, 
            "INSERT INTO customers (name, phone, created_at) 
             VALUES ('$customerName', '$customerPhone', NOW())");
        if (!$insertCustomer) throw new Exception("Failed to save customer: " . mysqli_error($conn));
        $customerId = mysqli_insert_id($conn);
    }
    
    // 2. Save invoice with item discount tracking
    $subtotal = floatval($data['subtotal'] ?? 0);
    $discount = floatval($data['discount'] ?? 0);
    $discountType = mysqli_real_escape_string($conn, $data['discount_type'] ?? 'percent');
    $total = floatval($data['total'] ?? 0);
    $cashReceived = floatval($data['cash_received'] ?? 0);
    $changeGiven = floatval($data['change_given'] ?? 0);
    $paymentMethod = mysqli_real_escape_string($conn, $data['payment_method'] ?? 'cash');
    
    // Get total item discount from data
    $totalItemDiscount = floatval($data['total_item_discount'] ?? 0);
    
    // Generate invoice number
    $invoiceNumber = 'INV' . date('YmdHis') . rand(100, 999);
    
    // Insert invoice
    $insertInvoice = mysqli_query($conn,
        "INSERT INTO invoices (
            customer_id, invoice_number, subtotal, discount, discount_type, 
            total_item_discount, total, cash_received, change_given, payment_method, created_at
        ) VALUES (
            $customerId, 
            '$invoiceNumber',
            $subtotal, $discount, '$discountType', 
            $totalItemDiscount, $total, $cashReceived, $changeGiven, '$paymentMethod', NOW()
        )");
    
    if (!$insertInvoice) {
        throw new Exception("Failed to save invoice: " . mysqli_error($conn));
    }
    $invoiceId = mysqli_insert_id($conn);
    
    // 3. Save invoice items with calculations for invoice_print.php
    $items = $data['items'] ?? [];
    $totalProfit = 0;
    $totalItems = 0;
    $soldProducts = [];
    
    error_log("Items count: " . count($items));
    
    foreach ($items as $index => $item) {
        error_log("Processing item $index: " . print_r($item, true));
        
        $productId = intval($item['id'] ?? 0);
        $productName = mysqli_real_escape_string($conn, $item['name'] ?? 'Unknown Product');
        $quantity = intval($item['quantity'] ?? $item['qty'] ?? 1);
        $price = floatval($item['price'] ?? 0);
        $category = mysqli_real_escape_string($conn, $item['category'] ?? $item['product_category'] ?? '');
        $productCode = mysqli_real_escape_string($conn, $item['code'] ?? $item['product_code'] ?? '');
        
        // Get discount information for this item
        $discountValue = floatval($item['discountValue'] ?? $item['discount_value'] ?? $item['discount'] ?? 0);
        $discountTypeItem = mysqli_real_escape_string($conn, $item['discountType'] ?? $item['discount_type'] ?? 'percent');
        
        // Calculate values for invoice_print.php
        $originalPrice = floatval($item['originalPrice'] ?? $item['original_price'] ?? $price);
        $baseAmount = $originalPrice * $quantity;
        
        // Calculate discount amount and percentage
        $discountAmount = 0;
        $discountPercentage = 0;
        
        if ($discountValue > 0) {
            if ($discountTypeItem === 'percent') {
                $discountAmount = $baseAmount * ($discountValue / 100);
                $discountPercentage = $discountValue;
            } else {
                $discountAmount = min($discountValue, $baseAmount);
                $discountPercentage = ($discountAmount / $baseAmount) * 100;
            }
        }
        
        $discountedPrice = $baseAmount - $discountAmount;
        $totalPrice = $discountedPrice;
        
        // Validate required fields
        if (empty($productName)) {
            throw new Exception("Product name is required for item $index");
        }
        
        if ($quantity <= 0) {
            throw new Exception("Invalid quantity for product: $productName");
        }
        
        // Check product stock if product ID is provided
        $stockData = null;
        $currentStock = 0;
        $stockPrice = 0;
        $profit = 0;
        $profitPercentage = 0;
        $customerPrice = $originalPrice; // Default to original price
        
        if ($productId > 0) {
            $checkStock = mysqli_query($conn, "SELECT quantity, product_name, stock_price, customer_price FROM products WHERE id = $productId");
            if (!$checkStock || mysqli_num_rows($checkStock) === 0) {
                throw new Exception("Product not found: ID $productId");
            }
            
            $stockData = mysqli_fetch_assoc($checkStock);
            $currentStock = $stockData['quantity'];
            $stockPrice = floatval($stockData['stock_price']);
            $customerPrice = floatval($stockData['customer_price']);
            
            // Calculate profit based on actual selling price (after discounts)
            $actualSellingPrice = $discountedPrice / $quantity;
            $profit = ($actualSellingPrice - $stockPrice) * $quantity;
            $profitPercentage = $stockPrice > 0 ? (($actualSellingPrice - $stockPrice) / $stockPrice) * 100 : 0;
            $totalProfit += $profit;
            
            if ($currentStock < $quantity) {
                throw new Exception("Insufficient stock for product: " . $stockData['product_name'] . " (Available: $currentStock, Requested: $quantity)");
            }
        }
        
        // CORRECTED: Insert item with columns that invoice_print.php expects
        $insertItem = mysqli_query($conn,
            "INSERT INTO invoice_items (
                invoice_id, product_name, quantity, 
                original_price, discount_percentage, discounted_price, total_price,
                product_category, product_code
            ) VALUES (
                $invoiceId, '$productName', $quantity, 
                $originalPrice, $discountPercentage, $discountedPrice, $totalPrice,
                '$category', '$productCode'
            )");
        
        if (!$insertItem) {
            throw new Exception("Failed to save invoice item: " . mysqli_error($conn) . " - Product: $productName");
        }
        
        $invoiceItemId = mysqli_insert_id($conn);
        
        // Update product stock if product ID is provided
        if ($productId > 0) {
            $updateStock = mysqli_query($conn,
                "UPDATE products SET quantity = quantity - $quantity WHERE id = $productId");
            
            if (!$updateStock) {
                throw new Exception("Failed to update product stock: " . mysqli_error($conn) . " - Product ID: $productId");
            }
            
            // Log stock reduction for this product
            logStockActivity($conn, $productId, 'STOCK_REDUCED_SALE', $quantity, 
                "Sold in invoice: $invoiceNumber", null, $invoiceId);
            
            // Store product details for sales logging
            $soldProducts[] = [
                'product_id' => $productId,
                'product_name' => $productName,
                'quantity' => $quantity,
                'selling_price' => $customerPrice,
                'actual_selling_price' => $discountedPrice / $quantity,
                'stock_price' => $stockPrice,
                'profit' => $profit,
                'profit_percentage' => $profitPercentage,
                'invoice_item_id' => $invoiceItemId,
                'discount_applied' => $discountAmount
            ];
        } else {
            // For products without ID (custom items), still log them
            $soldProducts[] = [
                'product_id' => null,
                'product_name' => $productName,
                'quantity' => $quantity,
                'selling_price' => $originalPrice,
                'actual_selling_price' => $discountedPrice / $quantity,
                'stock_price' => 0,
                'profit' => 0,
                'profit_percentage' => 0,
                'invoice_item_id' => $invoiceItemId,
                'discount_applied' => $discountAmount,
                'custom_item' => true
            ];
        }
        
        $totalItems += $quantity;
        error_log("Successfully saved item: $productName");
    }
    
    // 4. Create sales log entry - FIXED VERSION
    createSalesLog($conn, $invoiceId, $invoiceNumber, $customerId, $customerName, 
                  $total, $totalProfit, $totalItems, $paymentMethod, $soldProducts);
    
    // 5. Update sales analytics
    updateSalesAnalytics($conn, $total, $totalProfit);
    
    // Commit transaction
    mysqli_commit($conn);
    
    error_log("Invoice saved successfully: $invoiceNumber");
    error_log("Total profit calculated: $totalProfit");
    error_log("Sold products: " . count($soldProducts));
    
    echo json_encode([
        'success' => true,
        'invoice_id' => $invoiceNumber,
        'invoice_number' => $invoiceNumber,
        'total_profit' => $totalProfit,
        'message' => 'Invoice saved successfully with sales logging'
    ]);
    
} catch (Exception $e) {
    mysqli_rollback($conn);
    error_log("Invoice save error: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => 'Error saving invoice: ' . $e->getMessage()
    ]);
}

/**
 * Log stock activity
 */
function logStockActivity($conn, $productId, $action, $quantity, $reason = '', $userId = null, $invoiceId = null) {
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    // Check if product_logs table exists
    $checkTable = mysqli_query($conn, "SHOW TABLES LIKE 'product_logs'");
    if (!$checkTable || mysqli_num_rows($checkTable) === 0) {
        error_log("product_logs table does not exist, skipping stock logging");
        return true;
    }
    
    $details = json_encode([
        'quantity_change' => -$quantity,
        'reason' => $reason,
        'invoice_id' => $invoiceId,
        'ip_address' => $ip_address,
        'user_agent' => $user_agent
    ], JSON_PRETTY_PRINT);
    
    $sql = "INSERT INTO product_logs (product_id, action, details, user_id, ip_address, user_agent, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, NOW())";
    $stmt = mysqli_prepare($conn, $sql);
    
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "ississ", $productId, $action, $details, $userId, $ip_address, $user_agent);
        $result = mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
        
        if ($result) {
            error_log("Stock activity logged for product $productId");
        } else {
            error_log("Failed to log stock activity for product $productId");
        }
        
        return $result;
    }
    return false;
}

/**
 * Create sales log entry - FIXED VERSION
 */
function createSalesLog($conn, $invoiceId, $invoiceNumber, $customerId, $customerName, 
                       $totalAmount, $totalProfit, $totalItems, $paymentMethod, $soldProducts) {
    
    // Check if sales_logs table exists
    $checkTable = mysqli_query($conn, "SHOW TABLES LIKE 'sales_logs'");
    if (!$checkTable || mysqli_num_rows($checkTable) === 0) {
        error_log("sales_logs table does not exist, skipping sales logging");
        return false;
    }
    
    // Prepare sold products data
    $soldProductsJson = json_encode($soldProducts, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    
    // Debug log
    error_log("Attempting to insert into sales_logs:");
    error_log("Invoice ID: $invoiceId, Invoice Number: $invoiceNumber");
    error_log("Customer ID: $customerId, Customer Name: $customerName");
    error_log("Total Amount: $totalAmount, Total Profit: $totalProfit");
    error_log("Total Items: $totalItems, Payment Method: $paymentMethod");
    error_log("Sold Products Count: " . count($soldProducts));
    
    // Insert sales log - using direct query for better error reporting
    $sql = "INSERT INTO sales_logs (
        invoice_id, invoice_number, customer_id, customer_name, 
        total_amount, total_profit, total_items, payment_method, 
        sold_products, sale_date
    ) VALUES (
        $invoiceId, '$invoiceNumber', $customerId, '$customerName', 
        $totalAmount, $totalProfit, $totalItems, '$paymentMethod', 
        '" . mysqli_real_escape_string($conn, $soldProductsJson) . "', NOW()
    )";
    
    error_log("SQL Query: " . $sql);
    
    $result = mysqli_query($conn, $sql);
    
    if ($result) {
        $logId = mysqli_insert_id($conn);
        error_log("Sales log created successfully! Log ID: $logId");
        return true;
    } else {
        $error = mysqli_error($conn);
        error_log("FAILED to create sales log: " . $error);
        error_log("SQL Error: " . $error);
        return false;
    }
}

/**
 * Update sales analytics
 */
function updateSalesAnalytics($conn, $totalSales, $totalProfit) {
    // Check if sales_analytics table exists
    $checkTable = mysqli_query($conn, "SHOW TABLES LIKE 'sales_analytics'");
    if (!$checkTable || mysqli_num_rows($checkTable) === 0) {
        error_log("sales_analytics table does not exist, skipping analytics update");
        return false;
    }
    
    $today = date('Y-m-d');
    
    // Check if entry exists for today
    $checkExisting = mysqli_query($conn, "SELECT id FROM sales_analytics WHERE sale_date = '$today'");
    
    if ($checkExisting && mysqli_num_rows($checkExisting) > 0) {
        // Update existing entry
        $sql = "UPDATE sales_analytics SET 
                total_sales = total_sales + $totalSales,
                total_profit = total_profit + $totalProfit,
                total_transactions = total_transactions + 1,
                total_items_sold = total_items_sold + 1,
                average_transaction_value = (total_sales + $totalSales) / (total_transactions + 1),
                updated_at = NOW()
                WHERE sale_date = '$today'";
    } else {
        // Create new entry
        $sql = "INSERT INTO sales_analytics (
                sale_date, total_sales, total_profit, total_transactions, 
                total_items_sold, average_transaction_value, created_at, updated_at
            ) VALUES (
                '$today', $totalSales, $totalProfit, 1, 
                1, $totalSales, NOW(), NOW()
            )";
    }
    
    $result = mysqli_query($conn, $sql);
    
    if ($result) {
        error_log("Sales analytics updated for date: $today");
    } else {
        error_log("Failed to update sales analytics: " . mysqli_error($conn));
    }
    
    return $result;
}
?>