<?php
// orders.php
include('includes/db.php');

// Function to log stock activities
function logStockActivity($conn, $productId, $action, $quantity, $reason = '', $userId = null) {
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    // Check if product_logs table exists
    $checkTable = "SHOW TABLES LIKE 'product_logs'";
    $tableResult = mysqli_query($conn, $checkTable);
    if (mysqli_num_rows($tableResult) === 0) {
        return true; // Table doesn't exist, skip logging
    }
    
    $details = json_encode([
        'quantity_change' => $quantity,
        'reason' => $reason,
        '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);
        return $result;
    }
    return false;
}

// -----------------------------
// WhatsApp send handler
// -----------------------------
if (isset($_GET['send_whatsapp'])) {
    $invoice_id = (int)$_GET['send_whatsapp'];

    // Fetch invoice and customer details
    $sql = "SELECT i.*, c.name as customer_name, c.phone as customer_phone
            FROM invoices i
            LEFT JOIN customers c ON i.customer_id = c.id
            WHERE i.id = ?";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, 'i', $invoice_id);
    mysqli_stmt_execute($stmt);
    $res = mysqli_stmt_get_result($stmt);
    $invoice = mysqli_fetch_assoc($res);

    if (!$invoice) {
        // Redirect back with message if invoice not found
        header("Location: orders.php?msg=" . urlencode("Invoice not found") . "&type=danger");
        exit;
    }

    // Fetch invoice items
    $items_sql = "SELECT product_name, quantity, original_price, discounted_price, total_price FROM invoice_items WHERE invoice_id = ?";
    $items_stmt = mysqli_prepare($conn, $items_sql);
    mysqli_stmt_bind_param($items_stmt, 'i', $invoice_id);
    mysqli_stmt_execute($items_stmt);
    $items_result = mysqli_stmt_get_result($items_stmt);

    $items = [];
    while ($it = mysqli_fetch_assoc($items_result)) {
        $items[] = $it;
    }

    // Build message (shop details + invoice summary)
    // Using the provided shop details
    $shop_name = "Men's Core Fashion";
    $gst = "33CQGPA6498A1Z3";
    $addr1 = "PN Towers, 45/88B, kandasamy Vathiyar street, Canara Bank opp";
    $city = "Dharmapuri-636701.";
    $phone_shop = "95788 75699";
    $proprietor = "Men's Core Fashion";

    $message = "{$shop_name}\nGSTIN: {$gst}\n{$addr1}\n{$city}\nPh: {$phone_shop}\nProprietor: {$proprietor}\n\n";
    $message .= "Invoice: " . ($invoice['invoice_number'] ?? "N/A") . "\n";
    $message .= "Date: " . date("d-m-Y H:i", strtotime($invoice['created_at'])) . "\n";
    $message .= "Customer: " . ($invoice['customer_name'] ?? 'Walk-in Customer') . "\n\n";
    $message .= "Items:\n";

    foreach ($items as $idx => $it) {
        $qty = (int)$it['quantity'];
        $pname = $it['product_name'];
        $price = number_format((float)$it['total_price'], 2);
        $message .= ($idx + 1) . ". {$pname} x{$qty} - ₹{$price}\n";
    }

    $message .= "\nSubtotal: ₹" . number_format((float)$invoice['subtotal'], 2) . "\n";
    $message .= "Total: ₹" . number_format((float)$invoice['total'], 2) . "\n";
    if (!empty($invoice['payment_method'])) {
        $message .= "Payment: " . strtoupper($invoice['payment_method']) . "\n";
    }
    $message .= "\nThank you for shopping with us!\n";

    // Encode message
    $encoded = rawurlencode($message);

    // Determine recipient: use customer phone if available, otherwise open WhatsApp Web without recipient
    $cust_phone = $invoice['customer_phone'] ?? '';
    $cust_phone = trim($cust_phone);

    if (!empty($cust_phone)) {
        // Keep digits only, handle local 10-digit numbers by prepending country code 91
        $clean = preg_replace('/\D+/', '', $cust_phone);
        if (strlen($clean) === 10) {
            $clean = '91' . $clean;
        } elseif (strlen($clean) === 11 && strpos($clean, '0') === 0) {
            // if starts with 0 and 11 digits -> strip leading 0
            $clean = '91' . substr($clean, 1);
        }
        // Construct wa.me URL
        $waUrl = "https://wa.me/{$clean}?text={$encoded}";
    } else {
        // Open WhatsApp Web with message prefilled (no recipient)
        $waUrl = "https://web.whatsapp.com/send?text={$encoded}";
    }

    header("Location: $waUrl");
    exit;
}

// Handle order/invoice deletion
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    // Fetch invoice details for logging
    $sql = "SELECT i.id, i.invoice_number, i.customer_id, i.total, i.payment_method, i.created_at, c.name as customer_name
            FROM invoices i
            LEFT JOIN customers c ON i.customer_id = c.id
            WHERE i.id = ?";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, 'i', $delete_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $invoice = mysqli_fetch_assoc($result);
    if ($invoice) {
        // Log the deletion
        $record_details = json_encode($invoice);
        $log_sql = "INSERT INTO deletion_logs (table_name, record_id, record_details, deleted_by) VALUES (?, ?, ?, ?)";
        $log_stmt = mysqli_prepare($conn, $log_sql);
        $table_name = 'invoices';
        $deleted_by = 'admin';
        mysqli_stmt_bind_param($log_stmt, 'siss', $table_name, $delete_id, $record_details, $deleted_by);
        mysqli_stmt_execute($log_stmt);
        // Delete associated invoice items first
        $delete_items_sql = "DELETE FROM invoice_items WHERE invoice_id = ?";
        $delete_items_stmt = mysqli_prepare($conn, $delete_items_sql);
        mysqli_stmt_bind_param($delete_items_stmt, 'i', $delete_id);
        mysqli_stmt_execute($delete_items_stmt);
        // Delete identifiers
        $delete_ident_sql = "DELETE FROM invoice_item_identifiers WHERE invoice_id = ?";
        $delete_ident_stmt = mysqli_prepare($conn, $delete_ident_sql);
        mysqli_stmt_bind_param($delete_ident_stmt, 'i', $delete_id);
        mysqli_stmt_execute($delete_ident_stmt);
        // Delete the invoice
        $delete_sql = "DELETE FROM invoices WHERE id = ?";
        $delete_stmt = mysqli_prepare($conn, $delete_sql);
        mysqli_stmt_bind_param($delete_stmt, 'i', $delete_id);
        $success = mysqli_stmt_execute($delete_stmt);
        if ($success) {
            header("Location: orders.php?msg=Order deleted successfully&type=success");
        } else {
            header("Location: orders.php?msg=Failed to delete order&type=danger");
        }
        exit();
    } else {
        header("Location: orders.php?msg=Order not found&type=warning");
        exit();
    }
}

