<?php
session_start();
require_once '../config/db.php';

// Get the supply ID from the query string
$supply_id = isset($_GET['supply_id']) ? $_GET['supply_id'] : null;
if (!$supply_id) {
    echo "<script>alert('Invalid Supply ID.'); window.location.href = 'view_supply.php';</script>";
    exit();
}

// Get the payment history for the selected supply
$sql = "SELECT amount_paid, payment_date, added_by FROM supply_payments WHERE supply_id = ? ORDER BY payment_date DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute([$supply_id]);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch supply details for display
$sql = "SELECT s.total_cost, s.total_paid, s.status, sp.business_name FROM supplies s JOIN suppliers sp ON s.supplier_id = sp.id WHERE s.id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$supply_id]);
$supply = $stmt->fetch(PDO::FETCH_ASSOC);

// Calculate balance and determine status
$balance = $supply['total_cost'] - $supply['total_paid'];
$status = ($balance == 0.00) ? 'Paid' : 'Partially Paid';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment 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;
            --warning-color: #f6c23e;
            --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);
        }

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

        .card-header {
            background: white;
            border-bottom: 1px solid #e3e6f0;
        }

        .table th {
            background: #f8f9fc;
            border-top: none;
        }

        .badge {
            padding: 0.5em 1em;
            font-size: 0.75em;
        }

        .badge-success {
            background-color: var(--success-color);
        }

        .badge-warning {
            background-color: var(--warning-color);
            color: #fff;
        }

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

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

        .receipt-container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 2rem;
            border-radius: 0.5rem;
            box-shadow: 0 0.15rem 1.75rem rgba(58, 59, 69, 0.15);
        }

        .receipt-header {
            text-align: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 2px dashed #e3e6f0;
        }

        .receipt-company {
            font-size: 1.5rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }

        .receipt-details {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1.5rem;
            margin-bottom: 2rem;
            padding: 1rem;
            background: #f8f9fc;
            border-radius: 0.5rem;
        }

        .receipt-detail-item {
            display: flex;
            flex-direction: column;
        }

        .receipt-detail-label {
            font-size: 0.875rem;
            color: #858796;
            margin-bottom: 0.25rem;
        }

        .receipt-detail-value {
            font-size: 1.1rem;
            font-weight: 600;
        }

        .receipt-table {
            margin-bottom: 2rem;
        }

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

        .receipt-footer {
            text-align: center;
            margin-top: 2rem;
            padding-top: 1rem;
            border-top: 2px dashed #e3e6f0;
            color: #858796;
        }

        @media print {
            body {
                background: white;
            }
            
            .receipt-container {
                box-shadow: none;
                padding: 0;
            }
            
            .no-print {
                display: none !important;
            }
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <div class="mb-4 no-print">
            <div class="d-flex justify-content-between align-items-center">
                <a href="view_supply.php" class="btn btn-outline-primary">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <div>
                    <?php if ($balance > 0): ?>
                        <button type="button" class="btn btn-success" onclick="showPaymentModal()">
                            <i class="fas fa-plus mr-1"></i> Add Payment
                        </button>
                    <?php endif; ?>
                    <button type="button" class="btn btn-primary ml-2" onclick="window.print()">
                        <i class="fas fa-print mr-1"></i> Print
                    </button>
                </div>
            </div>
        </div>

        <div class="receipt-container">
            <div class="receipt-header">
                <div class="receipt-company">Payment History</div>
                <div>Statement of Supplier Payments</div>
            </div>

            <div class="receipt-details">
                <div class="receipt-detail-item">
                    <span class="receipt-detail-label">Supplier</span>
                    <span class="receipt-detail-value"><?php echo htmlspecialchars($supply['business_name']); ?></span>
                </div>
                <div class="receipt-detail-item">
                    <span class="receipt-detail-label">Total Cost</span>
                    <span class="receipt-detail-value">₦<?php echo number_format($supply['total_cost'], 2); ?></span>
                </div>
                <div class="receipt-detail-item">
                    <span class="receipt-detail-label">Amount Paid</span>
                    <span class="receipt-detail-value">₦<?php echo number_format($supply['total_paid'], 2); ?></span>
                </div>
                <div class="receipt-detail-item">
                    <span class="receipt-detail-label">Balance</span>
                    <span class="receipt-detail-value">₦<?php echo number_format($balance, 2); ?></span>
                </div>
            </div>

            <div class="receipt-table">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Payment Date</th>
                            <th>Amount Paid</th>
                            <th>Recorded By</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($payments) > 0): ?>
                            <?php foreach ($payments as $payment): ?>
                                <tr>
                                    <td><?php echo date('d M Y', strtotime($payment['payment_date'])); ?></td>
                                    <td>₦<?php echo number_format($payment['amount_paid'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($payment['added_by']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="3" class="text-center text-muted">No payments recorded</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="receipt-footer">
                <p class="mb-0">Generated on <?php echo date('d M Y, h:i A'); ?></p>
                <p class="mb-0">This is a computer-generated document.</p>
            </div>
        </div>
    </div>

    <!-- Payment Modal -->
    <div class="modal fade" id="paymentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-money-bill mr-2"></i>Add Payment
                    </h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form action="process_payment.php" method="POST" onsubmit="return validatePayment()">
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Amount</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">₦</span>
                                </div>
                                <input type="number" 
                                       class="form-control" 
                                       name="amount_paid" 
                                       step="0.01" 
                                       min="1" 
                                       max="<?php echo $balance; ?>" 
                                       required>
                            </div>
                            <small class="text-muted">Maximum payment: ₦<?php echo number_format($balance, 2); ?></small>
                        </div>
                        <input type="hidden" name="supply_id" value="<?php echo $supply_id; ?>">
                        <input type="hidden" name="added_by" value="<?php echo htmlspecialchars($_SESSION['username']); ?>">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save mr-1"></i>Save Payment
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

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

        function validatePayment() {
            const amount = parseFloat(document.querySelector('input[name="amount_paid"]').value);
            const balance = <?php echo $balance; ?>;
            
            if (isNaN(amount) || amount <= 0) {
                alert('Please enter a valid payment amount.');
                return false;
            }
            
            if (amount > balance) {
                alert('Payment amount cannot exceed the remaining balance of ₦' + balance.toFixed(2));
                return false;
            }
            
            return confirm('Are you sure you want to record this payment of ₦' + amount.toFixed(2) + '?');
        }

        // Initialize modal
        $(document).ready(function() {
            // Enable Bootstrap modal
            $('.modal').modal({
                show: false,
                backdrop: 'static'
            });

            // Clear form on modal close
            $('#paymentModal').on('hidden.bs.modal', function () {
                $(this).find('form')[0].reset();
            });
        });
    </script>
</body>
</html>
