<?php
// ajax/get_product_details.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../../assets/db_connect.php';

header('Content-Type: text/html');

// Check if product_id is provided
if (!isset($_GET['product_id'])) {
    echo '<div class="alert alert-danger">Product ID is required</div>';
    exit;
}

$product_id = intval($_GET['product_id']);
$shop_id = isset($_SESSION['user']['shop_id']) ? $_SESSION['user']['shop_id'] : 0;

try {
    // Get product details with stock information
    $sql = "SELECT 
                p.*,
                COALESCE(ps.total_qty, 0) as current_stock,
                COALESCE(ps.batch_count, 0) as batch_count,
                ps.earliest_expiry,
                ps.latest_expiry,
                s.name as shop_name
            FROM products p
            LEFT JOIN product_stock_view ps ON p.id = ps.product_id
            LEFT JOIN shops s ON p.shop_id = s.id
            WHERE p.id = ? 
            AND (p.shop_id = ? OR ? = 0 OR ? = 'admin')";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$product_id, $shop_id, $shop_id, $_SESSION['user']['role'] ?? '']);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$product) {
        echo '<div class="alert alert-danger">Product not found</div>';
        exit;
    }
    
    // Calculate stock value
    $stock_value = $product['current_stock'] * $product['buying_price'];
    
    // Get expiry status
    $expiry_status = '';
    $expiry_class = '';
    if ($product['earliest_expiry']) {
        $days_to_expiry = floor((strtotime($product['earliest_expiry']) - time()) / (60 * 60 * 24));
        if ($days_to_expiry < 0) {
            $expiry_status = 'Expired ' . abs($days_to_expiry) . ' days ago';
            $expiry_class = 'danger';
        } elseif ($days_to_expiry <= 30) {
            $expiry_status = $days_to_expiry . ' days left';
            $expiry_class = 'warning';
        } elseif ($days_to_expiry <= 90) {
            $expiry_status = $days_to_expiry . ' days left';
            $expiry_class = 'info';
        } else {
            $expiry_status = $days_to_expiry . ' days left';
            $expiry_class = 'success';
        }
    }
    
    // Get stock status
    $stock_status = '';
    $stock_class = '';
    if ($product['is_active'] != 1) {
        $stock_status = 'Inactive';
        $stock_class = 'secondary';
    } elseif ($product['current_stock'] <= 0) {
        $stock_status = 'Out of Stock';
        $stock_class = 'danger';
    } elseif ($product['current_stock'] <= 20) {
        $stock_status = 'Low Stock';
        $stock_class = 'warning';
    } else {
        $stock_status = 'In Stock';
        $stock_class = 'success';
    }
    
    // Get margin
    $margin = 0;
    if ($product['buying_price'] > 0 && $product['selling_price'] > 0) {
        $margin = (($product['selling_price'] - $product['buying_price']) / $product['buying_price']) * 100;
    }
    
    // Format dates
    $created_date = date('d M Y, h:i A', strtotime($product['created_at']));
    
    ?>
    
    <div class="container-fluid">
        <!-- Product Header -->
        <div class="row mb-4">
            <div class="col-md-8">
                <h4 class="text-primary mb-2">
                    <?= htmlspecialchars($product['name']) ?>
                    <?php if(!empty($product['generic_name'])): ?>
                    <small class="text-muted">(<?= htmlspecialchars($product['generic_name']) ?>)</small>
                    <?php endif; ?>
                </h4>
                <div class="d-flex flex-wrap gap-2 mb-3">
                    <span class="badge badge-<?= $stock_class ?> stock-badge">
                        <i class="fas fa-<?= $stock_class == 'success' ? 'check-circle' : ($stock_class == 'warning' ? 'exclamation-triangle' : ($stock_class == 'danger' ? 'times-circle' : 'ban')) ?>"></i>
                        <?= $stock_status ?>
                    </span>
                    <span class="badge badge-secondary">ID: #<?= $product['id'] ?></span>
                    <span class="badge badge-light">SKU: <?= htmlspecialchars($product['sku'] ?? 'N/A') ?></span>
                    <span class="badge badge-info">Shop: <?= htmlspecialchars($product['shop_name']) ?></span>
                </div>
            </div>
            <div class="col-md-4 text-right">
                <div class="d-flex justify-content-end gap-2">
                    <span class="badge badge-dark">
                        <i class="fas fa-cube"></i> <?= htmlspecialchars($product['unit']) ?>
                    </span>
                    <span class="badge badge-secondary">
                        <i class="fas fa-tag"></i> <?= htmlspecialchars($product['category'] ?? 'Uncategorized') ?>
                    </span>
                </div>
            </div>
        </div>
        
        <!-- Stats Row -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-light mb-3">
                    <div class="card-body p-3 text-center">
                        <div class="text-muted mb-1">Current Stock</div>
                        <div class="h3 text-primary mb-0"><?= number_format($product['current_stock']) ?></div>
                        <small class="text-muted"><?= $product['batch_count'] ?> batch(es)</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-light mb-3">
                    <div class="card-body p-3 text-center">
                        <div class="text-muted mb-1">Buying Price</div>
                        <div class="h3 text-success mb-0"><?= number_format($product['buying_price'], 2) ?></div>
                        <small class="text-muted">per unit</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-light mb-3">
                    <div class="card-body p-3 text-center">
                        <div class="text-muted mb-1">Selling Price</div>
                        <div class="h3 text-danger mb-0"><?= number_format($product['selling_price'], 2) ?></div>
                        <small class="text-muted">per unit</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-light mb-3">
                    <div class="card-body p-3 text-center">
                        <div class="text-muted mb-1">Margin</div>
                        <div class="h3 text-<?= $margin >= 0 ? 'success' : 'danger' ?> mb-0"><?= number_format($margin, 1) ?>%</div>
                        <small class="text-muted">profit</small>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Detailed Information -->
        <div class="row">
            <div class="col-md-6">
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="fas fa-info-circle"></i> Basic Information</h6>
                    </div>
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="text-muted small">Product Name</div>
                                <div class="font-weight-bold"><?= htmlspecialchars($product['name']) ?></div>
                            </div>
                            <div class="col-md-6">
                                <div class="text-muted small">Generic Name</div>
                                <div class="font-weight-bold"><?= htmlspecialchars($product['generic_name'] ?? 'N/A') ?></div>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="text-muted small">SKU Code</div>
                                <div class="font-weight-bold font-monospace"><?= htmlspecialchars($product['sku'] ?? 'N/A') ?></div>
                            </div>
                            <div class="col-md-6">
                                <div class="text-muted small">Unit</div>
                                <div class="font-weight-bold"><?= htmlspecialchars($product['unit']) ?></div>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="text-muted small">Category</div>
                                <div class="font-weight-bold"><?= htmlspecialchars($product['category'] ?? 'Uncategorized') ?></div>
                            </div>
                            <div class="col-md-6">
                                <div class="text-muted small">VAT Rate</div>
                                <div class="font-weight-bold"><?= $product['vat_percent'] ?>%</div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="text-muted small">Shop</div>
                                <div class="font-weight-bold"><?= htmlspecialchars($product['shop_name']) ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="fas fa-chart-line"></i> Stock & Financial Information</h6>
                    </div>
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="text-muted small">Current Stock</div>
                                <div class="font-weight-bold">
                                    <span class="badge badge-<?= $stock_class ?>">
                                        <?= number_format($product['current_stock']) ?> units
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="text-muted small">Total Batches</div>
                                <div class="font-weight-bold"><?= $product['batch_count'] ?></div>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="text-muted small">Buying Price</div>
                                <div class="font-weight-bold">$<?= number_format($product['buying_price'], 2) ?></div>
                            </div>
                            <div class="col-md-6">
                                <div class="text-muted small">Selling Price</div>
                                <div class="font-weight-bold">$<?= number_format($product['selling_price'], 2) ?></div>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="text-muted small">Stock Value</div>
                                <div class="font-weight-bold text-success">$<?= number_format($stock_value, 2) ?></div>
                            </div>
                            <div class="col-md-6">
                                <div class="text-muted small">Margin</div>
                                <div class="font-weight-bold text-<?= $margin >= 0 ? 'success' : 'danger' ?>">
                                    <?= number_format($margin, 1) ?>%
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="text-muted small">Expiry Status</div>
                                <div class="font-weight-bold">
                                    <?php if($product['earliest_expiry']): ?>
                                    <span class="badge badge-<?= $expiry_class ?>">
                                        <?= $expiry_status ?>
                                    </span>
                                    <br>
                                    <small class="text-muted"><?= date('d M Y', strtotime($product['earliest_expiry'])) ?></small>
                                    <?php else: ?>
                                    <span class="badge badge-secondary">No expiry date set</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="text-muted small">Created Date</div>
                                <div class="font-weight-bold"><?= $created_date ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Action Buttons -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body text-center">
                       <!-- <div class="btn-group" role="group">
                            <button class="btn btn-outline-info" id="viewBatchesFromModalBtn" 
                                    data-product-id="<?= $product_id ?>"
                                    data-product-name="<?= htmlspecialchars($product['name']) ?>">
                                <i class="fas fa-boxes"></i> View Batches
                            </button>
                           <button class="btn btn-outline-success" id="addBatchFromModalBtn"
                                    data-product-id="<?= $product_id ?>"
                                    data-product-name="<?= htmlspecialchars($product['name']) ?>"
                                    data-product-sku="<?= htmlspecialchars($product['sku']) ?>">
                                <i class="fas fa-plus"></i> Add Batch
                            </button> 
                            <a href="edit_product.php?id=<?= $product_id ?>" class="btn btn-outline-primary">
                                <i class="fas fa-edit"></i> Edit Product
                            </a>
                            <?php if($product['is_active'] == 1): ?>
                            <button class="btn btn-outline-danger delete-product-from-modal-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-outline-warning restore-product-from-modal-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>
    </div>
    
    <style>
    .font-monospace {
        font-family: 'Courier New', monospace;
    }
    .gap-2 > * {
        margin-right: 0.5rem;
        margin-bottom: 0.5rem;
    }
    .gap-2 > *:last-child {
        margin-right: 0;
    }
    .stock-badge {
        font-size: 1rem;
        padding: 6px 12px;
    }
    </style>
    
    <?php
    
} catch (PDOException $e) {
    echo '<div class="alert alert-danger">Database error: ' . htmlspecialchars($e->getMessage()) . '</div>';
}
?>