// Handle bulk actions
if (isset($_POST['bulk_action']) && isset($_POST['selected_orders'])) {
    $bulk_action = $_POST['bulk_action'];
    $selected_orders = $_POST['selected_orders'];
   
    if ($bulk_action === 'delete') {
        $success_count = 0;
        $error_count = 0;
       
        foreach ($selected_orders as $order_id) {
            $order_id = (int)$order_id;
           
            $delete_items_sql = "DELETE FROM invoice_items WHERE invoice_id = ?";
            $delete_items_stmt = mysqli_prepare($conn, $delete_items_sql);
            mysqli_stmt_bind_param($delete_items_stmt, 'i', $order_id);
            mysqli_stmt_execute($delete_items_stmt);
           
            $delete_ident_sql = "DELETE FROM invoice_item_identifiers WHERE invoice_id = ?";
            $delete_ident_stmt = mysqli_prepare($conn, $delete_ident_sql);
            mysqli_stmt_bind_param($delete_ident_stmt, 'i', $order_id);
            mysqli_stmt_execute($delete_ident_stmt);
           
            $delete_sql = "DELETE FROM invoices WHERE id = ?";
            $delete_stmt = mysqli_prepare($conn, $delete_sql);
            mysqli_stmt_bind_param($delete_stmt, 'i', $order_id);
           
            if (mysqli_stmt_execute($delete_stmt)) {
                $success_count++;
            } else {
                $error_count++;
            }
        }
       
        $msg = "Bulk delete completed: {$success_count} orders deleted";
        if ($error_count > 0) {
            $msg .= ", {$error_count} failed";
        }
        header("Location: orders.php?msg=" . urlencode($msg) . "&type=" . ($error_count > 0 ? 'warning' : 'success'));
        exit();
    }
}

