<?php


// Include database connection
include '../config/db.php'; // Adjust the path as necessary
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}


// Function to log transactions
function log_transaction($pdo, $username, $activity_type, $activity_details) {
    try {
        // Prepare the SQL statement to insert a new transaction
        $stmt = $pdo->prepare("INSERT INTO transactions (username, activity_type, activity_details) VALUES (?, ?, ?)");
        
        // Execute the SQL statement with the provided parameters
        $stmt->execute([$username, $activity_type, $activity_details]);
    } catch (PDOException $e) {
        die("Transaction log failed: " . $e->getMessage());
    }
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['csv_file'])) {
    $file = $_FILES['csv_file'];
    $allowedExts = ['csv'];
    $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);

    if (in_array($fileExtension, $allowedExts)) {
        $uploadDir = 'uploads/';
        $uploadFile = $uploadDir . basename($file['name']);

        if (move_uploaded_file($file['tmp_name'], $uploadFile)) {
            echo "CSV file successfully uploaded.<br>";

            try {
                // Open the CSV file for reading
                $csvHandle = fopen($uploadFile, 'r');
                if (!$csvHandle) {
                    die("Failed to open the CSV file.");
                }

                // Skip the header row (uncomment if your CSV has headers)
                fgetcsv($csvHandle);

                // Prepare the SQL statement for inserting drugs
                $stmt = $pdo->prepare("INSERT INTO drugs (drug_name, quantity, cost_price, selling_price, volume_size, volume_price, category, expiration_date, profit) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

                while (($data = fgetcsv($csvHandle)) !== false) {
                    // Map CSV data to variables
                    $drug_name = htmlspecialchars($data[0]);
                    $quantity = htmlspecialchars($data[1]);
                    $cost_price = htmlspecialchars($data[2]);
                    $selling_price = htmlspecialchars($data[3]);
                    $volume_size = htmlspecialchars($data[4]);
                    $volume_price = htmlspecialchars($data[5]);
                    $category = htmlspecialchars($data[6]);
                    $expiration_date = htmlspecialchars($data[7]);

                    // Calculate profit
                    $profit = $selling_price - $cost_price;

                    // Execute the prepared statement
                    $stmt->execute([$drug_name, $quantity, $cost_price, $selling_price, $volume_size, $volume_price, $category, $expiration_date, $profit]);
                }

                fclose($csvHandle);

                echo "Drugs imported successfully.<br>";
            } catch (PDOException $e) {
                die("Error importing drugs: " . $e->getMessage());
            }
        } else {
            echo "Failed to upload the CSV file.";
        }
    } else {
        echo "Invalid file format. Please upload a CSV file.";
    }
}
// Handle form submission for adding a drug
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_drug'])) {
    // Sanitize the input data from the form
    $drug_name = htmlspecialchars($_POST['drug_name']);
    $cost_price = htmlspecialchars($_POST['cost_price']);
    $selling_price = htmlspecialchars($_POST['selling_price']);
    $category = htmlspecialchars($_POST['category']);
    $expiration_date = htmlspecialchars($_POST['expiration_date']);
    $quantity = htmlspecialchars($_POST['quantity']);
    $volume_size = htmlspecialchars($_POST['volume_size']);
    $volume_price = htmlspecialchars($_POST['volume_price']);
    $barcode = htmlspecialchars($_POST['barcode']);
    $image_path = null;

    // Handle image upload
    if (isset($_FILES['product_image']) && $_FILES['product_image']['error'] === 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
        $filename = $_FILES['product_image']['name'];
        $file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        if (!in_array($file_ext, $allowed)) {
            $_SESSION['error'] = "Invalid file format. Allowed formats: " . implode(', ', $allowed);
            header("Location: add_drug.php");
            exit();
        }

        if ($_FILES['product_image']['size'] > 2 * 1024 * 1024) {
            $_SESSION['error'] = "File size too large. Maximum size is 2MB.";
            header("Location: add_drug.php");
            exit();
        }

        // Create upload directory if it doesn't exist
        $upload_dir = 'uploads/products/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        // Generate unique filename
        $new_filename = uniqid() . '.' . $file_ext;
        $upload_path = $upload_dir . $new_filename;

        if (move_uploaded_file($_FILES['product_image']['tmp_name'], $upload_path)) {
            $image_path = $upload_path;
        }
    }

    // Calculate the profit
    $profit = $selling_price - $cost_price;

    try {
        // Insert the new drug into the drugs table with the calculated profit
        $stmt = $pdo->prepare("INSERT INTO drugs (drug_name, quantity, cost_price, selling_price, volume_size, volume_price, category, expiration_date, profit, barcode, image_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$drug_name, $quantity, $cost_price, $selling_price, $volume_size, $volume_price, $category, $expiration_date, $profit, $barcode, $image_path]);

        // Ensure the username is stored in the session
        if (!isset($_SESSION['username'])) {
            die("Error: Username not found in the session."); // Handle the error if the username is not set
        }

        $username = $_SESSION['username']; // Fetch the logged-in user's username from the session
         // Get the drug_id of the newly inserted drug
         $drug_id = $pdo->lastInsertId();

        // Prepare activity details for logging
        $activity_type = "Add Drug";
        $activity_details = "$username added drug: $drug_name, Quantity: $quantity, Cost Price: $cost_price, Selling Price: $selling_price, Volume Size: $volume_size, Volume Price: $volume_price, Category: $category, Expiration Date: $expiration_date";

        // Log the transaction with the username
        log_transaction($pdo, $username, $activity_type, $activity_details);


        // Log the action to the drug history table
        $history_stmt = $pdo->prepare("INSERT INTO drug_history (drug_id, action, quantity, details, user, action_date) VALUES (?, ?, ?, ?, ?, ?)");
        $history_stmt->execute([$drug_id, 'Add Drug', $quantity, $activity_details, $username, date('Y-m-d H:i:s')]);

        // Redirect to the manage drugs page after adding the drug
        header("Location: manage_drugs.php"); // Change this to your actual drugs management page
        exit();
    } catch (PDOException $e) {
        die("Insert failed: " . $e->getMessage()); // Handle error if drug insertion fails
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Product | Store Management</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <style>
        body {
            background-color: #f5f6fa;
            font-family: Arial, sans-serif;
            font-size: 14px;
        }

        .container {
            padding: 20px;
            scroll-padding-top: 70px;
        }

        .top-bar {
            background-color: #ffffff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .table-container {
            background: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #2c3e50, #3498db);
            border: none;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
        }

        #suggestions {
            border: 1px solid #ddd;
            border-radius: 0 0 5px 5px;
            max-height: 200px;
            overflow-y: auto;
            position: absolute;
            background: white;
            width: calc(100% - 24px);
            z-index: 1001;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        #suggestions div {
            padding: 10px;
            cursor: pointer;
            transition: background 0.3s ease;
        }

        #suggestions div:hover {
            background: #f8f9fa;
        }

        .form-label {
            font-weight: 500;
            color: #2c3e50;
        }

        .form-control:focus {
            border-color: #3498db;
            box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
        }

        .custom-file-label::after {
            content: "Browse";
        }

        .image-preview {
            max-width: 200px;
            max-height: 200px;
            margin-top: 10px;
        }

        .barcode-input {
            font-family: 'Courier New', Courier, monospace;
            letter-spacing: 1px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="top-bar">
            <div class="d-flex justify-content-between align-items-center">
                <h2><i class="fas fa-plus-circle"></i> Add New Product</h2>
                <div>
                    <a href="admin_dashboard.php" class="btn btn-primary">
                        <i class="fas fa-arrow-left"></i> Dashboard
                    </a>
                    <a href="manage_drugs.php" class="btn btn-primary">
                        <i class="fas fa-list"></i> View Products
                    </a>
                </div>
            </div>
        </div>

        <?php if (isset($_SESSION['success']) || isset($_SESSION['error'])): ?>
            <div class="alert alert-<?= isset($_SESSION['success']) ? 'success' : 'danger' ?> alert-dismissible fade show" role="alert">
                <i class="fas fa-<?= isset($_SESSION['success']) ? 'check' : 'exclamation' ?>-circle"></i> 
                <?= $_SESSION['success'] ?? $_SESSION['error'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['success'], $_SESSION['error']); ?>
        <?php endif; ?>

        <!-- CSV Import Section -->
        <div class="table-container">
            <h4 class="mb-3"><i class="fas fa-file-csv"></i> Import Products from CSV</h4>
            <form method="POST" enctype="multipart/form-data">
                <div class="row g-3">
                    <div class="col-md-8">
                        <input type="file" class="form-control" id="csv_file" name="csv_file" accept=".csv" required>
                    </div>
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-upload"></i> Import
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- Add Product Form -->
        <div class="table-container">
            <h4 class="mb-3"><i class="fas fa-plus"></i> Add Product Manually</h4>
            <form method="POST" enctype="multipart/form-data">
                <div class="row">
                    <!-- Left Column -->
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="drug_name" class="form-label"> <i class="fas fa-pills"></i> Drug Name</label>
                            <input type="text" class="form-control" id="drug_name" name="drug_name" required autocomplete="off">
                            <div id="suggestions"></div> <!-- Suggestions container -->
                        </div>
                        <div class="mb-3">
                            <label for="quantity" class="form-label"> <i class="fas fa-box"></i> Quantity</label>
                            <input type="number" class="form-control" id="quantity" name="quantity" required>
                        </div>
                        <div class="mb-3">
                            <label for="cost_price" class="form-label"> <i class="fas fa-money-bill-wave"></i> Cost Price</label>
                            <input type="number" step="0.01" class="form-control" id="cost_price" name="cost_price" required>
                        </div>
                        <div class="mb-3">
                            <label for="selling_price" class="form-label"> <i class="fas fa-tag"></i> Selling Price</label>
                            <input type="number" step="0.01" class="form-control" id="selling_price" name="selling_price" required>
                        </div>
                    </div>

                    <!-- Right Column -->
                    <div class="col-md-6">
                        <div class="mb-3">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="enableVolume" name="enable_volume">
                                <label class="form-check-label" for="enableVolume">
                                    <i class="fas fa-boxes"></i> Enable Bulk/Volume Pricing
                                </label>
                            </div>
                        </div>

                        <div id="volumeFields" style="display: none;">
                            <div class="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" 
                                       class="form-control" 
                                       id="volume_size" 
                                       name="volume_size" 
                                       placeholder="Enter number of units per pack">
                            </div>
                            <div class="mb-3">
                                <label for="volume_price" class="form-label">
                                    <i class="fas fa-tag"></i> Volume Price
                                </label>
                                <input type="number" 
                                       step="0.01" 
                                       class="form-control" 
                                       id="volume_price" 
                                       name="volume_price" 
                                       placeholder="Enter price for bulk purchase">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="category" class="form-label">
                                <i class="fas fa-th-list"></i> Category
                            </label>
                            <div class="input-group">
                                <select class="form-control" id="category" name="category" required>
                                    <option value="" disabled selected>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) {
                                        echo "<option value='" . htmlspecialchars($cat['category_name']) . "'>" 
                                        . 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="mb-3">
                            <label for="expiration_date" class="form-label"> <i class="fas fa-calendar-alt"></i> Expiration Date</label>
                            <input type="date" class="form-control" id="expiration_date" name="expiration_date" required>
                        </div>
                        <div class="mb-3">
                            <label for="barcode" class="form-label barcode-input">
                                <i class="fas fa-barcode"></i> Barcode
                            </label>
                            <input type="text" class="form-control" id="barcode" name="barcode" 
                                   placeholder="Enter barcode or scan">
                        </div>

                        <div class="mb-3">
                            <label for="product_image" class="form-label">
                                <i class="fas fa-image"></i> Product Image
                            </label>
                            <input type="file" class="form-control" id="product_image" name="product_image" 
                                   accept="image/*">
                            <small class="text-muted">Max file size: 2MB. Supported formats: JPG, PNG, GIF</small>
                        </div>
                    </div>
                </div>

                <!-- Buttons -->
                <div class="mt-4">
                    <button type="submit" name="add_drug" class="btn btn-primary"> <i class="fas fa-plus"></i> Add Product</button>
                   
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Example drug names (replace with a comprehensive list)
      


            // Add more drugs as needed
    
            
document.addEventListener('DOMContentLoaded', function () {
    const drugInput = document.getElementById('drug_name');
    const suggestionsDiv = document.getElementById('suggestions'); // Suggestions div
    let hasFocused = false; // Track if focus has been applied

    // Handle input events and suggest drugs
    drugInput.addEventListener('input', function () {
        const query = this.value.toLowerCase();
        suggestionsDiv.innerHTML = ''; // Clear previous suggestions
        suggestionsDiv.style.display = 'none'; // Hide suggestions by default

        if (query.length >= 2) { // Trigger search after 2 characters
            // Fetch suggestions from the backend (you can also filter on client side if necessary)
            fetch(`search_drugs.php?query=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.length > 0) {
                        suggestionsDiv.style.display = 'block'; // Show suggestions
                        data.forEach(drug => {
                            const suggestionDiv = document.createElement('div');
                            suggestionDiv.textContent = drug.drug_name;
                            suggestionDiv.addEventListener('click', function () {
                                drugInput.value = drug.drug_name; // Set input value to selected drug
                                suggestionsDiv.innerHTML = ''; // Clear suggestions
                                suggestionsDiv.style.display = 'none'; // Hide suggestions
                                drugInput.blur(); // Blur the input immediately after selection

                                // Check if the drug exists in the store
                                checkDrugInStore(drug.drug_name); // Trigger the check
                            });
                            suggestionsDiv.appendChild(suggestionDiv);
                        });
                    } else {
                        suggestionsDiv.style.display = 'none'; // Hide if no matches
                    }
                })
                .catch(error => {
                    console.error('Error fetching suggestions:', error);
                });
        }
    });

    // Hide suggestions when clicking outside or outside the input
    document.addEventListener('click', function (event) {
        if (!suggestionsDiv.contains(event.target) && event.target !== drugInput) {
            suggestionsDiv.innerHTML = ''; // Clear suggestions
            suggestionsDiv.style.display = 'none'; // Hide suggestions
            drugInput.blur(); // Remove focus from input
        }
    });

    // Function to check if the drug exists in the store
    function checkDrugInStore(drugName) {
        suggestionsDiv.innerHTML = '<div>Checking availability...</div>';
        suggestionsDiv.style.display = 'block'; // Ensure the message is visible

        // Send AJAX request to check the drug
        $.ajax({
            url: 'check_drug.php', // Path to your backend script
            type: 'POST',
            dataType: 'json',
            data: { drug_name: drugName },
            success: function(response) {
                suggestionsDiv.innerHTML = ''; // Clear the checking message

                if (response.exists) {
                    // If the drug exists, show an alert before redirecting
                    const proceed = confirm(`The drug "${drugName}" already exists in the store. Do you want to update it?`);
                    if (proceed) {
                        // Redirect to edit page if the user confirms
                        window.location.href = `edit_drug.php?id=${response.id}`;
                    }
                } else {
                    alert("The drug does not exist in the store.");
                }
            },
            error: function(xhr, status, error) {
                console.error('Error checking drug:', error);
                alert("Error occurred while checking the drug.");
            }
        });
    }
});

// Add this to your existing script section
document.getElementById('barcode').addEventListener('keypress', function(e) {
    // Most barcode scanners terminate with a return/enter key
    if (e.key === 'Enter') {
        e.preventDefault(); // Prevent form submission
        // You can add additional processing here
        // For example, auto-focus the next field
        document.getElementById('product_image').focus();
    }
});

// Add to existing script section
document.getElementById('saveCategoryBtn').addEventListener('click', function() {
    const categoryInput = document.getElementById('newCategory');
    const categoryName = categoryInput.value.trim().toUpperCase();
    
    if (!categoryName) {
        alert('Please enter a category name');
        return;
    }

    fetch('add_category.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'category_name=' + encodeURIComponent(categoryName)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Add new category to select
            const select = document.getElementById('category');
            const option = new Option(categoryName, categoryName);
            select.add(option);
            select.value = categoryName;
            
            // Reset and close modal
            categoryInput.value = '';
            bootstrap.Modal.getInstance(document.getElementById('addCategoryModal')).hide();
        } else {
            alert(data.message || 'Failed to add category');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to add category');
    });
});
</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');

    enableVolumeCheckbox.addEventListener('change', function() {
        if (this.checked) {
            volumeFields.style.display = 'block';
            // Make fields required when enabled
            volumeSize.setAttribute('required', 'required');
            volumePrice.setAttribute('required', 'required');
        } else {
            volumeFields.style.display = 'none';
            // Remove required attribute and clear values when disabled
            volumeSize.removeAttribute('required');
            volumePrice.removeAttribute('required');
            volumeSize.value = '';
            volumePrice.value = '';
        }
    });

    // Initialize on page load
    volumeFields.style.display = enableVolumeCheckbox.checked ? 'block' : 'none';
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Get the save category button and modal elements
    const saveCategoryBtn = document.getElementById('saveCategoryBtn');
    const addCategoryModal = document.getElementById('addCategoryModal');
    const modal = new bootstrap.Modal(addCategoryModal);
    
    // Verify elements exist
    if (!saveCategoryBtn) {
        console.error('Save category button not found');
        return;
    }

    // Add click event listener to save category button
    saveCategoryBtn.addEventListener('click', function() {
        const categoryInput = document.getElementById('newCategory');
        const categorySelect = document.getElementById('category');
        const categoryName = categoryInput.value.trim().toUpperCase();
        
        if (!categoryName) {
            alert('Please enter a category name');
            return;
        }

        // Show loading state
        saveCategoryBtn.disabled = true;
        saveCategoryBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';

        const formData = new FormData();
        formData.append('category_name', categoryName);

        fetch('add_category.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Add new option to select dropdown
                const option = new Option(categoryName, categoryName);
                categorySelect.add(option);
                categorySelect.value = categoryName;

                // Reset input
                categoryInput.value = '';
                
                // Close modal properly using Bootstrap modal instance
                modal.hide();
                
                // Show success message
                alert('Category added successfully!');

                // Re-enable all form elements and modal triggers
                document.querySelectorAll('button, input, select').forEach(element => {
                    element.disabled = false;
                });

                // Reinitialize modal trigger
                const modalTriggers = document.querySelectorAll('[data-bs-toggle="modal"]');
                modalTriggers.forEach(trigger => {
                    trigger.addEventListener('click', () => {
                        modal.show();
                    });
                });
            } else {
                throw new Error(data.message || 'Failed to add category');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert(error.message || 'Failed to add category');
        })
        .finally(() => {
            // Reset button state
            saveCategoryBtn.disabled = false;
            saveCategoryBtn.innerHTML = '<i class="fas fa-save"></i> Save Category';
            
            // Ensure modal backdrop is removed
            document.body.classList.remove('modal-open');
            const backdrop = document.querySelector('.modal-backdrop');
            if (backdrop) {
                backdrop.remove();
            }
        });
    });
});
</script>

</body>
</html>
