<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}

// Include database configuration file
include '../config/db.php'; // Ensure this file contains your database connection

// Check if ID is provided
if (!isset($_GET['id'])) {
    header("Location: manage_products.php");
    exit();
}

// Fetch pharmacy name from the settings table
$query = "SELECT pharmacy_name FROM settings LIMIT 1"; // Assuming only one entry
$stmt = $pdo->prepare($query);
$stmt->execute();
$setting = $stmt->fetch(PDO::FETCH_ASSOC);
$pharmacy_name = $setting['pharmacy_name'] ?? 'Default Pharmacy Name'; // Fallback to a default if not found


// Fetch the drug details from the database
$drugId = $_GET['id'];
$query = "SELECT * FROM drugs WHERE id = :id";
$stmt = $pdo->prepare($query);
$stmt->execute(['id' => $drugId]);
$drug = $stmt->fetch(PDO::FETCH_ASSOC);

// If drug not found, redirect back
if (!$drug) {
    header("Location: manage_products.php");
    exit();
}

// Initialize variables for form submission
$drug_name = $drug['drug_name'];
$quantity = $drug['quantity'];
$cost_price = $drug['cost_price'];
$selling_price = $drug['selling_price'];
$category = $drug['category'];
$expiration_date = $drug['expiration_date'];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $drug_name = $_POST['drug_name'];
    $add_quantity = isset($_POST['add_quantity']) ? (int)$_POST['add_quantity'] : 0;
    $remove_quantity = isset($_POST['remove_quantity']) ? (int)$_POST['remove_quantity'] : 0;
    $cost_price = $_POST['cost_price'];
    $selling_price = $_POST['selling_price'];
    $category = $_POST['category'];
    $expiration_date = $_POST['expiration_date'];
    $volume_size = $_POST['volume_size'];
    $volume_price = $_POST['volume_price'];

    // Calculate new quantity
    $new_quantity = $quantity + $add_quantity - $remove_quantity;

    // Update the drug in the database
    $updateQuery = "UPDATE drugs SET drug_name = :drug_name, quantity = :quantity, cost_price = :cost_price, selling_price = :selling_price, category = :category, expiration_date = :expiration_date, volume_size = :volume_size, volume_price = :volume_price WHERE id = :id";
    $updateStmt = $pdo->prepare($updateQuery);
    $updateStmt->execute([
        'drug_name' => $drug_name,
        'quantity' => $new_quantity,
        'cost_price' => $cost_price,
        'selling_price' => $selling_price,
        'category' => $category,
        'expiration_date' => $expiration_date,
        'volume_size' => $volume_size,
        'volume_price' => $volume_price,
        'id' => $drugId,
    ]);
    // Add to drug history
$action = 'update';
$quantityChange = $add_quantity - $remove_quantity; // Net change in quantity
$details = "Before Update: Current Quantity = $quantity, Volume Price = $drug[volume_price], Volume Size = $drug[volume_size]";
    
$user = $_SESSION['username']; // Assuming username is stored in session
$actionDate = date('Y-m-d H:i:s'); // Current timestamp

$historyQuery = "INSERT INTO drug_history (drug_id, action, quantity, details, user, action_date) 
                 VALUES (:drug_id, :action, :quantity, :details, :user, :action_date)";
$historyStmt = $pdo->prepare($historyQuery);
$historyStmt->execute([
    'drug_id' => $drugId,
    'action' => $action,
    'quantity' => $quantityChange,
    'details' => $details,
    'user' => $user,
    'action_date' => $actionDate,
]);

    // Handle image upload
    if (isset($_FILES['product_image']) && $_FILES['product_image']['error'] === 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
        $filename = $_FILES['product_image']['name'];
        $filetype = pathinfo($filename, PATHINFO_EXTENSION);
        
        if (in_array(strtolower($filetype), $allowed)) {
            $new_filename = 'product_' . $drugId . '.' . $filetype;
            $upload_path = 'uploads/products/' . $new_filename;
            
            if (move_uploaded_file($_FILES['product_image']['tmp_name'], $upload_path)) {
                $updateImage = "UPDATE drugs SET image_path = :image_path WHERE id = :id";
                $stmt = $pdo->prepare($updateImage);
                $stmt->execute(['image_path' => $upload_path, 'id' => $drugId]);
            }
        }
    }

    if (isset($_GET['id'])) {
        $drug_id = $_GET['id'];
    
        header("Location: edit_drug.php?id=" . $drug_id . "&success=true");
        exit();
    } else {
        header("Location: manage_products.php");
        exit();
    }
}

