<?php
// view_product.php - Product Details Page

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../../assets/db_connect.php';
require_once '../../includes/header.php';
require_once '../../includes/sidebar.php';

if (!isset($_SESSION['user']['id']) || !isset($_SESSION['user']['shop_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

$user = $_SESSION['user'];
$user_id = $user['id'];
$shop_id = $user['shop_id'];
$user_role = $user['role'] ?? 'cashier';

// Check if product ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: list_product.php?error=Invalid product ID");
    exit();
}

$product_id = intval($_GET['id']);

// Get product details
$sql = "SELECT 
            p.*,
            s.name as shop_name,
            COALESCE(ps.total_qty, 0) as current_stock,
            COALESCE(ps.batch_count, 0) as batch_count,
            ps.earliest_expiry,
            ps.latest_expiry,
            u.fullname as created_by_name
        FROM products p
        LEFT JOIN shops s ON p.shop_id = s.id
        LEFT JOIN product_stock_view ps ON p.id = ps.product_id
        LEFT JOIN users u ON p.shop_id = u.shop_id
        WHERE p.id = ? 
        AND (p.shop_id = ? OR ? = 'admin')";

$stmt = $pdo->prepare($sql);
$params = [$product_id, $shop_id, $user_role];
$stmt->execute($params);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    header("Location: list_product.php?error=Product not found or access denied");
    exit();
}

// Get product batches
$batch_sql = "SELECT 
                pb.*,
                s.name as supplier_name,
                bs.current_qty,
                DATEDIFF(pb.expiry_date, CURDATE()) as days_to_expiry
              FROM product_batches pb
              LEFT JOIN suppliers s ON pb.supplier_id = s.id
              LEFT JOIN batch_stock_view bs ON pb.id = bs.batch_id
              WHERE pb.product_id = ?
              AND pb.shop_id = ?
              ORDER BY pb.expiry_date ASC, pb.created_at DESC";

$batch_stmt = $pdo->prepare($batch_sql);
$batch_stmt->execute([$product_id, $product['shop_id']]);
$batches = $batch_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get recent purchases for this product
$purchase_sql = "SELECT 
                    pu.id,
                    pu.invoice_no,
                    pu.purchase_date,
                    pu.total,
                    pl.qty,
                    pl.cost_price,
                    s.name as supplier_name,
                    u.fullname as created_by_name
                 FROM purchases pu
                 JOIN purchase_lines pl ON pu.id = pl.purchase_id
                 JOIN product_batches pb ON pl.batch_id = pb.id
                 LEFT JOIN suppliers s ON pu.supplier_id = s.id
                 LEFT JOIN users u ON pu.created_by = u.id
                 WHERE pb.product_id = ?
                 AND pu.shop_id = ?
                 ORDER BY pu.purchase_date DESC
                 LIMIT 10";

$purchase_stmt = $pdo->prepare($purchase_sql);
$purchase_stmt->execute([$product_id, $product['shop_id']]);
$purchases = $purchase_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get recent sales for this product
$sale_sql = "SELECT 
                sl.sale_id,
                sa.invoice_no,
                sa.sale_date,
                sl.qty,
                sl.unit_price,
                sl.line_total,
                c.name as customer_name,
                u.fullname as created_by_name
             FROM sale_lines sl
             JOIN sales sa ON sl.sale_id = sa.id
             LEFT JOIN customers c ON sa.customer_id = c.id
             LEFT JOIN users u ON sa.created_by = u.id
             WHERE sl.product_id = ?
             AND sa.shop_id = ?
             ORDER BY sa.sale_date DESC
             LIMIT 10";

$sale_stmt = $pdo->prepare($sale_sql);
$sale_stmt->execute([$product_id, $product['shop_id']]);
$sales = $sale_stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate stock statistics
$total_batch_value = 0;
$expiring_soon_count = 0;
$expired_count = 0;
$low_stock_batches = 0;

foreach ($batches as $batch) {
    $batch_value = $batch['current_qty'] * $batch['cost_price'];
    $total_batch_value += $batch_value;
    
    if ($batch['days_to_expiry'] < 0) {
        $expired_count++;
    } elseif ($batch['days_to_expiry'] <= 30) {
        $expiring_soon_count++;
    }
    
    if ($batch['current_qty'] <= 20) {
        $low_stock_batches++;
    }
}
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <!-- Header with Back Button -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="text-success mb-0">
                <i class="fas fa-eye"></i> Product Details
            </h3>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb bg-transparent p-0">
                    <li class="breadcrumb-item"><a href="list_product.php">Products</a></li>
                    <li class="breadcrumb-item active"><?= htmlspecialchars($product['name']) ?></li>
                </ol>
            </nav>
        </div>
        <div>
            <a href="../list_products.php" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> Back to List
            </a>
            <a href="edit_product.php?id=<?= $product_id ?>" class="btn btn-warning">
                <i class="fas fa-edit"></i> Edit
            </a>
        </div>
    </div>

    <!-- Product Summary Card -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">
                        <i class="fas fa-capsules"></i> Product Information
                        <?php if($product['is_active'] == 0): ?>
                        <span class="badge badge-danger ml-2">Inactive</span>
                        <?php endif; ?>
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <!-- Left Column - Basic Info -->
                        <div class="col-md-6">
                            <h4 class="text-success"><?= htmlspecialchars($product['name']) ?></h4>
                            <?php if(!empty($product['generic_name'])): ?>
                            <p class="text-muted">
                                <i class="fas fa-tag"></i> <?= htmlspecialchars($product['generic_name']) ?>
                            </p>
                            <?php endif; ?>
                            
                            <div class="row mt-3">
                                <div class="col-md-6">
                                    <p><strong>SKU:</strong> <?= htmlspecialchars($product['sku'] ?? 'N/A') ?></p>
                                    <p><strong>Product ID:</strong> <?= $product['id'] ?></p>
                                    <p><strong>Category:</strong> 
                                        <span class="badge badge-secondary"><?= htmlspecialchars($product['category'] ?? 'Uncategorized') ?></span>
                                    </p>
                                    <p><strong>Unit:</strong> <?= htmlspecialchars($product['unit']) ?></p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>Shop:</strong> <?= htmlspecialchars($product['shop_name']) ?></p>
                                    <p><strong>VAT:</strong> <?= $product['vat_percent'] ?>%</p>
                                    <p><strong>Status:</strong> 
                                        <span class="badge <?= $product['is_active'] ? 'badge-success' : 'badge-danger' ?>">
                                            <?= $product['is_active'] ? 'Active' : 'Inactive' ?>
                                        </span>
                                    </p>
                                    <p><strong>Created:</strong> <?= date('M d, Y', strtotime($product['created_at'])) ?></p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Right Column - Pricing -->
                        <div class="col-md-6">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h5 class="card-title">Pricing Information</h5>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="text-center p-3">
                                                <h6 class="text-muted">Buying Price</h6>
                                                <h3 class="text-primary"><?= number_format($product['buying_price'], 2) ?></h3>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="text-center p-3">
                                                <h6 class="text-muted">Selling Price</h6>
                                                <h3 class="text-success"><?= number_format($product['selling_price'], 2) ?></h3>
                                            </div>
                                        </div>
                                    </div>
                                    <?php if($product['buying_price'] > 0 && $product['selling_price'] > 0): ?>
                                    <?php 
                                        $margin = $product['selling_price'] - $product['buying_price'];
                                        $margin_percent = $product['buying_price'] > 0 ? ($margin / $product['buying_price']) * 100 : 0;
                                    ?>
                                    <div class="text-center mt-2">
                                        <small class="text-muted">
                                            Margin: <?= number_format($margin, 2) ?> 
                                            (<?= number_format($margin_percent, 1) ?>%)
                                        </small>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Stock Information Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body text-center">
                    <h6 class="card-title">Current Stock</h6>
                    <h2 class="mb-0"><?= $product['current_stock'] ?></h2>
                    <small><?= htmlspecialchars($product['unit']) ?></small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card <?= $product['batch_count'] > 0 ? 'bg-success' : 'bg-secondary' ?> text-white">
                <div class="card-body text-center">
                    <h6 class="card-title">Active Batches</h6>
                    <h2 class="mb-0"><?= $product['batch_count'] ?></h2>
                    <small>Total Batches</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card <?= $expiring_soon_count > 0 ? 'bg-warning' : 'bg-light' ?>">
                <div class="card-body text-center">
                    <h6 class="card-title">Expiring Soon</h6>
                    <h2 class="mb-0"><?= $expiring_soon_count ?></h2>
                    <small>Within 30 days</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-dark text-white">
                <div class="card-body text-center">
                    <h6 class="card-title">Stock Value</h6>
                    <h4 class="mb-0"><?= number_format($total_batch_value, 2) ?></h4>
                    <small>Total Value</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Batches Section -->
    <div class="card mb-4">
        <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-boxes"></i> Product Batches</h5>
            <a href="add_purchase.php?product_id=<?= $product_id ?>" class="btn btn-sm btn-success">
                <i class="fas fa-plus"></i> Add New Batch
            </a>
        </div>
        <div class="card-body">
            <?php if(empty($batches)): ?>
            <div class="text-center py-4 text-muted">
                <i class="fas fa-box-open fa-2x mb-2"></i>
                <p>No batches found for this product.</p>
                <a href="add_purchase.php?product_id=<?= $product_id ?>" class="btn btn-sm btn-primary">
                    <i class="fas fa-plus"></i> Add First Batch
                </a>
            </div>
            <?php else: ?>
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead class="thead-light">
                        <tr>
                            <th>Batch No</th>
                            <th>Expiry Date</th>
                            <th>Quantity</th>
                            <th>Cost Price</th>
                            <th>Sell Price</th>
                            <th>Supplier</th>
                            <th>Status</th>
                            <th>Days Left</th>
                            <th>Created</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($batches as $batch): 
                            $is_expired = $batch['days_to_expiry'] < 0;
                            $expiring_soon = $batch['days_to_expiry'] <= 30 && $batch['days_to_expiry'] >= 0;
                            $low_stock = $batch['current_qty'] <= 20;
                        ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($batch['batch_no']) ?></strong></td>
                            <td><?= date('M d, Y', strtotime($batch['expiry_date'])) ?></td>
                            <td class="text-center">
                                <span class="badge <?= $low_stock ? 'badge-warning' : 'badge-info' ?> p-2">
                                    <?= $batch['current_qty'] ?>
                                </span>
                            </td>
                            <td class="text-right"><?= number_format($batch['cost_price'], 2) ?></td>
                            <td class="text-right"><?= number_format($batch['sell_price'], 2) ?></td>
                            <td><?= htmlspecialchars($batch['supplier_name'] ?? 'N/A') ?></td>
                            <td>
                                <?php if($batch['is_active'] == 0): ?>
                                <span class="badge badge-danger">Inactive</span>
                                <?php elseif($is_expired): ?>
                                <span class="badge badge-danger">Expired</span>
                                <?php elseif($expiring_soon): ?>
                                <span class="badge badge-warning">Expiring Soon</span>
                                <?php else: ?>
                                <span class="badge badge-success">Active</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <?php if($is_expired): ?>
                                <span class="text-danger">Expired</span>
                                <?php else: ?>
                                <?= $batch['days_to_expiry'] ?> days
                                <?php endif; ?>
                            </td>
                            <td><?= date('M d, Y', strtotime($batch['created_at'])) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Purchase History -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-shopping-cart"></i> Recent Purchases</h5>
                </div>
                <div class="card-body">
                    <?php if(empty($purchases)): ?>
                    <div class="text-center py-3 text-muted">
                        <i class="fas fa-receipt fa-lg mb-2"></i>
                        <p>No purchase history found.</p>
                    </div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Invoice</th>
                                    <th>Date</th>
                                    <th>Qty</th>
                                    <th>Cost</th>
                                    <th>Supplier</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($purchases as $purchase): ?>
                                <tr>
                                    <td><?= htmlspecialchars($purchase['invoice_no']) ?></td>
                                    <td><?= date('M d', strtotime($purchase['purchase_date'])) ?></td>
                                    <td><?= $purchase['qty'] ?></td>
                                    <td><?= number_format($purchase['cost_price'], 2) ?></td>
                                    <td><?= htmlspecialchars($purchase['supplier_name'] ?? 'N/A') ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="text-center mt-2">
                        <a href="list_purchase.php?product_id=<?= $product_id ?>" class="btn btn-sm btn-outline-primary">
                            View All Purchases
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Sales History -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0"><i class="fas fa-chart-line"></i> Recent Sales</h5>
                </div>
                <div class="card-body">
                    <?php if(empty($sales)): ?>
                    <div class="text-center py-3 text-muted">
                        <i class="fas fa-chart-bar fa-lg mb-2"></i>
                        <p>No sales history found.</p>
                    </div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Invoice</th>
                                    <th>Date</th>
                                    <th>Qty</th>
                                    <th>Price</th>
                                    <th>Customer</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($sales as $sale): ?>
                                <tr>
                                    <td><?= htmlspecialchars($sale['invoice_no']) ?></td>
                                    <td><?= date('M d H:i', strtotime($sale['sale_date'])) ?></td>
                                    <td><?= $sale['qty'] ?></td>
                                    <td><?= number_format($sale['unit_price'], 2) ?></td>
                                    <td><?= htmlspecialchars($sale['customer_name'] ?? 'Walk-in') ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="text-center mt-2">
                        <a href="list_sales.php?product_id=<?= $product_id ?>" class="btn btn-sm btn-outline-success">
                            View All Sales
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="card">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-bolt"></i> Quick Actions</h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3 mb-2">
                    <a href="add_purchase.php?product_id=<?= $product_id ?>" class="btn btn-success btn-block">
                        <i class="fas fa-plus-circle"></i> Add Stock
                    </a>
                </div>
                <div class="col-md-3 mb-2">
                    <a href="edit_product.php?id=<?= $product_id ?>" class="btn btn-warning btn-block">
                        <i class="fas fa-edit"></i> Edit Product
                    </a>
                </div>
                <div class="col-md-3 mb-2">
                    <a href="pos.php?product_id=<?= $product_id ?>" class="btn btn-primary btn-block">
                        <i class="fas fa-cash-register"></i> Sell Product
                    </a>
                </div>
                <div class="col-md-3 mb-2">
                    <?php if($product['is_active']): ?>
                    <button class="btn btn-danger btn-block delete-product-btn" 
                            data-product-id="<?= $product_id ?>"
                            data-product-name="<?= htmlspecialchars($product['name']) ?>">
                        <i class="fas fa-trash"></i> Deactivate
                    </button>
                    <?php else: ?>
                    <button class="btn btn-success btn-block restore-product-btn" 
                            data-product-id="<?= $product_id ?>"
                            data-product-name="<?= htmlspecialchars($product['name']) ?>">
                        <i class="fas fa-undo"></i> Restore
                    </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once '../../includes/footer.php'; ?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    // Delete/Deactivate Product
    $('.delete-product-btn').click(function() {
        const productId = $(this).data('product-id');
        const productName = $(this).data('product-name');
        
        Swal.fire({
            title: 'Deactivate Product',
            html: `Are you sure you want to deactivate <strong>${productName}</strong>?<br>
                   <small class="text-muted">This will mark the product as inactive. It can be restored later.</small>`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, deactivate it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Deactivating...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                });
                
                $.ajax({
                    url: 'ajax/deactivate_product.php',
                    type: 'POST',
                    data: { id: productId },
                    dataType: 'json',
                    success: function(response) {
                        Swal.close();
                        if (response.status === 'success') {
                            Swal.fire({
                                title: 'Deactivated!',
                                text: response.message,
                                icon: 'success'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Error!',
                                text: response.message,
                                icon: 'error'
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        Swal.close();
                        Swal.fire({
                            title: 'Error!',
                            html: 'An error occurred while deactivating the product.',
                            icon: 'error'
                        });
                        console.error("AJAX Error:", error);
                    }
                });
            }
        });
    });
    
    // Restore Product
    $('.restore-product-btn').click(function() {
        const productId = $(this).data('product-id');
        const productName = $(this).data('product-name');
        
        Swal.fire({
            title: 'Restore Product',
            html: `Are you sure you want to restore <strong>${productName}</strong>?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, restore it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Restoring...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                });
                
                $.ajax({
                    url: 'ajax/restore_product.php',
                    type: 'POST',
                    data: { id: productId },
                    dataType: 'json',
                    success: function(response) {
                        Swal.close();
                        if (response.status === 'success') {
                            Swal.fire({
                                title: 'Restored!',
                                text: response.message,
                                icon: 'success'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Error!',
                                text: response.message,
                                icon: 'error'
                            });
                        }
                    },
                    error: function(xhr) {
                        Swal.close();
                        Swal.fire({
                            title: 'Error!',
                            text: 'Failed to restore product.',
                            icon: 'error'
                        });
                    }
                });
            }
        });
    });
});
</script>

<script>
// Handle links with AJAX loading
$(document).ready(function() {
    // Function to load content via AJAX
    function loadContent(url, targetElement, title) {
        Swal.fire({
            title: 'Loading...',
            text: 'Please wait',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });
        
        $.ajax({
            url: url,
            type: 'GET',
            success: function(response) {
                Swal.close();
                
                // Create modal to display content
                Swal.fire({
                    title: title,
                    html: '<div style="max-height: 70vh; overflow-y: auto;">' + response + '</div>',
                    width: '90%',
                    showCloseButton: true,
                    showConfirmButton: false
                });
            },
            error: function(xhr, status, error) {
                Swal.close();
                
                // If AJAX fails, redirect to the page directly
                if (xhr.status === 404 || xhr.status === 0) {
                    Swal.fire({
                        title: 'Page Not Found',
                        text: 'The requested page does not exist. Would you like to create it?',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: 'Yes, create it',
                        cancelButtonText: 'No, cancel'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = url;
                        }
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: 'Failed to load content. Please try again.',
                        icon: 'error'
                    });
                }
            }
        });
    }
    
    // Handle list_purchase.php link
    $('a[href*="list_purchase.php"]').click(function(e) {
        e.preventDefault();
        const url = $(this).attr('href');
        loadContent(url, '#purchaseContent', 'Purchase History');
    });
    
    // Handle list_sales.php link
    $('a[href*="list_sales.php"]').click(function(e) {
        e.preventDefault();
        const url = $(this).attr('href');
        loadContent(url, '#salesContent', 'Sales History');
    });
    
    // Handle edit_product.php link - keep as direct link (no modal)
    $('a[href*="edit_product.php"]').click(function(e) {
        // Allow direct navigation for edit
        return true;
    });
    
    // Handle add_purchase.php link - keep as direct link (no modal)
    $('a[href*="add_purchase.php"]').click(function(e) {
        // Allow direct navigation for add purchase
        return true;
    });
    
    // Handle pos.php link - keep as direct link (no modal)
    $('a[href*="pos.php"]').click(function(e) {
        // Allow direct navigation for POS
        return true;
    });
    
    // Handle "View All Purchases" button
    $('a.btn-outline-primary').filter(function() {
        return $(this).text().includes('View All Purchases');
    }).click(function(e) {
        e.preventDefault();
        const url = $(this).attr('href');
        loadContent(url, '#allPurchasesContent', 'All Purchase History');
    });
    
    // Handle "View All Sales" button
    $('a.btn-outline-success').filter(function() {
        return $(this).text().includes('View All Sales');
    }).click(function(e) {
        e.preventDefault();
        const url = $(this).attr('href');
        loadContent(url, '#allSalesContent', 'All Sales History');
    });
    
    // Handle "Back to Products List" link
    $('a[href*="list_product.php"]').not('.btn-outline-secondary').click(function(e) {
        e.preventDefault();
        const url = $(this).attr('href');
        
        Swal.fire({
            title: 'Leave this page?',
            text: 'You will be redirected to the products list.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, go to list',
            cancelButtonText: 'Stay here'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = url;
            }
        });
    });
    
    // Handle "Back to List" button (different behavior - direct navigation)
    $('a.btn-outline-secondary').filter(function() {
        return $(this).text().includes('Back to List');
    }).click(function(e) {
        // Allow direct navigation
        return true;
    });
});
</script>
<script>
// Handle Add Purchase/POS/Edit links with AJAX modals
$(document).ready(function() {
    // Handle Add Purchase links
    $('a[href*="add_purchase.php"]').click(function(e) {
        e.preventDefault();
        const url = $(this).attr('href');
        loadPurchaseForm(url);
    });
    
    // Handle POS links
    $('a[href*="pos.php"]').click(function(e) {
        e.preventDefault();
        const url = $(this).attr('href');
        loadPOSForm(url);
    });
    
    // Handle Edit Product links
    $('a[href*="edit_product.php"]').click(function(e) {
        e.preventDefault();
        const url = $(this).attr('href');
        loadEditForm(url);
    });
    
    // Also handle button clicks with same functionality
    $('button').on('click', function() {
        const onclick = $(this).attr('onclick') || '';
        if (onclick.includes('addStock')) {
            const productId = onclick.match(/addStock\((\d+)\)/)?.[1];
            if (productId) {
                e.preventDefault();
                e.stopPropagation();
                loadPurchaseForm(`ajax/add_purchase.php?product_id=${productId}`);
            }
        }
        if (onclick.includes('sellProduct')) {
            const productId = onclick.match(/sellProduct\((\d+)\)/)?.[1];
            if (productId) {
                e.preventDefault();
                e.stopPropagation();
                loadPOSForm(`ajax/pos.php?product_id=${productId}`);
            }
        }
        if (onclick.includes('editProduct')) {
            const productId = onclick.match(/editProduct\((\d+)\)/)?.[1];
            if (productId) {
                e.preventDefault();
                e.stopPropagation();
                loadEditForm(`ajax/edit_product.php?id=${productId}`);
            }
        }
    });
});

// Load Add Purchase form in modal
function loadPurchaseForm(url) {
    Swal.fire({
        title: 'Loading Purchase Form...',
        text: 'Please wait',
        allowOutsideClick: false,
        didOpen: () => { Swal.showLoading(); }
    });
    
    $.ajax({
        url: url,
        type: 'GET',
        success: function(response) {
            Swal.close();
            
            Swal.fire({
                title: 'Add Stock Purchase',
                html: '<div style="max-height: 80vh; overflow-y: auto;">' + response + '</div>',
                width: '95%',
                showCloseButton: true,
                showConfirmButton: false,
                customClass: {
                    container: 'p-0'
                }
            });
            
            // Initialize form functionality
            initPurchaseForm();
        },
        error: function(xhr, status, error) {
            Swal.close();
            if (xhr.status === 404) {
                Swal.fire({
                    title: 'Form Not Available',
                    text: 'The purchase form is not available. Would you like to be redirected?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, redirect',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = url;
                    }
                });
            } else {
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to load purchase form.',
                    icon: 'error'
                });
            }
        }
    });
}

// Load POS form in modal
function loadPOSForm(url) {
    Swal.fire({
        title: 'Loading POS Form...',
        text: 'Please wait',
        allowOutsideClick: false,
        didOpen: () => { Swal.showLoading(); }
    });
    
    $.ajax({
        url: url,
        type: 'GET',
        success: function(response) {
            Swal.close();
            
            Swal.fire({
                title: 'Sell Product',
                html: '<div style="max-height: 80vh; overflow-y: auto;">' + response + '</div>',
                width: '95%',
                showCloseButton: true,
                showConfirmButton: false,
                customClass: {
                    container: 'p-0'
                }
            });
            
            // Initialize POS functionality
            initPOSForm();
        },
        error: function(xhr, status, error) {
            Swal.close();
            if (xhr.status === 404) {
                Swal.fire({
                    title: 'POS Not Available',
                    text: 'The POS form is not available. Would you like to be redirected?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, redirect',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = url;
                    }
                });
            } else {
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to load POS form.',
                    icon: 'error'
                });
            }
        }
    });
}

// Load Edit form in modal
function loadEditForm(url) {
    Swal.fire({
        title: 'Loading Edit Form...',
        text: 'Please wait',
        allowOutsideClick: false,
        didOpen: () => { Swal.showLoading(); }
    });
    
    $.ajax({
        url: url,
        type: 'GET',
        success: function(response) {
            Swal.close();
            
            Swal.fire({
                title: 'Edit Product',
                html: '<div style="max-height: 80vh; overflow-y: auto;">' + response + '</div>',
                width: '90%',
                showCloseButton: true,
                showConfirmButton: false,
                customClass: {
                    container: 'p-0'
                }
            });
            
            // Initialize edit form functionality
            initEditForm();
        },
        error: function(xhr, status, error) {
            Swal.close();
            if (xhr.status === 404) {
                Swal.fire({
                    title: 'Edit Form Not Available',
                    text: 'The edit form is not available. Would you like to be redirected?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, redirect',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = url;
                    }
                });
            } else {
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to load edit form.',
                    icon: 'error'
                });
            }
        }
    });
}

// Initialize purchase form functionality
function initPurchaseForm() {
    // Form validation
    $('#purchaseForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        Swal.fire({
            title: 'Processing Purchase...',
            text: 'Please wait',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });
        
        $.ajax({
            url: 'ajax/save_purchase.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                Swal.close();
                if (response.status === 'success') {
                    Swal.fire({
                        title: 'Success!',
                        text: response.message,
                        icon: 'success'
                    }).then(() => {
                        Swal.close();
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message,
                        icon: 'error'
                    });
                }
            },
            error: function() {
                Swal.close();
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to save purchase.',
                    icon: 'error'
                });
            }
        });
    });
    
    // Auto-calculate total
    $('input[name="qty"], input[name="cost_price"]').on('input', function() {
        const qty = parseInt($('input[name="qty"]').val()) || 0;
        const price = parseFloat($('input[name="cost_price"]').val()) || 0;
        const total = qty * price;
        $('#totalAmount').text(total.toFixed(2));
    });
}

// Initialize POS form functionality
// Initialize POS form functionality
function initPOSForm() {
    // Form submission
    $('#posForm').on('submit', function(e) {
        e.preventDefault();
        
        // Get form data as object
        const formData = {
            product_id: $('input[name="product_id"]').val(),
            customer_id: $('select[name="customer_id"]').val() || null,
            invoice_no: $('input[name="invoice_no"]').val(),
            sale_date: $('input[name="sale_date"]').val(),
            qty: $('input[name="qty"]').val(),
            unit_price: $('input[name="unit_price"]').val(),
            discount: $('input[name="discount"]').val() || 0,
            batch_id: $('select[name="batch_id"]').val() || null,
            payment_method: $('select[name="payment_method"]').val(),
            amount_paid: $('input[name="amount_paid"]').val(),
            shop_id: $('input[name="shop_id"]').val(),
            created_by: $('input[name="created_by"]').val()
        };
        
        console.log('Form Data:', formData); // Debug log
        
        Swal.fire({
            title: 'Processing Sale...',
            text: 'Please wait',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });
        
        $.ajax({
            url: 'ajax/save_sale.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                Swal.close();
                console.log('Response:', response); // Debug log
                
                if (response.status === 'success') {
                    Swal.fire({
                        title: 'Sale Complete!',
                        html: `Invoice: ${response.invoice_no}<br>
                               Total: ${response.total}<br>
                               Change: ${response.change || '0.00'}`,
                        icon: 'success',
                        showCancelButton: true,
                        confirmButtonText: 'Print Receipt',
                        cancelButtonText: 'Close',
                        showDenyButton: true,
                        denyButtonText: 'New Sale'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.open(`ajax/print_receipt.php?sale_id=${response.sale_id}`, '_blank');
                            Swal.close();
                            location.reload();
                        } else if (result.isDenied) {
                            Swal.close();
                            // Reload the POS form
                            $('#posForm')[0].reset();
                            // Reset invoice number to new one
                            const newInvoice = 'SALE-' + new Date().toISOString().slice(0,10).replace(/-/g,'') + '-' + 
                                             Math.floor(Math.random() * 1000).toString().padStart(3, '0');
                            $('input[name="invoice_no"]').val(newInvoice);
                            calculateTotals();
                        } else {
                            Swal.close();
                            location.reload();
                        }
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'Unknown error occurred',
                        icon: 'error'
                    });
                }
            },
            error: function(xhr, status, error) {
                Swal.close();
                console.error('AJAX Error:', xhr.responseText, status, error);
                
                Swal.fire({
                    title: 'Error!',
                    html: `Failed to process sale.<br>
                           <small>${error}: ${xhr.responseText || 'No response'}</small>`,
                    icon: 'error'
                });
            }
        });
    });
    
    // Calculate total function (make sure this exists)
    function calculateTotals() {
        const qty = parseInt($('input[name="qty"]').val()) || 0;
        const price = parseFloat($('input[name="unit_price"]').val()) || 0;
        const discount = parseFloat($('input[name="discount"]').val()) || 0;
        const vatPercent = parseFloat($('input[name="vat_percent"]').val()) || 0;
        
        const subtotal = qty * price;
        const discountAmount = subtotal * (discount / 100);
        const afterDiscount = subtotal - discountAmount;
        const vatAmount = afterDiscount * (vatPercent / 100);
        const total = afterDiscount + vatAmount;
        
        $('#subtotal').text(subtotal.toFixed(2));
        $('#discountAmount').text(discountAmount.toFixed(2));
        $('#vatAmount').text(vatAmount.toFixed(2));
        $('#saleTotal').text(total.toFixed(2));
        
        // Calculate change
        const amountPaid = parseFloat($('input[name="amount_paid"]').val()) || 0;
        const change = amountPaid - total;
        $('#changeAmount').val(change > 0 ? change.toFixed(2) : '0.00');
        
        return total;
    }
    
    // Update totals when inputs change
    $('input[name="qty"], input[name="unit_price"], input[name="discount"], input[name="amount_paid"]').on('input', calculateTotals);
}

// Initialize edit form functionality
// Initialize POS form functionality
function initPOSForm() {
    // Form submission
    $('#posForm').on('submit', function(e) {
        e.preventDefault();
        
        // Get form data as object
        const formData = {
            product_id: $('input[name="product_id"]').val(),
            customer_name: $('input[name="customer_name"]').val() || '',
            invoice_no: $('input[name="invoice_no"]').val(),
            sale_date: $('input[name="sale_date"]').val(),
            qty: $('input[name="qty"]').val(),
            unit_price: $('input[name="unit_price"]').val(),
            discount: $('input[name="discount"]').val() || 0,
            batch_id: $('select[name="batch_id"]').val() || null,
            payment_method: $('select[name="payment_method"]').val(),
            amount_paid: $('input[name="amount_paid"]').val(),
            shop_id: $('input[name="shop_id"]').val(),
            created_by: $('input[name="created_by"]').val(),
            vat_percent: $('input[name="vat_percent"]').val()
        };
        
        console.log('Form Data:', formData);
        
        Swal.fire({
            title: 'Processing Sale...',
            text: 'Please wait',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });
        
        $.ajax({
            url: 'ajax/save_sale.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                Swal.close();
                console.log('Response:', response);
                
                if (response.status === 'success') {
                    Swal.fire({
                        title: 'Sale Complete!',
                        html: `Invoice: ${response.invoice_no}<br>
                               Total: ${response.total}<br>
                               Change: ${response.change || '0.00'}`,
                        icon: 'success',
                        showCancelButton: true,
                        confirmButtonText: 'Print Receipt',
                        cancelButtonText: 'Close',
                        showDenyButton: true,
                        denyButtonText: 'New Sale'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.open(`ajax/print_receipt.php?sale_id=${response.sale_id}`, '_blank');
                            Swal.close();
                            location.reload();
                        } else if (result.isDenied) {
                            Swal.close();
                            // Reload the POS form
                            $('#posForm')[0].reset();
                            // Reset invoice number to new one
                            const newInvoice = 'SALE-' + new Date().toISOString().slice(0,10).replace(/-/g,'') + '-' + 
                                             Math.floor(Math.random() * 1000).toString().padStart(3, '0');
                            $('input[name="invoice_no"]').val(newInvoice);
                            calculateTotals();
                        } else {
                            Swal.close();
                            location.reload();
                        }
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'Unknown error occurred',
                        icon: 'error'
                    });
                }
            },
            error: function(xhr, status, error) {
                Swal.close();
                console.error('AJAX Error:', xhr.responseText, status, error);
                
                let errorMessage = 'Failed to process sale.';
                if (xhr.responseText) {
                    try {
                        const errorResponse = JSON.parse(xhr.responseText);
                        errorMessage = errorResponse.message || errorMessage;
                    } catch (e) {
                        errorMessage = xhr.responseText;
                    }
                }
                
                Swal.fire({
                    title: 'Error!',
                    html: errorMessage,
                    icon: 'error'
                });
            }
        });
    });
    
    // Calculate total function
    function calculateTotals() {
        const qty = parseInt($('input[name="qty"]').val()) || 0;
        const price = parseFloat($('input[name="unit_price"]').val()) || 0;
        const discount = parseFloat($('input[name="discount"]').val()) || 0;
        const vatPercent = parseFloat($('input[name="vat_percent"]').val()) || 0;
        
        const subtotal = qty * price;
        const discountAmount = subtotal * (discount / 100);
        const afterDiscount = subtotal - discountAmount;
        const vatAmount = afterDiscount * (vatPercent / 100);
        const total = afterDiscount + vatAmount;
        
        $('#subtotal').text(subtotal.toFixed(2));
        $('#discountAmount').text(discountAmount.toFixed(2));
        $('#vatAmount').text(vatAmount.toFixed(2));
        $('#saleTotal').text(total.toFixed(2));
        
        // Calculate change
        const amountPaid = parseFloat($('input[name="amount_paid"]').val()) || 0;
        const change = amountPaid - total;
        $('#changeAmount').val(change > 0 ? change.toFixed(2) : '0.00');
        
        return total;
    }
    
    // Update totals when inputs change
    $('input[name="qty"], input[name="unit_price"], input[name="discount"], input[name="amount_paid"]').on('input', calculateTotals);
}
</script>

<style>
.breadcrumb {
    background: transparent;
    padding: 0;
    margin-bottom: 1rem;
}
.breadcrumb-item a {
    color: #6c757d;
    text-decoration: none;
}
.breadcrumb-item.active {
    color: #28a745;
    font-weight: bold;
}
.card-header h5 {
    display: flex;
    align-items: center;
    gap: 10px;
}
.badge {
    font-size: 0.85em;
}
.table th {
    font-weight: 600;
}
.btn-block {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
}
</style>