<?php
session_start();
include 'php/db_connection.php';

// শুধুমাত্র লগইন করা ইউজার পেজ দেখতে পারবে
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userName = $_SESSION['user_name'];
$role = $_SESSION['role'];
$isAdmin = ($_SESSION['role'] == 'admin');

// Check if ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    echo "<script>alert('No product ID provided!'); window.location.href='add_product_name.php';</script>";
    exit();
}

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

// Fetch product details
$stmt = $con->prepare("SELECT * FROM product WHERE id = ?");
$stmt->bind_param("i", $Product_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    echo "<script>alert('Product not found!'); window.location.href='add_product_name.php';</script>";
    exit();
}

$product = $result->fetch_assoc();
$category_id = $product['Product_id'];

// Fetch product_cat details for purchase_price and price
$cat_stmt = $con->prepare("SELECT purchase_price, price FROM product_cat WHERE Product_id = ?");
$cat_stmt->bind_param("i", $category_id);
$cat_stmt->execute();
$cat_result = $cat_stmt->get_result();
$product_cat = $cat_result->fetch_assoc();
$cat_stmt->close();

// Update product
if (isset($_POST['update'])) {
    $Quantity = floatval($_POST['Quantity']);
    $expiration_date = $_POST['Expiration_date'];
    $price = floatval($_POST['price']);
    $purchase_price = floatval($_POST['purchase_price']);
    $totalPrice = floatval($_POST['totalPrice']);
    
    // Update product table
    $update_stmt = $con->prepare("UPDATE product SET Quantity = ?, Expiration_date = ?, price = ?, totalPrice = ? WHERE id = ?");
    $update_stmt->bind_param("dsddi", $Quantity, $expiration_date, $price, $totalPrice, $Product_id);
    
    // Update product_cat table
    $update_cat_stmt = $con->prepare("UPDATE product_cat SET purchase_price = ?, price = ? WHERE Product_id = ?");
    $update_cat_stmt->bind_param("ddi", $purchase_price, $price, $category_id);
    
    if ($update_stmt->execute() && $update_cat_stmt->execute()) {
        echo "<script>
            alert('Product updated successfully!');
            window.location.href='add_product.php?category={$category_id}';
        </script>";
        exit();
    } else {
        echo "<script>alert('Failed to update product!');</script>";
    }
    $update_stmt->close();
    $update_cat_stmt->close();
}

