{% extends "layout.html.twig" %}

{% block title %}Borrow {{ item.name }} - LocalLendables{% endblock %}

{% block content %}
    <!-- Item Details Section -->
    <section class="container pt-1 mt-1 mt-sm-3">
        <div class="row">
            <div class="col-12">

            </div>
        </div>
        
        <div class="row">
            <!-- Item Image and Basic Info -->
            <div class="col-12 col-md-6 mb-4">
                <div class="card h-100">
                    <div class="card-body">
                        <h1 class="giantish mb-3">{{ item.name }}</h1>
                        
                        <!-- Item Image -->
                        <div class="text-center mb-3">
                            {% if item.primaryLogo %}
                                <img src="/item-images/{{ item.primaryLogo }}" 
                                     alt="{{ item.name }}" 
                                     class="img-fluid rounded" 
                                     style="max-height: 300px; object-fit: cover;">
                            {% else %}
                                <div class="bg-light d-flex align-items-center justify-content-center rounded" 
                                     style="height: 200px;">
                                    <i class="fas fa-image fa-3x text-muted"></i>
                                </div>
                            {% endif %}
                        </div>
                        
                        <!-- Item Details -->
                        <div class="mb-3">
                            <div class="row">
                                <div class="col-6">
                                    <div class="small text-muted">Category:</div>
                                    <div class="small text-primary">{{ item.categoryName ?: 'Uncategorized' }}</div>
                                </div>
                                <div class="col-6">
                                    <div class="small text-muted">Owner:</div>
                                    <div class="small">
                                        <a href="/dashboard/{{ item.owner }}" class="text-decoration-none text-primary">
                                            {{ item.ownerShowName ?: item.ownerFirstName }}
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        {% if item.description %}
                        <div class="mb-3">
                            <div class="small text-muted mb-1">Description:</div>
                            <div class="midi">{{ item.description }}</div>
                        </div>
                        {% endif %}
                        
                        {% if item.pricePerDay %}
                        <div class="mb-3">
                            <div class="small text-muted">Daily Rate:</div>
                            <div class="text-success fw-bold">${{ item.pricePerDay }}</div>
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
            
            <!-- Borrow Request Form -->
            <div class="col-12 col-md-6">
                <div class="card h-100">
                    <div class="card-header">
                        <h3 class="h5 mb-0 medium">Request to Borrow</h3>
                    </div>
                    <div class="card-body">
                        <form id="borrowRequestForm" action="/borrow/{{ item.id }}/request" method="POST">
                            <!-- Date Selection with Calendar -->
                            <div class="mb-3">
                                <label for="startDate" class="form-label small">Start Date</label>
                                <input type="date" class="form-control" id="startDate" name="startDate" required 
                                       min="{{ "now"|date("Y-m-d") }}">
                                <div class="form-text">Select your preferred start date</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="endDate" class="form-label small">End Date</label>
                                <input type="date" class="form-control" id="endDate" name="endDate" required 
                                       min="{{ "now"|date("Y-m-d") }}">
                                <div class="form-text">Select your preferred end date</div>
                            </div>
                            
                            <!-- Existing Bookings Calendar -->
                            {% if existingBookings and existingBookings|length > 0 %}
                            <div class="mb-3">
                                <div class="alert alert-info">
                                    <div class="small fw-bold">Existing Bookings for this Item:</div>
                                    {% for booking in existingBookings %}
                                    <div class="small">
                                        📅 {{ booking.startDate|date("M j") }} - {{ booking.endDate|date("M j, Y") }}
                                        {% if booking.status == 'pending' %}
                                            <span class="badge bg-warning text-dark">Pending</span>
                                        {% elseif booking.status == 'approved' %}
                                            <span class="badge bg-success">Approved</span>
                                        {% endif %}
                                    </div>
                                    {% endfor %}
                                    <div class="small text-muted mt-1">Please avoid these dates when making your request.</div>
                                </div>
                            </div>
                            {% endif %}
                            
                            <!-- Optional Message -->
                            <div class="mb-3">
                                <label for="message" class="form-label small">Message to Owner (Optional)</label>
                                <textarea class="form-control" id="message" name="message" rows="3" 
                                          placeholder="Introduce yourself or explain how you'll use the item..."></textarea>
                            </div>
                            
                            <!-- Cost Calculation -->
                            {% if item.pricePerDay %}
                            <div class="mb-3">
                                <div class="alert alert-info">
                                    <div class="small text-muted">Estimated Cost:</div>
                                    <div id="costCalculation" class="fw-bold">Select dates to calculate</div>
                                </div>
                            </div>
                            {% endif %}
                            
                            <!-- Submit Button -->
                            <button type="submit" class="btn btn-primary w-100 medium" id="submitBtn">
                                Request Selected Dates to Borrow
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Legal Terms Section -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="h5 mb-0 medium">Important Terms & Conditions</h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            {% for legal in legalContent %}
                            <div class="col-12 col-md-4 mb-3">
                                <h6 class="text-primary medium">{{ legal.title }}</h6>
                                <div class="small">{{ legal.content }}</div>
                            </div>
                            {% endfor %}
                        </div>
                        
                        <div class="form-check mt-3">
                            <input class="form-check-input" type="checkbox" id="agreeTerms" required>
                            <label class="form-check-label small" for="agreeTerms">
                                I have read and agree to the terms and conditions above
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const startDateInput = document.getElementById('startDate');
        const endDateInput = document.getElementById('endDate');
        const costCalculation = document.getElementById('costCalculation');
        const submitBtn = document.getElementById('submitBtn');
        const agreeTerms = document.getElementById('agreeTerms');
        const dailyRate = {{ item.pricePerDay ?: 0 }};
        
        // Update end date minimum when start date changes
        startDateInput.addEventListener('change', function() {
            endDateInput.min = this.value;
            if (endDateInput.value && endDateInput.value < this.value) {
                endDateInput.value = this.value;
            }
            calculateCost();
        });
        
        endDateInput.addEventListener('change', calculateCost);
        
        function calculateCost() {
            if (startDateInput.value && endDateInput.value && dailyRate > 0) {
                const startDate = new Date(startDateInput.value);
                const endDate = new Date(endDateInput.value);
                const days = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
                const totalCost = days * dailyRate;
                
                if (days > 0) {
                    costCalculation.innerHTML = `${days} day${days > 1 ? 's' : ''} × $${dailyRate} = $${totalCost}`;
                } else {
                    costCalculation.innerHTML = 'End date must be after start date';
                }
            }
        }
        
        // Enable/disable submit button based on terms agreement
        agreeTerms.addEventListener('change', function() {
            submitBtn.disabled = !this.checked;
        });
        
        // Initially disable submit button
        submitBtn.disabled = true;
        
        // Form submission
        document.getElementById('borrowRequestForm').addEventListener('submit', function(e) {
            if (!agreeTerms.checked) {
                e.preventDefault();
                alert('Please agree to the terms and conditions before submitting your request.');
                return;
            }
            
            if (!startDateInput.value || !endDateInput.value) {
                e.preventDefault();
                alert('Please select both start and end dates.');
                return;
            }
            
            // Show loading state
            submitBtn.innerHTML = 'Submitting Request...';
            submitBtn.disabled = true;
        });
    });
    </script>
{% endblock %}