// Handle return/exchange actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_type'])) {
    $action_type = $_POST['action_type'];
    $invoice_item_id = (int)$_POST['invoice_item_id'];
    $quantity = (int)$_POST['quantity'];
    $reason = mysqli_real_escape_string($conn, $_POST['reason']);
    
    // Get invoice item details with proper product matching
    $item_sql = "SELECT 
                    ii.id,
                    ii.product_name, 
                    ii.quantity as item_quantity,
                    ii.original_price, 
                    ii.discounted_price,
                    ii.total_price,
                    ii.invoice_id,
                    i.invoice_number,
                    i.total as invoice_total,
                    i.subtotal as invoice_subtotal,
                    p.id as product_id, 
                    p.product_name as db_product_name,
                    p.quantity as current_stock,
                    p.stock_price,
                    p.customer_price
                 FROM invoice_items ii 
                 JOIN invoices i ON ii.invoice_id = i.id 
                 LEFT JOIN products p ON ii.product_name = p.product_name 
                 WHERE ii.id = ?";
    $item_stmt = mysqli_prepare($conn, $item_sql);
    mysqli_stmt_bind_param($item_stmt, 'i', $invoice_item_id);
    mysqli_stmt_execute($item_stmt);
    $item_result = mysqli_stmt_get_result($item_stmt);
    $item_data = mysqli_fetch_assoc($item_result);
    
    if ($item_data) {
        // Validate return quantity
        if ($quantity <= 0 || $quantity > $item_data['item_quantity']) {
            $response = ['success' => false, 'message' => 'Invalid return quantity'];
            header('Content-Type: application/json');
            echo json_encode($response);
            exit;
        }
        
        mysqli_begin_transaction($conn);
        
        try {
            if ($action_type === 'return') {
                // Calculate refund amount
                $refund_amount = ($item_data['discounted_price'] / $item_data['item_quantity']) * $quantity;
                
                // Handle return - add stock back
                if ($item_data['product_id']) {
                    $update_stock_sql = "UPDATE products SET quantity = quantity + ? WHERE id = ?";
                    $update_stmt = mysqli_prepare($conn, $update_stock_sql);
                    mysqli_stmt_bind_param($update_stmt, 'ii', $quantity, $item_data['product_id']);
                    mysqli_stmt_execute($update_stmt);
                    
                    // Log stock activity
                    logStockActivity($conn, $item_data['product_id'], 'STOCK_ADDED_RETURN', $quantity, "Return from invoice: " . $item_data['invoice_number']);
                }
                
                // Update invoice totals
                $new_subtotal = $item_data['invoice_subtotal'] - $refund_amount;
                $new_total = $item_data['invoice_total'] - $refund_amount;
                
                $update_invoice_sql = "UPDATE invoices SET subtotal = ?, total = ? WHERE id = ?";
                $update_invoice_stmt = mysqli_prepare($conn, $update_invoice_sql);
                mysqli_stmt_bind_param($update_invoice_stmt, 'ddi', $new_subtotal, $new_total, $item_data['invoice_id']);
                mysqli_stmt_execute($update_invoice_stmt);
                
                // Update invoice item if partial return
                if ($quantity < $item_data['item_quantity']) {
                    $remaining_quantity = $item_data['item_quantity'] - $quantity;
                    $remaining_total = ($item_data['discounted_price'] / $item_data['item_quantity']) * $remaining_quantity;
                    
                    $update_item_sql = "UPDATE invoice_items SET quantity = ?, total_price = ? WHERE id = ?";
                    $update_item_stmt = mysqli_prepare($conn, $update_item_sql);
                    mysqli_stmt_bind_param($update_item_stmt, 'idi', $remaining_quantity, $remaining_total, $invoice_item_id);
                    mysqli_stmt_execute($update_item_stmt);
                } else {
                    // Remove the invoice item if full return
                    $delete_item_sql = "DELETE FROM invoice_items WHERE id = ?";
                    $delete_item_stmt = mysqli_prepare($conn, $delete_item_sql);
                    mysqli_stmt_bind_param($delete_item_stmt, 'i', $invoice_item_id);
                    mysqli_stmt_execute($delete_item_stmt);
                }
                
                // Log the return
                $log_details = json_encode([
                    'action' => 'RETURN',
                    'invoice_item_id' => $invoice_item_id,
                    'invoice_id' => $item_data['invoice_id'],
                    'invoice_number' => $item_data['invoice_number'],
                    'product_name' => $item_data['product_name'],
                    'quantity_returned' => $quantity,
                    'reason' => $reason,
                    'original_price' => $item_data['original_price'],
                    'discounted_price' => $item_data['discounted_price'],
                    'total_refund' => $refund_amount,
                    'new_invoice_total' => $new_total,
                    'refund_date' => date('Y-m-d H:i:s')
                ]);
                
                // Check if return_exchange_logs table exists, if not create it
                $check_table_sql = "SHOW TABLES LIKE 'return_exchange_logs'";
                $table_result = mysqli_query($conn, $check_table_sql);
                if (mysqli_num_rows($table_result) === 0) {
                    // Create the table
                    $create_table_sql = "CREATE TABLE IF NOT EXISTS `return_exchange_logs` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        `invoice_id` int(11) NOT NULL,
                        `invoice_item_id` int(11) NOT NULL,
                        `action_type` enum('RETURN','EXCHANGE') NOT NULL,
                        `product_name` varchar(255) NOT NULL,
                        `exchange_product_name` varchar(255) DEFAULT NULL,
                        `quantity` int(11) NOT NULL,
                        `exchange_quantity` int(11) DEFAULT NULL,
                        `amount` decimal(10,2) DEFAULT 0.00,
                        `exchange_amount` decimal(10,2) DEFAULT 0.00,
                        `reason` text DEFAULT NULL,
                        `details` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
                        `created_at` timestamp NULL DEFAULT current_timestamp(),
                        PRIMARY KEY (`id`),
                        KEY `invoice_id` (`invoice_id`),
                        KEY `invoice_item_id` (`invoice_item_id`),
                        KEY `action_type` (`action_type`),
                        KEY `created_at` (`created_at`)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
                    mysqli_query($conn, $create_table_sql);
                }
                
                $log_sql = "INSERT INTO return_exchange_logs (invoice_id, invoice_item_id, action_type, product_name, quantity, amount, reason, details, created_at) 
                           VALUES (?, ?, 'RETURN', ?, ?, ?, ?, ?, NOW())";
                $log_stmt = mysqli_prepare($conn, $log_sql);
                mysqli_stmt_bind_param($log_stmt, 'iisidss', $item_data['invoice_id'], $invoice_item_id, $item_data['product_name'], $quantity, $refund_amount, $reason, $log_details);
                mysqli_stmt_execute($log_stmt);
                
                $response = ['success' => true, 'message' => 'Product returned successfully. Stock and invoice updated.', 'refund_amount' => $refund_amount];
                
            } elseif ($action_type === 'exchange') {
                $exchange_product_id = (int)$_POST['exchange_product_id'];
                $exchange_quantity = (int)$_POST['exchange_quantity'];
                
                // Validate exchange quantity
                if ($exchange_quantity <= 0) {
                    throw new Exception('Invalid exchange quantity');
                }
                
                // Get exchange product details
                $exchange_sql = "SELECT * FROM products WHERE id = ?";
                $exchange_stmt = mysqli_prepare($conn, $exchange_sql);
                mysqli_stmt_bind_param($exchange_stmt, 'i', $exchange_product_id);
                mysqli_stmt_execute($exchange_stmt);
                $exchange_result = mysqli_stmt_get_result($exchange_stmt);
                $exchange_product = mysqli_fetch_assoc($exchange_result);
                
                if ($exchange_product) {
                    // Validate stock availability
                    if ($exchange_product['quantity'] < $exchange_quantity) {
                        throw new Exception('Insufficient stock for exchange product');
                    }
                    
                    // Calculate amounts
                    $original_amount = ($item_data['discounted_price'] / $item_data['item_quantity']) * $quantity;
                    $exchange_amount = $exchange_product['customer_price'] * $exchange_quantity;
                    $amount_difference = $exchange_amount - $original_amount;
                    
                    // Add original product back to stock
                    if ($item_data['product_id']) {
                        $return_stock_sql = "UPDATE products SET quantity = quantity + ? WHERE id = ?";
                        $return_stmt = mysqli_prepare($conn, $return_stock_sql);
                        mysqli_stmt_bind_param($return_stmt, 'ii', $quantity, $item_data['product_id']);
                        mysqli_stmt_execute($return_stmt);
                        
                        // Log stock activity for returned product
                        logStockActivity($conn, $item_data['product_id'], 'STOCK_ADDED_EXCHANGE', $quantity, "Exchange return from invoice: " . $item_data['invoice_number']);
                    }
                    
                    // Reduce exchange product stock
                    $exchange_stock_sql = "UPDATE products SET quantity = quantity - ? WHERE id = ?";
                    $exchange_stmt = mysqli_prepare($conn, $exchange_stock_sql);
                    mysqli_stmt_bind_param($exchange_stmt, 'ii', $exchange_quantity, $exchange_product_id);
                    mysqli_stmt_execute($exchange_stmt);
                    
                    // Log stock activity for exchanged product
                    logStockActivity($conn, $exchange_product_id, 'STOCK_REDUCED_EXCHANGE', $exchange_quantity, "Exchange for invoice: " . $item_data['invoice_number']);
                    
                    // Update invoice totals
                    $new_subtotal = $item_data['invoice_subtotal'] - $original_amount + $exchange_amount;
                    $new_total = $item_data['invoice_total'] - $original_amount + $exchange_amount;
                    
                    $update_invoice_sql = "UPDATE invoices SET subtotal = ?, total = ? WHERE id = ?";
                    $update_invoice_stmt = mysqli_prepare($conn, $update_invoice_sql);
                    mysqli_stmt_bind_param($update_invoice_stmt, 'ddi', $new_subtotal, $new_total, $item_data['invoice_id']);
                    mysqli_stmt_execute($update_invoice_stmt);
                    
                    // Update or replace the invoice item
                    if ($quantity < $item_data['item_quantity']) {
                        // Partial exchange - update existing item
                        $remaining_quantity = $item_data['item_quantity'] - $quantity;
                        $remaining_total = ($item_data['discounted_price'] / $item_data['item_quantity']) * $remaining_quantity;
                        
                        $update_item_sql = "UPDATE invoice_items SET quantity = ?, total_price = ? WHERE id = ?";
                        $update_item_stmt = mysqli_prepare($conn, $update_item_sql);
                        mysqli_stmt_bind_param($update_item_stmt, 'idi', $remaining_quantity, $remaining_total, $invoice_item_id);
                        mysqli_stmt_execute($update_item_stmt);
                        
                        // Add new item for exchanged product
                        $add_item_sql = "INSERT INTO invoice_items (invoice_id, product_name, quantity, original_price, discounted_price, total_price, product_category) 
                                        VALUES (?, ?, ?, ?, ?, ?, ?)";
                        $add_item_stmt = mysqli_prepare($conn, $add_item_sql);
                        $exchange_category = $exchange_product['category_id'] ? 'mobile' : 'general'; // Adjust as needed
                        mysqli_stmt_bind_param($add_item_stmt, 'isiddds', $item_data['invoice_id'], $exchange_product['product_name'], $exchange_quantity, $exchange_product['customer_price'], $exchange_product['customer_price'], $exchange_amount, $exchange_category);
                        mysqli_stmt_execute($add_item_stmt);
                    } else {
                        // Full exchange - replace the item
                        $update_item_sql = "UPDATE invoice_items SET 
                                            product_name = ?, 
                                            quantity = ?, 
                                            original_price = ?, 
                                            discounted_price = ?, 
                                            total_price = ?,
                                            product_category = ?
                                            WHERE id = ?";
                        $update_item_stmt = mysqli_prepare($conn, $update_item_sql);
                        $exchange_category = $exchange_product['category_id'] ? 'mobile' : 'general'; // Adjust as needed
                        mysqli_stmt_bind_param($update_item_stmt, 'sidddsi', $exchange_product['product_name'], $exchange_quantity, $exchange_product['customer_price'], $exchange_product['customer_price'], $exchange_amount, $exchange_category, $invoice_item_id);
                        mysqli_stmt_execute($update_item_stmt);
                    }
                    
                    // Log the exchange
                    $log_details = json_encode([
                        'action' => 'EXCHANGE',
                        'invoice_item_id' => $invoice_item_id,
                        'invoice_id' => $item_data['invoice_id'],
                        'invoice_number' => $item_data['invoice_number'],
                        'original_product' => $item_data['product_name'],
                        'exchange_product' => $exchange_product['product_name'],
                        'quantity_returned' => $quantity,
                        'quantity_exchanged' => $exchange_quantity,
                        'original_amount' => $original_amount,
                        'exchange_amount' => $exchange_amount,
                        'amount_difference' => $amount_difference,
                        'new_invoice_total' => $new_total,
                        'reason' => $reason,
                        'exchange_date' => date('Y-m-d H:i:s')
                    ]);
                    
                    $log_sql = "INSERT INTO return_exchange_logs (invoice_id, invoice_item_id, action_type, product_name, exchange_product_name, quantity, exchange_quantity, amount, exchange_amount, reason, details, created_at) 
                               VALUES (?, ?, 'EXCHANGE', ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
                    $log_stmt = mysqli_prepare($conn, $log_sql);
                    mysqli_stmt_bind_param($log_stmt, 'iissiiddss', $item_data['invoice_id'], $invoice_item_id, $item_data['product_name'], $exchange_product['product_name'], $quantity, $exchange_quantity, $original_amount, $exchange_amount, $reason, $log_details);
                    mysqli_stmt_execute($log_stmt);
                    
                    $response = ['success' => true, 'message' => 'Product exchanged successfully. Stock and invoice updated.', 'amount_difference' => $amount_difference];
                } else {
                    throw new Exception('Exchange product not found');
                }
            }
            
            mysqli_commit($conn);
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $response = ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
        }
        
    } else {
        $response = ['success' => false, 'message' => 'Invoice item not found. Please check if the item exists.'];
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// ---- Fetch stock data with new pricing structure ----
$sql = "SELECT i.id, i.invoice_number, i.total, i.payment_method, i.created_at,
               c.name as customer_name, c.phone as customer_phone,
               COUNT(ii.id) as items_count
        FROM invoices i
        LEFT JOIN customers c ON i.customer_id = c.id
        LEFT JOIN invoice_items ii ON i.id = ii.invoice_id
        GROUP BY i.id
        ORDER BY i.id DESC";
$result = mysqli_query($conn, $sql);

$rows = [];
$totalSkus = 0;
$totalUnits = 0;
$totalInvestment = 0.00;
$totalSellable = 0.00;
$totalProfit = 0.00;
$lowStock = [];

if ($result && mysqli_num_rows($result) > 0) {
  while ($r = mysqli_fetch_assoc($result)) {
    $id   = (int)$r['id'];
    $name = (string)$r['customer_name'] ?? 'N/A';
    $phone = $r['customer_phone'] ?? 'N/A';
    $items_count = (int)$r['items_count'];
    $total = number_format((float)$r['total'], 2);
    $payment_method = strtoupper($r['payment_method']);
    $created = date("d M Y, h:i A", strtotime($r['created_at']));

    $rows[] = [
      'id' => $id,
      'invoice_number' => $r['invoice_number'],
      'customer_name' => $name,
      'customer_phone' => $phone,
      'items_count' => $items_count,
      'total' => $total,
      'payment_method' => $payment_method,
      'created_at' => $created
    ];

    $totalSkus++;
  }
}

function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
?>
<!doctype html>
<html lang="en">
<?php include('includes/head.php'); ?>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.dataTables.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .badge-paid { background-color: #28a745; }
    .badge-pending { background-color: #ffc107; color: #212529; }
    .badge-cancelled { background-color: #dc3545; }
    .order-actions { white-space: nowrap; }
    .table-responsive { overflow-x: auto; }
    .electron-print-btn {
        background: #28a745; color: white; border: none; padding: 6px 12px;
        border-radius: 4px; cursor: pointer; font-size: 12px; font-weight: bold;
    }
    .electron-print-btn:hover { background: #218838; }
    .electron-print-btn:disabled { background: #6c757d; cursor: not-allowed; }
    .btn-view-details { font-size: 12px; padding: 4px 8px; }
    .return-exchange-btn { font-size: 11px; padding: 3px 6px; margin: 1px; }
    .action-buttons { display: flex; gap: 2px; flex-wrap: wrap; }
    .refund-amount { color: #dc3545; font-weight: bold; }
    .exchange-difference { color: #fd7e14; font-weight: bold; }
</style>
<body data-sidebar="dark">
<?php include('includes/pre-loader.php'); ?>
<div id="layout-wrapper">
<?php include('includes/topbar.php'); ?>
    <div class="vertical-menu">
        <div data-simplebar class="h-100">
            <?php include('includes/sidebar.php'); ?>
        </div>
    </div>
    <div class="main-content">
        <div class="page-content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-xl-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center mb-4">
                                    <h4 class="card-title mb-0">All Orders</h4>
                                    <div>
                                        <a href="sales.php" class="btn btn-primary">
                                            <i class="fas fa-plus me-1"></i> New Sale
                                        </a>
                                    </div>
                                </div>
                                <?php if (isset($_GET['msg'])): ?>
                                    <div class="alert alert-<?php echo htmlspecialchars($_GET['type'] ?? 'info'); ?> alert-dismissible fade show" role="alert">
                                        <?php echo htmlspecialchars($_GET['msg']); ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                    </div>
                                <?php endif; ?>

                                <!-- Order Statistics -->
                                <div class="row mb-4">
                                    <div class="col-md-3">
                                        <div class="card bg-primary text-white">
                                            <div class="card-body">
                                                <div class="d-flex align-items-center">
                                                    <div class="flex-grow-1">
                                                        <h4 class="mb-0">
                                                            <?php
                                                            $total_orders_sql = "SELECT COUNT(*) as total FROM invoices";
                                                            $total_orders_result = mysqli_query($conn, $total_orders_sql);
                                                            $total_orders = mysqli_fetch_assoc($total_orders_result)['total'];
                                                            echo $total_orders;
                                                            ?>
                                                        </h4>
                                                        <p class="mb-0">Total Orders</p>
                                                    </div>
                                                    <div class="flex-shrink-0">
                                                        <i class="fas fa-shopping-cart fa-2x"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="card bg-success text-white">
                                            <div class="card-body">
                                                <div class="d-flex align-items-center">
                                                    <div class="flex-grow-1">
                                                        <h4 class="mb-0">
                                                            ₹<?php
                                                            $total_revenue_sql = "SELECT COALESCE(SUM(total), 0) as revenue FROM invoices";
                                                            $total_revenue_result = mysqli_query($conn, $total_revenue_sql);
                                                            $total_revenue = mysqli_fetch_assoc($total_revenue_result)['revenue'];
                                                            echo number_format($total_revenue, 2);
                                                            ?>
                                                        </h4>
                                                        <p class="mb-0">Total Revenue</p>
                                                    </div>
                                                    <div class="flex-shrink-0">
                                                        <i class="fas fa-rupee-sign fa-2x"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="card bg-info text-white">
                                            <div class="card-body">
                                                <div class="d-flex align-items-center">
                                                    <div class="flex-grow-1">
                                                        <h4 class="mb-0">
                                                            <?php
                                                            $today_orders_sql = "SELECT COUNT(*) as total FROM invoices WHERE DATE(created_at) = CURDATE()";
                                                            $today_orders_result = mysqli_query($conn, $today_orders_sql);
                                                            $today_orders = mysqli_fetch_assoc($today_orders_result)['total'];
                                                            echo $today_orders;
                                                            ?>
                                                        </h4>
                                                        <p class="mb-0">Today's Orders</p>
                                                    </div>
                                                    <div class="flex-shrink-0">
                                                        <i class="fas fa-calendar-day fa-2x"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="card bg-warning text-dark">
                                            <div class="card-body">
                                                <div class="d-flex align-items-center">
                                                    <div class="flex-grow-1">
                                                        <h4 class="mb-0">
                                                            ₹<?php
                                                            $today_revenue_sql = "SELECT COALESCE(SUM(total), 0) as revenue FROM invoices WHERE DATE(created_at) = CURDATE()";
                                                            $today_revenue_result = mysqli_query($conn, $today_revenue_sql);
                                                            $today_revenue = mysqli_fetch_assoc($today_revenue_result)['revenue'];
                                                            echo number_format($today_revenue, 2);
                                                            ?>
                                                        </h4>
                                                        <p class="mb-0">Today's Revenue</p>
                                                    </div>
                                                    <div class="flex-shrink-0">
                                                        <i class="fas fa-chart-line fa-2x"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Bulk Actions Form -->
                                <form method="POST" id="bulkActionForm" class="mb-3">
                                    <div class="row align-items-center">
                                        <div class="col-md-4">
                                            <select name="bulk_action" class="form-select" id="bulkAction">
                                                <option value="">Bulk Actions</option>
                                                <option value="delete">Delete Selected</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <button type="submit" class="btn btn-outline-primary" id="applyBulkAction" disabled>Apply</button>
                                        </div>
                                        <div class="col-md-6 text-end">
                                            <div class="btn-group">
                                                <button type="button" class="btn btn-outline-secondary" onclick="selectAllOrders()">
                                                    <i class="fas fa-check-square me-1"></i> Select All
                                                </button>
                                                <button type="button" class="btn btn-outline-secondary" onclick="deselectAllOrders()">
                                                    <i class="fas fa-square me-1"></i> Deselect All
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </form>

                                <div class="table-responsive">
                                    <table id="ordersTable" class="table table-bordered table-striped" style="width:100%">
                                        <thead>
                                            <tr>
                                                <th width="30"><input type="checkbox" id="selectAll"></th>
                                                <th>#</th>
                                                <th>Order ID</th>
                                                <th>Customer</th>
                                                <th>Phone</th>
                                                <th>Items</th>
                                                <th>Total (₹)</th>
                                                <th>Payment</th>
                                                <th>Date</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            if (!empty($rows)) {
                                                $count = 1;
                                                foreach ($rows as $r) {
                                                    // Safely escape values
                                                    $invoiceId = (int)$r['id'];
                                                    $invoiceNumber = htmlspecialchars($r['invoice_number'], ENT_QUOTES, 'UTF-8');
                                                    $custName = h($r['customer_name']);
                                                    $custPhone = h($r['customer_phone']);
                                                    $itemsCount = (int)$r['items_count'];
                                                    $totalStr = $r['total'];
                                                    $paymentMethod = h($r['payment_method']);
                                                    $createdAt = h($r['created_at']);

                                                    echo "<tr>
                                                            <td><input type='checkbox' name='selected_orders[]' value='{$invoiceId}' class='order-checkbox'></td>
                                                            <td>{$count}</td>
                                                            <td><strong>{$invoiceNumber}</strong></td>
                                                            <td>{$custName}</td>
                                                            <td>{$custPhone}</td>
                                                            <td><span class='badge bg-primary'>{$itemsCount} items</span></td>
                                                            <td><strong>₹{$totalStr}</strong></td>
                                                            <td><span class='badge bg-info text-dark'>{$paymentMethod}</span></td>
                                                            <td>{$createdAt}</td>
                                                            <td class='order-actions'>
                                                                <button onclick='printInvoice(\"{$invoiceNumber}\")' class='btn btn-outline-dark btn-sm electron-print-btn' title='Print'>
                                                                    <i class='fas fa-print'></i>
                                                                </button>
                                                                <button onclick='viewOrderDetails({$invoiceId})' class='btn btn-outline-info btn-sm btn-view-details' title='View Details'>
                                                                    <i class='fas fa-eye'></i>
                                                                </button>
                                                                <a href='orders.php?send_whatsapp={$invoiceId}' target='_blank' class='btn btn-success btn-sm' title='Send Invoice via WhatsApp'>
                                                                    <i class='fab fa-whatsapp'></i>
                                                                </a>
                                                                <a href='orders.php?delete_id={$invoiceId}' class='btn btn-outline-danger btn-sm' onclick='return confirmDelete(\"Delete this order?\");' title='Delete'>
                                                                    <i class='fas fa-trash'></i>
                                                                </a>
                                                            </td>
                                                          </tr>";
                                                    $count++;
                                                }
                                            } else {
                                                echo "<tr><td colspan='10' class='text-center py-4'>No orders found</td></tr>";
                                            }
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include('includes/footer.php'); ?>
    </div>
</div>

<!-- BOOTSTRAP MODAL FOR ORDER DETAILS -->
<div class="modal fade" id="orderDetailsModal" tabindex="-1" aria-labelledby="orderDetailsLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="orderDetailsLabel">Order Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="orderDetailsBody">
        <!-- Filled by JS -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- RETURN/EXCHANGE MODAL -->
<div class="modal fade" id="returnExchangeModal" tabindex="-1" aria-labelledby="returnExchangeLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="returnExchangeLabel">Return/Exchange Product</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="returnExchangeForm">
          <input type="hidden" id="invoice_item_id" name="invoice_item_id">
          <input type="hidden" name="action_type" id="action_type">
          
          <div class="row mb-3">
            <div class="col-md-6">
              <label class="form-label">Product</label>
              <input type="text" id="product_name" class="form-control" readonly>
            </div>
            <div class="col-md-6">
              <label class="form-label">Original Quantity</label>
              <input type="text" id="original_quantity" class="form-control" readonly>
            </div>
          </div>
          
          <div class="row mb-3">
            <div class="col-md-6">
              <label class="form-label">Return Quantity *</label>
              <input type="number" id="return_quantity" name="quantity" class="form-control" min="1" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Reason *</label>
              <input type="text" name="reason" class="form-control" placeholder="Reason for return/exchange" required>
            </div>
          </div>
          
          <div id="exchangeSection" style="display: none;">
            <div class="row mb-3">
              <div class="col-md-6">
                <label class="form-label">Exchange Product *</label>
                <select id="exchange_product_id" name="exchange_product_id" class="form-select select2">
                  <option value="">Select Product</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Exchange Quantity *</label>
                <input type="number" id="exchange_quantity" name="exchange_quantity" class="form-control" min="1" value="1">
              </div>
            </div>
            <div class="row mb-3">
              <div class="col-md-12">
                <div id="exchangeDetails" class="alert alert-info">
                  <!-- Exchange details will be shown here -->
                </div>
              </div>
            </div>
          </div>
          
          <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <span id="actionWarning">This action cannot be undone. Stock will be updated accordingly.</span>
          </div>
          
          <div id="financialImpact" class="alert alert-info" style="display: none;">
            <i class="fas fa-calculator me-2"></i>
            <span id="impactDetails">Financial impact details will be shown here.</span>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="submitReturnExchange">Process</button>
      </div>
    </div>
  </div>
</div>

<?php include('includes/rightbar.php'); ?>
<?php include('includes/scripts.php'); ?>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
// Print Invoice
function printInvoice(invoiceNumber) {
    const btn = event.target.closest('button');
    const original = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>'; btn.disabled = true;
    if (window.electronAPI) {
        window.electronAPI.printInvoice(invoiceNumber).then(r => {
            showNotification(r.success ? 'Printed!' : 'Print failed', r.success ? 'success' : 'error');
            setTimeout(() => { btn.innerHTML = original; btn.disabled = false; }, 1500);
        }).catch(() => fallbackPrint(invoiceNumber, btn, original));
    } else {
        fallbackPrint(invoiceNumber, btn, original);
    }
}
function fallbackPrint(invoiceNumber, btn, original) {
    const win = window.open(`invoice_print.php?invoice_id=${invoiceNumber}&auto=1`, '_self');
}

function showNotification(msg, type = 'info') {
    const n = document.createElement('div');
    n.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    n.style.cssText = 'top:20px; right:20px; z-index:10000; min-width:300px;';
    n.innerHTML = `${msg}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
    document.body.appendChild(n);
    setTimeout(() => n.remove(), 3000);
}
function confirmDelete(msg) {
    return window.electronAPI?.showConfirm?.(msg) ?? confirm(msg);
}

// VIEW ORDER DETAILS IN MODAL
function viewOrderDetails(invoiceId) {
    fetch(`get_order_details.php?invoice_id=${invoiceId}`)
        .then(r => r.json())
        .then(data => {
            if (!data.success) throw new Error(data.message || 'Failed');
            const items = data.items;
            let html = `
                <div class="table-responsive">
                    <table class="table table-sm table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th>Product</th>
                                <th>Qty</th>
                                <th>Price</th>
                                <th>Disc</th>
                                <th>Total</th>
                               
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>`;
            items.forEach(it => {
                const ident = [];
                if (it.imei_list?.length) ident.push(...it.imei_list.map((v,i) => `IMEI ${i+1}: ${v}`));
                if (it.serial_list?.length) ident.push(...it.serial_list.map((v,i) => `Serial ${i+1}: ${v}`));
                
                html += `<tr>
                    <td><strong>${escapeHtml(it.product_name)}</strong><br><small class="text-muted">${it.product_category || ''}</small></td>
                    <td class="text-center">${it.quantity}</td>
                    <td>₹${Number(it.original_price).toFixed(2)}</td>
                    <td>${it.discount_percentage > 0 ? it.discount_percentage + '%' : '-'}</td>
                    <td>₹${Number(it.total_price).toFixed(2)}</td>
                    
                    <td>
                        <div class="action-buttons">
                            <button onclick="initiateReturn(${it.id}, '${escapeHtml(it.product_name)}', ${it.quantity}, ${it.discounted_price})" 
                                    class="btn btn-warning btn-sm return-exchange-btn" title="Return">
                                <i class="fas fa-undo"></i> Return
                            </button>
                            <button onclick="initiateExchange(${it.id}, '${escapeHtml(it.product_name)}', ${it.quantity}, ${it.discounted_price})" 
                                    class="btn btn-info btn-sm return-exchange-btn" title="Exchange">
                                <i class="fas fa-exchange-alt"></i> Exchange
                            </button>
                        </div>
                    </td>
                </tr>`;
            });
            html += `</tbody></table></div>`;
            document.getElementById('orderDetailsBody').innerHTML = html;
            new bootstrap.Modal(document.getElementById('orderDetailsModal')).show();
        })
        .catch(err => {
            showNotification('Error loading details: ' + err.message, 'danger');
        });
}

// RETURN/EXCHANGE FUNCTIONS
function initiateReturn(invoiceItemId, productName, maxQuantity, discountedPrice) {
    document.getElementById('invoice_item_id').value = invoiceItemId;
    document.getElementById('action_type').value = 'return';
    document.getElementById('product_name').value = productName;
    document.getElementById('original_quantity').value = maxQuantity;
    document.getElementById('return_quantity').max = maxQuantity;
    document.getElementById('return_quantity').value = 1;
    document.getElementById('exchangeSection').style.display = 'none';
    document.getElementById('actionWarning').textContent = 'Product will be returned and stock will be updated. Refund amount will be calculated.';
    document.getElementById('returnExchangeLabel').textContent = 'Return Product';
    document.getElementById('financialImpact').style.display = 'block';
    
    // Store discounted price for calculations
    document.getElementById('return_quantity').setAttribute('data-unit-price', discountedPrice / maxQuantity);
    
    updateFinancialImpact();
    new bootstrap.Modal(document.getElementById('returnExchangeModal')).show();
}

function initiateExchange(invoiceItemId, productName, maxQuantity, discountedPrice) {
    document.getElementById('invoice_item_id').value = invoiceItemId;
    document.getElementById('action_type').value = 'exchange';
    document.getElementById('product_name').value = productName;
    document.getElementById('original_quantity').value = maxQuantity;
    document.getElementById('return_quantity').max = maxQuantity;
    document.getElementById('return_quantity').value = 1;
    document.getElementById('exchangeSection').style.display = 'block';
    document.getElementById('actionWarning').textContent = 'Original product will be returned to stock and exchange product will be deducted from stock.';
    document.getElementById('returnExchangeLabel').textContent = 'Exchange Product';
    document.getElementById('financialImpact').style.display = 'block';
    
    // Store discounted price for calculations
    document.getElementById('return_quantity').setAttribute('data-unit-price', discountedPrice / maxQuantity);
    
    // Load products for exchange
    loadExchangeProducts();
    updateFinancialImpact();
    new bootstrap.Modal(document.getElementById('returnExchangeModal')).show();
}

function loadExchangeProducts() {
    fetch('get_products.php')
        .then(r => r.json())
        .then(data => {
            const select = document.getElementById('exchange_product_id');
            select.innerHTML = '<option value="">Select Product</option>';
            if (data.success && data.products) {
                data.products.forEach(product => {
                    const option = document.createElement('option');
                    option.value = product.id;
                    option.textContent = `${product.product_name} (Stock: ${product.quantity}) - ₹${product.customer_price}`;
                    option.setAttribute('data-price', product.customer_price);
                    select.appendChild(option);
                });
            }
            $('#exchange_product_id').select2();
        })
        .catch(err => {
            console.error('Error loading products:', err);
        });
}

// Update financial impact when quantities change
document.addEventListener('DOMContentLoaded', function() {
    const exchangeSelect = document.getElementById('exchange_product_id');
    const exchangeQty = document.getElementById('exchange_quantity');
    const returnQty = document.getElementById('return_quantity');

    if (exchangeSelect) exchangeSelect.addEventListener('change', updateFinancialImpact);
    if (exchangeQty) exchangeQty.addEventListener('input', updateFinancialImpact);
    if (returnQty) returnQty.addEventListener('input', updateFinancialImpact);

    // Also update exchange details when product/qty changes
    if (exchangeSelect) exchangeSelect.addEventListener('change', updateExchangeDetails);
    if (exchangeQty) exchangeQty.addEventListener('input', updateExchangeDetails);
});

function updateFinancialImpact() {
    const actionType = document.getElementById('action_type').value;
    const returnQuantity = parseInt(document.getElementById('return_quantity').value) || 0;
    const unitPrice = parseFloat(document.getElementById('return_quantity').getAttribute('data-unit-price')) || 0;
    
    if (actionType === 'return') {
        const refundAmount = unitPrice * returnQuantity;
        document.getElementById('impactDetails').innerHTML = `
            <strong>Refund Amount:</strong> ₹${refundAmount.toFixed(2)}
        `;
    } else if (actionType === 'exchange') {
        const exchangeProductSelect = document.getElementById('exchange_product_id');
        const exchangeProduct = exchangeProductSelect.options[exchangeProductSelect.selectedIndex];
        const exchangeQuantity = parseInt(document.getElementById('exchange_quantity').value) || 0;
        
        const originalAmount = unitPrice * returnQuantity;
        let exchangeAmount = 0;
        
        if (exchangeProduct && exchangeProduct.value) {
            exchangeAmount = parseFloat(exchangeProduct.getAttribute('data-price')) * exchangeQuantity;
        }
        
        const amountDifference = exchangeAmount - originalAmount;
        const differenceText = amountDifference >= 0 ? 
            `Additional payment: <span class="exchange-difference">₹${amountDifference.toFixed(2)}</span>` :
            `Refund amount: <span class="refund-amount">₹${Math.abs(amountDifference).toFixed(2)}</span>`;
        
        document.getElementById('impactDetails').innerHTML = `
            <strong>Financial Impact:</strong><br>
            Original Product Value: ₹${originalAmount.toFixed(2)}<br>
            Exchange Product Value: ₹${exchangeAmount.toFixed(2)}<br>
            ${differenceText}
        `;
    }
}

// Update exchange details when product or quantity changes
function updateExchangeDetails() {
    if (document.getElementById('action_type').value !== 'exchange') return;
    
    const exchangeProductSelect = document.getElementById('exchange_product_id');
    const exchangeProduct = exchangeProductSelect.options[exchangeProductSelect.selectedIndex];
    const exchangeQuantity = parseInt(document.getElementById('exchange_quantity').value) || 0;
    
    if (exchangeProduct && exchangeProduct.value) {
        const exchangePrice = parseFloat(exchangeProduct.getAttribute('data-price'));
        const totalExchangeAmount = exchangePrice * exchangeQuantity;
        
        document.getElementById('exchangeDetails').innerHTML = `
            <strong>Exchange Details:</strong><br>
            Product: ${exchangeProduct.textContent}<br>
            Quantity: ${exchangeQuantity}<br>
            Unit Price: ₹${exchangePrice.toFixed(2)}<br>
            Total Amount: ₹${totalExchangeAmount.toFixed(2)}
        `;
    } else {
        document.getElementById('exchangeDetails').innerHTML = 'Please select an exchange product';
    }
    
    updateFinancialImpact();
}

// Submit return/exchange form
document.getElementById('submitReturnExchange').addEventListener('click', function() {
    const form = document.getElementById('returnExchangeForm');
    const formData = new FormData(form);
    
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const actionType = document.getElementById('action_type').value;
    if (actionType === 'exchange') {
        const exchangeProduct = document.getElementById('exchange_product_id').value;
        const exchangeQuantity = parseInt(document.getElementById('exchange_quantity').value) || 0;
        
        if (!exchangeProduct) {
            showNotification('Please select an exchange product', 'warning');
            return;
        }
        if (exchangeQuantity <= 0) {
            showNotification('Please enter valid exchange quantity', 'warning');
            return;
        }
    }
    
    this.disabled = true;
    this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    
    fetch('orders.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            let successMsg = data.message;
            if (data.refund_amount) {
                successMsg += ` Refund amount: ₹${data.refund_amount.toFixed(2)}`;
            }
            if (data.amount_difference) {
                const diffText = data.amount_difference >= 0 ? 
                    `Additional payment: ₹${data.amount_difference.toFixed(2)}` : 
                    `Refund amount: ₹${Math.abs(data.amount_difference).toFixed(2)}`;
                successMsg += ` ${diffText}`;
            }
            
            showNotification(successMsg, 'success');
            bootstrap.Modal.getInstance(document.getElementById('returnExchangeModal')).hide();
            // Refresh the order details modal if open
            const orderModal = bootstrap.Modal.getInstance(document.getElementById('orderDetailsModal'));
            if (orderModal) {
                orderModal.hide();
            }
            // Refresh the page to show updated totals
            setTimeout(() => location.reload(), 1500);
        } else {
            showNotification(data.message, 'danger');
        }
    })
    .catch(err => {
        showNotification('Error processing request: ' + err.message, 'danger');
    })
    .finally(() => {
        this.disabled = false;
        this.innerHTML = 'Process';
    });
});

function escapeHtml(str) {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}

// DataTable + Bulk Actions
$(document).ready(function () {
    const table = $('#ordersTable').DataTable({
        pageLength: 25,
        dom: 'Bfrtip',
        buttons: ['excel', 'pdf', 'print'],
        columnDefs: [{ orderable: false, targets: [0, 9] }],
        order: [[1, 'desc']]
    });

    $('#selectAll').on('click', function() {
        $('.order-checkbox').prop('checked', this.checked);
        updateBulk();
    });
    $('.order-checkbox').on('change', updateBulk);
    function updateBulk() {
        const checked = $('.order-checkbox:checked').length;
        $('#applyBulkAction').prop('disabled', checked === 0);
        $('#selectAll').prop('checked', checked === $('.order-checkbox').length);
    }

    $('#bulkActionForm').on('submit', function(e) {
        const action = $('#bulkAction').val();
        const count = $('.order-checkbox:checked').length;
        if (!action || count === 0) {
            e.preventDefault();
            showNotification('Select action and orders', 'warning');
            return;
        }
        if (action === 'delete' && !confirmDelete(`Delete ${count} order(s)?`)) {
            e.preventDefault();
        }
    });
});

function selectAllOrders() { $('.order-checkbox').prop('checked', true); $('#selectAll').prop('checked', true); updateBulk(); }
function deselectAllOrders() { $('.order-checkbox').prop('checked', false); $('#selectAll').prop('checked', false); updateBulk(); }
</script>
</body>
</html>