$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Product - <?php echo htmlspecialchars($product['name']); ?></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        .main-container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }

        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
            text-align: center;
        }

        .product-id-display {
            text-align: center;
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .back-button {
            display: inline-block;
            padding: 10px 20px;
            background-color: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            margin-bottom: 20px;
            transition: background-color 0.3s;
        }

        .back-button:hover {
            background-color: #5a6268;
            color: white;
            text-decoration: none;
        }

        .form-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 25px;
            border: 2px solid #dee2e6;
        }

        .form-section h3 {
            color: #495057;
            font-size: 18px;
            margin-bottom: 20px;
            text-align: center;
            border-bottom: 2px solid #adb5bd;
            padding-bottom: 10px;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 25px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-group label {
            display: block;
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
            font-size: 14px;
        }

        .form-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-group input.readonly {
            background-color: #e9ecef;
            cursor: not-allowed;
            color: #6c757d;
        }

        .button-group {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }

        .btn-update {
            flex: 1;
            padding: 14px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .btn-update:hover {
            background-color: #218838;
        }

        .btn-cancel {
            flex: 1;
            padding: 14px;
            background-color: #6c757d;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s;
            text-decoration: none;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .btn-cancel:hover {
            background-color: #5a6268;
            color: white;
            text-decoration: none;
        }

        .alert-info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .profit-info {
            background-color: #d4edda;
            border: 2px solid #c3e6cb;
            color: #155724;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            text-align: center;
            font-weight: bold;
            font-size: 16px;
        }

        @media (max-width: 768px) {
            .main-container {
                padding: 20px;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .button-group {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <?php include 'sidebar.php'; ?>

    <div class="main-container">
        <a href="add_product.php?category=<?php echo $category_id; ?>" class="back-button">
            ← Back to Product List
        </a>

        <h1>Edit Product</h1>
        <div class="product-id-display">
            <strong><?php echo htmlspecialchars($product['name']); ?></strong> 
            (ID: <?php echo htmlspecialchars($category_id); ?>)
        </div>

        <div class="alert-info">
            <strong>Note:</strong> Product Name and Product ID cannot be changed. Only Quantity, expiration date, purchase price, and selling price can be updated.
        </div>

        <form method="POST">
            <!-- Basic Information Section -->
            <div class="form-section">
                <h3>📋 Basic Information</h3>
                <div class="form-row">
                    <div class="form-group">
                        <label for="productId">Product ID:</label>
                        <input type="text" 
                               value="<?php echo htmlspecialchars($category_id); ?>" 
                               id="productId" 
                               name="productId" 
                               class="readonly" 
                               readonly>
                    </div>

                    <div class="form-group">
                        <label for="productName">Product Name:</label>
                        <input type="text" 
                               value="<?php echo htmlspecialchars($product['name']); ?>" 
                               id="productName" 
                               name="productName" 
                               class="readonly" 
                               readonly>
                    </div>
                </div>
            </div>

            <!-- Stock Information Section -->
            <div class="form-section">
                <h3>📦 Stock Information</h3>
                <div class="form-row">
                    <div class="form-group">
                        <label for="Quantity">Quantity: <span style="color: red;">*</span></label>
                        <input type="number" 
                               id="Quantity" 
                               name="Quantity" 
                               value="<?php echo $product['Quantity']; ?>" 
                               min="0" 
                               step="0.01" 
                               oninput="calculateTotal()" 
                               required>
                    </div>

                    <div class="form-group">
                        <label for="Expiration_date">Expiration Date: <span style="color: red;">*</span></label>
                        <input type="date" 
                               id="Expiration_date" 
                               name="Expiration_date" 
                               value="<?php echo $product['Expiration_date']; ?>" 
                               required>
                    </div>
                </div>
            </div>

            <!-- Pricing Information Section -->
            <div class="form-section">
                <h3>💰 Pricing Information</h3>
                <div class="form-row">
                    <div class="form-group">
                        <label for="purchase_price">Purchase Price (per Unit): <span style="color: red;">*</span></label>
                        <input type="number" 
                               id="purchase_price" 
                               name="purchase_price" 
                               value="<?php echo $product_cat['purchase_price']; ?>" 
                               step="0.01" 
                               min="0" 
                               oninput="calculateTotal()" 
                               required>
                        <small style="color: #6c757d;">This updates product_cat table</small>
                    </div>

                    <div class="form-group">
                        <label for="price">Selling Price (per Unit): <span style="color: red;">*</span></label>
                        <input type="number" 
                               id="price" 
                               name="price" 
                               value="<?php echo $product_cat['price']; ?>" 
                               step="0.01" 
                               min="0" 
                               oninput="calculateTotal()" 
                               required>
                        <small style="color: #6c757d;">This updates both tables</small>
                    </div>
                </div>

                <div class="form-group">
                    <label for="totalPrice">Total Selling Price:</label>
                    <input type="number" 
                           id="totalPrice" 
                           name="totalPrice" 
                           value="<?php echo $product['totalPrice']; ?>" 
                           step="0.01" 
                           class="readonly" 
                           readonly>
                </div>

                <div class="profit-info" id="profitInfo">
                    Calculating profit...
                </div>
            </div>

            <div class="button-group">
                <button type="submit" name="update" class="btn-update">
                    ✓ Update Product
                </button>
                <a href="add_product.php?category=<?php echo $category_id; ?>" class="btn-cancel">
                    ✕ Cancel
                </a>
            </div>
        </form>
    </div>

    <script>
        function calculateTotal() {
            const quantity = parseFloat(document.getElementById('Quantity').value) || 0;
            const purchasePrice = parseFloat(document.getElementById('purchase_price').value) || 0;
            const sellingPrice = parseFloat(document.getElementById('price').value) || 0;
            
            // Calculate totals
            const totalPurchase = quantity * purchasePrice;
            const totalSelling = quantity * sellingPrice;
            
            // Calculate profit
            const profitPerUnit = sellingPrice - purchasePrice;
            const totalProfit = totalSelling - totalPurchase;
            const profitPercentage = purchasePrice > 0 ? ((profitPerUnit / purchasePrice) * 100) : 0;
            
            // Update total selling price field
            document.getElementById('totalPrice').value = totalSelling.toFixed(2);
            
            // Update profit info
            const profitInfo = document.getElementById('profitInfo');
            
            if (totalProfit >= 0) {
                profitInfo.style.backgroundColor = '#d4edda';
                profitInfo.style.borderColor = '#c3e6cb';
                profitInfo.style.color = '#155724';
                profitInfo.innerHTML = `
                    ✓ Profit per Unit: ৳${profitPerUnit.toFixed(2)} (${profitPercentage.toFixed(1)}%) | 
                    Total Profit: ৳${totalProfit.toFixed(2)}
                `;
            } else {
                profitInfo.style.backgroundColor = '#f8d7da';
                profitInfo.style.borderColor = '#f5c6cb';
                profitInfo.style.color = '#721c24';
                profitInfo.innerHTML = `
                    ✗ Loss per Unit: ৳${Math.abs(profitPerUnit).toFixed(2)} | 
                    Total Loss: ৳${Math.abs(totalProfit).toFixed(2)}
                `;
            }
        }

        // Calculate total on page load
        window.onload = function() {
            calculateTotal();
        };
    </script>
</body>
</html>

<?php
$con->close();
?>