if (isset($_GET['success']) && $_GET['success'] == 'true') {
    echo '<script type="text/javascript">';
    echo 'alert("Drug updated successfully!");';
    echo '</script>';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Product - Admin Dashboard</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <style>
        :root {
            --primary-bg: #f4f6f9;
            --sidebar-width: 250px;
            --topbar-height: 60px;
            --primary-color: #4e73df;
        }

        body {
            background-color: var(--primary-bg);
            font-family: 'Segoe UI', sans-serif;
        }

        .wrapper {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .top-bar {
            height: var(--topbar-height);
            background: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,.08);
            padding: 0 1.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }

        .content-wrapper {
            margin-top: var(--topbar-height);
            padding: 2rem;
            flex: 1;
        }

        .card {
            border: none;
            box-shadow: 0 0 20px rgba(0,0,0,.08);
            border-radius: 0.5rem;
            background: #fff;
            margin-bottom: 1.5rem;
        }

        .card-header {
            background: #fff;
            border-bottom: 1px solid #edf2f9;
            padding: 1rem 1.5rem;
        }

        .form-control, .form-select {
            border-radius: 0.375rem;
            border: 1px solid #e2e8f0;
            padding: 0.5rem 0.75rem;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
        }

        .btn-primary:hover {
            background-color: #2e59d9;
            border-color: #2e59d9;
        }

        .section-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #edf2f9;
        }

        .input-group-text {
            background-color: #f8f9fa;
            border: 1px solid #e2e8f0;
        }

        .form-label {
            font-weight: 500;
            color: #4a5568;
            margin-bottom: 0.5rem;
        }

        .footer {
            background-color: #fff;
            padding: 1rem;
            text-align: center;
            border-top: 1px solid #edf2f9;
            color: #718096;
        }

        .alert {
            border-radius: 0.5rem;
            border: none;
            box-shadow: 0 0 20px rgba(0,0,0,.05);
        }

        .barcode-display {
            background: #fff;
            padding: 1rem;
            border-radius: 0.5rem;
            box-shadow: 0 0 10px rgba(0,0,0,.05);
        }

        .barcode-display img {
            max-width: 100%;
            height: auto;
        }

        .barcode-display .text-muted {
            font-family: monospace;
            font-size: 1.1rem;
            letter-spacing: 1px;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <!-- Top Bar -->
        <div class="top-bar">
            <h4 class="mb-0">Edit Product</h4>
            <div>
                <a href="manage_drugs.php" class="btn btn-outline-primary">
                    <i class="fas fa-arrow-left"></i> Back to Products
                </a>
            </div>
        </div>

        <!-- Content Wrapper -->
        <div class="content-wrapper">
            <div class="container-fluid">
                <!-- Alert Messages -->
                <?php if (isset($_GET['success']) && $_GET['success'] == 'true'): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i> Product updated successfully!
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <form method="POST" enctype="multipart/form-data">
    <div class="row">
        <!-- Left Column -->
        <div class="col-lg-8">
            <!-- Product Details Card -->
            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">Product Information</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="drug_name" class="form-label">Product Name</label>
                                            <input type="text" name="drug_name" class="form-control" id="drug_name" value="<?php echo htmlspecialchars($drug_name); ?>" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="quantity" class="form-label">Current Quantity</label>
                                            <input type="text" class="form-control" id="quantity" value="<?php echo htmlspecialchars($quantity); ?>" disabled>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="cost_price" class="form-label">Cost Price</label>
                                            <input type="number" step="0.01" name="cost_price" class="form-control" id="cost_price" value="<?php echo htmlspecialchars($cost_price); ?>" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="selling_price" class="form-label">Selling Price</label>
                                            <input type="number" step="0.01" name="selling_price" class="form-control" id="selling_price" value="<?php echo htmlspecialchars($selling_price); ?>" required>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="category" class="form-label">Category</label>
                                            <div class="input-group">
                                                <select class="form-control" id="category" name="category" required>
                                                    <option value="" disabled>Select a category</option>
                                                    <?php
                                                    // Fetch categories from database
                                                    $stmt = $pdo->prepare("SELECT category_name FROM categories ORDER BY category_name");
                                                    $stmt->execute();
                                                    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                                    foreach ($categories as $cat) {
                                                        $selected = ($cat['category_name'] == $drug['category']) ? 'selected' : '';
                                                        echo "<option value='" . htmlspecialchars($cat['category_name']) . "' {$selected}>" 
                                                            . htmlspecialchars($cat['category_name']) . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                                                    <i class="fas fa-plus"></i>
                                                </button>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="expiration_date" class="form-label">Expiration Date</label>
                                            <input type="date" name="expiration_date" class="form-control" id="expiration_date" value="<?php echo htmlspecialchars($expiration_date); ?>" required>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-12 mb-3">
                                            <div class="form-check">
                                                <input type="checkbox" 
                                                       class="form-check-input" 
                                                       id="enableVolume" 
                                                       name="enable_volume"
                                                       <?php echo (!empty($drug['volume_size']) && !empty($drug['volume_price'])) ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="enableVolume">
                                                    <i class="fas fa-boxes"></i> Enable Bulk/Volume Pricing
                                                </label>
                                            </div>
                                        </div>
                                    </div>

                                    <div id="volumeFields" style="display: none;">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="volume_size" class="form-label">
                                                    <i class="fas fa-box-open"></i> Volume Size (e.g per pack/carton)
                                                </label>
                                                <input type="number" 
                                                       name="volume_size" 
                                                       class="form-control" 
                                                       id="volume_size" 
                                                       value="<?php echo htmlspecialchars($drug['volume_size'] ?? ''); ?>" 
                                                       placeholder="Enter number of units per pack">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="volume_price" class="form-label">
                                                    <i class="fas fa-tag"></i> Volume Price
                                                </label>
                                                <input type="number" 
                                                       step="0.01" 
                                                       name="volume_price" 
                                                       class="form-control" 
                                                       id="volume_price" 
                                                       value="<?php echo htmlspecialchars($drug['volume_price'] ?? ''); ?>" 
                                                       placeholder="Enter price for bulk purchase">
                                            </div>
                                        </div>
                                    </div>

                                    <!-- <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="product_image" class="form-label">Product Image</label>
                                            <input type="file" name="product_image" class="form-control" id="product_image" accept="image/*">
                                        </div>
                                    </div> -->
                                </div>
                            </div>
        </div>

        <!-- Right Column -->
        <div class="col-lg-4">
            <!-- Image Upload Card -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Product Image</h5>
                </div>
                <div class="card-body text-center">
                    <div class="mb-3">
                        <img src="<?= htmlspecialchars($drug['image_path'] ?? 'uploads/products/default.png') ?>" 
                             class="img-thumbnail mb-2" 
                             style="max-width: 200px; height: auto;" 
                             alt="Product Image">
                    </div>
                    <div class="input-group">
                        <input type="file" class="form-control" name="product_image" accept="image/*">
                    </div>
                </div>
            </div>

            <!-- Barcode Card -->
            <div class="card">
    <div class="card-header">
        <h5 class="mb-0">Product Barcode</h5>
    </div>
    <div class="card-body text-center">
        <div class="mb-3">
            <?php if (!empty($drug['barcode'])): ?>
                <div class="barcode-display">
                    <img src="barcode.php?code=<?= htmlspecialchars($drug['barcode']) ?>" 
                         class="img-fluid" 
                         alt="Product Barcode">
                    <div class="mt-2">
                        <span class="text-muted"><?= htmlspecialchars($drug['barcode']) ?></span>
                    </div>
                </div>
            <?php else: ?>
                <div class="text-muted">
                    <i class="fas fa-barcode fa-3x mb-2"></i>
                    <p>No barcode assigned</p>
                </div>
            <?php endif; ?>
        </div>
        <?php if (!empty($drug['barcode'])): ?>
            <a href="print_barcode.php?barcode=<?= htmlspecialchars($drug['barcode']) ?>" 
               class="btn btn-outline-primary btn-sm w-100">
                <i class="fas fa-print"></i> Print Barcode
            </a>
        <?php endif; ?>
    </div>
</div>

            <!-- Stock Management Card -->
            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">Stock Management</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="add_quantity" class="form-label">Add to Quantity</label>
                                            <input type="number" name="add_quantity" class="form-control" id="add_quantity" min="0" value="0">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="remove_quantity" class="form-label">Remove from Quantity</label>
                                            <input type="number" name="remove_quantity" class="form-control" id="remove_quantity" min="0" value="0">
                                        </div>
                                    </div>
                                </div>
                            </div>

            <!-- Submit Button Card -->
            <div class="card">
                                <div class="card-body">
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="fas fa-save me-2"></i> Update Product
                                    </button>
                                </div>
                            </div>
        </div>
    </div>
</form>
            </div>
        </div>

        <!-- Footer -->
        <footer class="footer">
            <p class="mb-0">&copy; <?php echo date("Y"); ?> <?php echo htmlspecialchars($pharmacy_name); ?>. All rights reserved.</p>
        </footer>
    </div>

    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <!-- Add Category Modal -->
<div class="modal fade" id="addCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-folder-plus"></i> Add New Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="categoryForm">
                    <div class="mb-3">
                        <label for="newCategory" class="form-label">Category Name</label>
                        <input type="text" class="form-control" id="newCategory" 
                               placeholder="Enter category name" required>
                    </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="saveCategoryBtn">
                    <i class="fas fa-save"></i> Save Category
                </button>
            </div>
        </div>
    </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const enableVolumeCheckbox = document.getElementById('enableVolume');
    const volumeFields = document.getElementById('volumeFields');
    const volumeSize = document.getElementById('volume_size');
    const volumePrice = document.getElementById('volume_price');

    function toggleVolumeFields() {
        if (enableVolumeCheckbox.checked) {
            volumeFields.style.display = 'block';
            volumeSize.setAttribute('required', 'required');
            volumePrice.setAttribute('required', 'required');
        } else {
            volumeFields.style.display = 'none';
            volumeSize.removeAttribute('required');
            volumePrice.removeAttribute('required');
        }
    }

    enableVolumeCheckbox.addEventListener('change', toggleVolumeFields);
    
    // Initialize on page load
    toggleVolumeFields();
});
</script>
</body>
</html>
