<?php
session_start(); // Start the session

// Include the database connection
require_once '../config/db.php';

// Get the supply ID from the query parameter
$supplyId = isset($_GET['id']) ? $_GET['id'] : null;

if ($supplyId) {
    // Fetch supply information
    $sql = "SELECT s.supply_date, s.total_cost, s.total_paid, sup.business_name 
            FROM supplies s 
            JOIN suppliers sup ON s.supplier_id = sup.id 
            WHERE s.id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$supplyId]);
    $supply = $stmt->fetch();

    // Fetch supply details (drugs)
    $sql = "SELECT sd.drug_id, d.drug_name, sd.quantity_supplied, sd.cost_price 
            FROM supply_details sd 
            JOIN drugs d ON sd.drug_id = d.id 
            WHERE sd.supply_id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$supplyId]);
    $supplyDetails = $stmt->fetchAll();
} else {
    echo "Invalid supply ID.";
    exit;
}

// Handle the return action
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $totalReturnCost = 0; // Variable to keep track of the total return cost
    $totalReturnQuantity = 0; // Variable to track the total quantity returned

    foreach ($supplyDetails as $detail) {
        $drugId = $detail['drug_id'];
        $quantityToReturn = isset($_POST["return_quantity_$drugId"]) ? (int)$_POST["return_quantity_$drugId"] : 0;
        $reason = isset($_POST["reason_$drugId"]) ? $_POST["reason_$drugId"] : null;

        if ($quantityToReturn > 0 && $quantityToReturn <= $detail['quantity_supplied']) {
            $pdo->beginTransaction();

            try {
                // Update the quantity in the drugs table
                $sql = "UPDATE drugs SET quantity = quantity - ? WHERE id = ?"; // Adding back the returned quantity
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$quantityToReturn, $drugId]);

                // Update the quantity in the supply_details table
                $sql = "UPDATE supply_details SET quantity_supplied = quantity_supplied - ? 
                        WHERE supply_id = ? AND drug_id = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$quantityToReturn, $supplyId, $drugId]);

                // Insert into returns table
                $sql = "INSERT INTO returns (supply_id, drug_id, quantity_returned, reason) VALUES (?, ?, ?, ?)";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$supplyId, $drugId, $quantityToReturn, $reason]);

                // Calculate the total return cost
                $returnCost = $quantityToReturn * $detail['cost_price'];
                $totalReturnCost += $returnCost;
                $totalReturnQuantity += $quantityToReturn;

                $pdo->commit();

                // Set the success message in session
                $_SESSION['success_message'] = 'Return processed successfully.';
            } catch (Exception $e) {
                $pdo->rollBack();
                echo "Error: " . $e->getMessage();
            }
        }
    }

    // Update the supply total cost after the return
    if ($totalReturnCost > 0) {
        $sql = "UPDATE supplies SET total_cost = total_cost - ? WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$totalReturnCost, $supplyId]);
    }

    // Optionally, update the total paid based on the return quantity and the cost
    if ($totalReturnCost > 0) {
        // Adjust the total paid based on how much was returned. (For example, you can reduce the total paid by the return amount)
        $newTotalPaid = $supply['total_paid'] - $totalReturnCost;

        // Update the total paid in the supplies table
        $sql = "UPDATE supplies SET total_paid = ? WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$newTotalPaid, $supplyId]);
    }

    // Redirect to the view supply page
    header("Location: view_supply.php");
    exit;
}
?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Supply Details - 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;
            --primary-color: #4e73df;
            --success-color: #1cc88a;
            --danger-color: #e74a3b;
        }

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

        .info-card {
            background: linear-gradient(135deg, var(--primary-color), #224abe);
            color: white;
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 0.15rem 1.75rem rgba(58, 59, 69, 0.15);
        }

        .info-card h6 {
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 0.5rem;
            font-size: 0.8rem;
        }

        .info-card p {
            margin: 0;
            font-size: 1.25rem;
            font-weight: 500;
        }

        .card {
            border: none;
            border-radius: 0.5rem;
            box-shadow: 0 0.15rem 1.75rem rgba(58, 59, 69, 0.15);
        }

        .card-header {
            background-color: #fff;
            border-bottom: 1px solid #e3e6f0;
            padding: 1rem 1.25rem;
        }

        .table th {
            background-color: #f8f9fc;
            font-weight: 600;
            border-top: none;
        }

        .table td {
            vertical-align: middle;
        }

        .btn-return {
            color: #fff;
            background-color: var(--danger-color);
            border: none;
        }

        .btn-return:hover {
            background-color: #be3326;
        }

        .modal-content {
            border: none;
            border-radius: 0.5rem;
        }

        .form-control {
            border-radius: 0.35rem;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0 text-gray-800">Supply Details</h1>
            <a href="view_supply.php" class="btn btn-outline-primary">
                <i class="fas fa-arrow-left"></i> Back to Supplies
            </a>
        </div>

        <?php if ($supply): ?>
            <!-- Supply Information Cards -->
            <div class="row">
                <div class="col-xl-3 col-md-6">
                    <div class="info-card">
                        <h6><i class="fas fa-building mr-2"></i>Supplier</h6>
                        <p><?php echo htmlspecialchars($supply['business_name']); ?></p>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6">
                    <div class="info-card">
                        <h6><i class="fas fa-calendar mr-2"></i>Supply Date</h6>
                        <p><?php echo htmlspecialchars($supply['supply_date']); ?></p>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6">
                    <div class="info-card">
                        <h6><i class="fas fa-money-bill mr-2"></i>Total Cost</h6>
                        <p>₦<?php echo number_format($supply['total_cost'], 2); ?></p>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6">
                    <div class="info-card">
                        <h6><i class="fas fa-credit-card mr-2"></i>Amount Paid</h6>
                        <p>₦<?php echo number_format($supply['total_paid'], 2); ?></p>
                    </div>
                </div>
            </div>

            <!-- Products Table -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="font-weight-bold text-primary mb-0">Supply Details</h5>
                    <button type="button" class="btn btn-danger btn-sm" onclick="showReturnModal()">
                        <i class="fas fa-undo mr-1"></i> Return Items
                    </button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Product Name</th>
                                    <th>Quantity</th>
                                    <th>Unit Price</th>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($supplyDetails as $detail): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($detail['drug_name']); ?></td>
                                        <td><?php echo htmlspecialchars($detail['quantity_supplied']); ?></td>
                                        <td>₦<?php echo number_format($detail['cost_price'], 2); ?></td>
                                        <td>₦<?php echo number_format($detail['quantity_supplied'] * $detail['cost_price'], 2); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Return Modal -->
            <div class="modal fade" id="returnModal" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-undo mr-2"></i>Return Products
                            </h5>
                            <button type="button" class="close" data-dismiss="modal">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <form method="post" onsubmit="return confirmReturn()">
                            <div class="modal-body">
                                <div class="row">
                                    <?php foreach ($supplyDetails as $detail): ?>
                                        <div class="col-md-6 mb-3">
                                            <div class="card">
                                                <div class="card-body">
                                                    <h6 class="font-weight-bold mb-3">
                                                        <?php echo htmlspecialchars($detail['drug_name']); ?>
                                                    </h6>
                                                    <div class="form-group">
                                                        <label>Return Quantity</label>
                                                        <input type="number" 
                                                               name="return_quantity_<?php echo $detail['drug_id']; ?>" 
                                                               class="form-control" 
                                                               min="0" 
                                                               max="<?php echo $detail['quantity_supplied']; ?>"
                                                               placeholder="Max: <?php echo $detail['quantity_supplied']; ?>">
                                                    </div>
                                                    <div class="form-group mb-0">
                                                        <label>Return Reason</label>
                                                        <textarea name="reason_<?php echo $detail['drug_id']; ?>" 
                                                                  class="form-control" 
                                                                  rows="2"
                                                                  placeholder="Why are you returning this product?"></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                <button type="submit" class="btn btn-danger">
                                    <i class="fas fa-check mr-1"></i>Confirm Return
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle mr-2"></i>Supply not found.
            </div>
        <?php endif; ?>
    </div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <script>
        function showReturnModal() {
            $('#returnModal').modal('show');
        }

        function confirmReturn() {
            let hasItems = false;

            // Check if any items are being returned
            document.querySelectorAll('input[type="number"]').forEach(input => {
                if (parseInt(input.value) > 0) {
                    hasItems = true;
                }
            });

            if (!hasItems) {
                alert('Please enter quantity for at least one product to return');
                return false;
            }

            return confirm('Are you sure you want to return these products?');
        }

        // Add input validation
        document.querySelectorAll('input[type="number"]').forEach(input => {
            input.addEventListener('change', function() {
                const max = parseInt(this.getAttribute('max'));
                const value = parseInt(this.value);
                
                if (value > max) {
                    this.value = max;
                    alert(`Maximum return quantity is ${max}`);
                }
            });
        });

        // Initialize Bootstrap components
        $(document).ready(function() {
            $('.modal').modal({
                show: false
            });
        });
    </script>
</body>
</html>
