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

{% block title %}Loan Agreement - LocalLendables{% endblock %}

{% block content %}
<div class="container-fluid px-3 py-4">
  <div class="row">
    <div class="col-md-10 mx-auto">
      
      <!-- Header -->
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-file-contract me-2"></i>Loan Agreement</h2>
        <div>
          <button onclick="window.print()" class="btn btn-outline-secondary me-2">
            <i class="fas fa-print me-2"></i>Print
          </button>
          <a href="/dashboard/{{ currentUser.id }}" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
          </a>
        </div>
      </div>

      <!-- Agreement Status -->
      <div class="alert {% if agreement.status == 'signed' %}alert-success{% elseif agreement.status == 'pending' %}alert-warning{% else %}alert-info{% endif %} mb-4">
        <div class="row align-items-center">
          <div class="col-md-8">
            <h5 class="mb-1">
              {% if agreement.status == 'signed' %}
                <i class="fas fa-check-circle me-2"></i>Agreement Fully Signed
              {% elseif agreement.status == 'pending' %}
                <i class="fas fa-clock me-2"></i>Awaiting Signatures
              {% else %}
                <i class="fas fa-info-circle me-2"></i>Agreement {{ agreement.status|title }}
              {% endif %}
            </h5>
            <p class="mb-0">
              {% if agreement.status == 'signed' %}
                This agreement is fully executed and ready for use.
              {% elseif agreement.borrowerSignedAt and agreement.ownerSignedAt %}
                Both parties have signed this agreement.
              {% elseif agreement.borrowerSignedAt %}
                Borrower has signed. Waiting for owner signature.
              {% elseif agreement.ownerSignedAt %}
                Owner has signed. Waiting for borrower signature.
              {% else %}
                Both parties need to sign this agreement.
              {% endif %}
            </p>
          </div>
          <div class="col-md-4 text-end">
            {% if agreement.status == 'pending' %}
              {% if currentUser.id == agreement.borrowerId and not agreement.borrowerSignedAt %}
                <button class="btn btn-success" onclick="showSignatureModal('borrower')">
                  <i class="fas fa-signature me-2"></i>Sign Agreement
                </button>
              {% elseif currentUser.id == agreement.ownerId and not agreement.ownerSignedAt %}
                <button class="btn btn-success" onclick="showSignatureModal('owner')">
                  <i class="fas fa-signature me-2"></i>Sign Agreement
                </button>
              {% endif %}
            {% endif %}
          </div>
        </div>
      </div>

      <!-- Agreement Document -->
      <div class="card">
        <div class="card-body p-5">
          
          <!-- Agreement Header -->
          <div class="text-center mb-5">
            <h1 class="h2">Lendable Item Signed Handshake Agreement</h1>
            <p class="text-muted">Date: {{ agreement.createdAt|date('M j, Y') }}</p>
            <hr class="my-4">
          </div>

          <!-- Parties -->
          <div class="row mb-4">
            <div class="col-md-6">
              <h5>Owner (Lender)</h5>
              <div class="bg-light p-3 rounded">
                <strong>{{ owner.firstName ~ ' ' ~ owner.lastName }}</strong><br>
                {% if owner.email %}{{ owner.email }}<br>{% endif %}
                {% if owner.phone %}{{ owner.phone }}<br>{% endif %}
                {% if owner.address %}{{ owner.address }}<br>{% endif %}
                {% if owner.town %}{{ owner.town }}, {{ owner.zipcode }}{% endif %}
              </div>
            </div>
            <div class="col-md-6">
              <h5>Borrower</h5>
              <div class="bg-light p-3 rounded">
                <strong>{{ borrower.firstName ~ ' ' ~ borrower.lastName }}</strong><br>
                {% if borrower.email %}{{ borrower.email }}<br>{% endif %}
                {% if borrower.phone %}{{ borrower.phone }}<br>{% endif %}
                {% if borrower.address %}{{ borrower.address }}<br>{% endif %}
                {% if borrower.town %}{{ borrower.town }}, {{ borrower.zipcode }}{% endif %}
              </div>
            </div>
          </div>

          <!-- Item Details -->
          <div class="mb-4">
            <h5>Item Being Lent</h5>
            <div class="row">
              <div class="col-md-3">
                {% if item.primaryLogo %}
                  <img src="/lendable_items/{{ item.primaryLogo }}" 
                       alt="{{ item.name }}" 
                       class="img-fluid rounded shadow-sm">
                {% endif %}
              </div>
              <div class="col-md-9">
                <div class="bg-light p-3 rounded">
                  <h6>{{ item.name }}</h6>
                  {% if item.description %}
                  <p class="mb-2">{{ item.description }}</p>
                  {% endif %}
                  <div class="row">
                    <div class="col-sm-6">
                      <strong>Category:</strong> {{ category.name }}<br>
                      <strong>Item ID:</strong> #{{ item.id }}
                    </div>
                    <div class="col-sm-6">
                      <strong>Borrow Date:</strong> {{ agreement.startDate|date('M j, Y') }}<br>
                      <strong>Intended Return Date:</strong> {{ agreement.endDate|date('M j, Y') }}<br>
                      <span class="text-muted">({{ ((agreement.endDate|date('U') - agreement.startDate|date('U')) / 86400)|round + 1 }} days)</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Financial Terms -->
          {% if agreement.dailyRate or agreement.totalAmount %}
          <div class="mb-4">
            <h5>Financial Terms</h5>
            <div class="bg-light p-3 rounded">
              <div class="row">
                {% if agreement.dailyRate %}
                <div class="col-md-6">
                  <strong>Daily Rate:</strong> ${{ agreement.dailyRate }}
                </div>
                {% endif %}
                {% if agreement.totalAmount %}
                <div class="col-md-6">
                  <strong>Total Amount:</strong> ${{ agreement.totalAmount }}
                </div>
                {% endif %}
              </div>
            </div>
          </div>
          {% endif %}

          <!-- Agreement Terms -->
          <div class="mb-4">
            <h5>Agreement Terms</h5>
            <div class="agreement-terms" style="font-size: 0.95em; line-height: 1.8; padding: 20px; background-color: #f8f9fa; border-radius: 8px;">
              <div class="mb-4">
                <p><strong>Owner agrees</strong> that the item(s) are provided "as is" to Borrower.</p>
              </div>
              
              <div class="mb-4">
                <p><strong>Borrower agrees</strong> that the item(s) provided will be used carefully, and returned by the end date with only normal wear and tear.</p>
              </div>
              
              <div class="mb-4">
                <p><strong>Both Owner and Borrower agree</strong> that, in the case of a problem, they will work out an equitable arrangement, which others would agree was equitable.</p>
              </div>
              
              <div class="mb-3">
                <p><strong>Both Owner and Borrower agree</strong> that neither the Commons nor its Manager(s) has any responsibility for, or involvement in, this arrangement.</p>
              </div>
              
              {% if agreement.agreementTerms and agreement.agreementTerms != "Standard lending terms apply. Item must be returned in original condition." %}
              <div class="mt-4 pt-3 border-top">
                <h6>Additional Notes:</h6>
                {{ agreement.agreementTerms|nl2br }}
              </div>
              {% endif %}
            </div>
          </div>

          <!-- Return Instructions -->
          {% if agreement.returnInstructions %}
          <div class="mb-4">
            <h5>Return Instructions</h5>
            <div class="bg-light p-3 rounded">
              {{ agreement.returnInstructions|nl2br }}
            </div>
          </div>
          {% endif %}

          <!-- Digital Signature Information and Signatures -->
          {% if agreement.status != 'signed' %}
          <div class="alert alert-info mt-4">
            <i class="fas fa-info-circle me-2"></i>
            <strong>Digital Signature System:</strong> This agreement uses typed digital signatures with timestamp and IP address logging for security. Your typed signature has the same legal validity as a handwritten signature. Click the signature areas below to sign.
          </div>

          <!-- Signatures -->
          <div class="row mt-4">
            <div class="col-md-6">
              <div class="mb-3">
                <label class="form-label"><strong>Owner:</strong></label>
                <div class="text-muted mb-2"><small>{{ owner.firstName ~ ' ' ~ owner.lastName }}</small></div>
                <div class="signature-box border-bottom border-2 border-dark p-3 mb-2" style="height: 80px; background-color: white; {% if not agreement.ownerSignedAt %}cursor: pointer;{% endif %}" {% if not agreement.ownerSignedAt %}onclick="showSignatureModal('owner')"{% endif %}>
                  {% if agreement.ownerSignedAt %}
                    <div class="signature-content">
                      <div class="signature-line">{{ owner.firstName ~ ' ' ~ owner.lastName }}</div>
                    </div>
                  {% else %}
                    <div class="text-center text-muted pt-3">
                      <i class="fas fa-signature me-2"></i>Click to Sign Agreement
                    </div>
                  {% endif %}
                </div>
                <div class="text-center mt-2">
                  <small class="text-muted">{{ "now"|date("F j, Y") }}</small>
                </div>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label class="form-label"><strong>Borrower:</strong></label>
                <div class="text-muted mb-2"><small>{{ borrower.firstName ~ ' ' ~ borrower.lastName }}</small></div>
                <div class="signature-box border-bottom border-2 border-dark p-3 mb-2" style="height: 80px; background-color: white; {% if not agreement.borrowerSignedAt %}cursor: pointer;{% endif %}" {% if not agreement.borrowerSignedAt %}onclick="showSignatureModal('borrower')"{% endif %}>
                  {% if agreement.borrowerSignedAt %}
                    <div class="signature-content">
                      <div class="signature-line">{{ borrower.firstName ~ ' ' ~ borrower.lastName }}</div>
                    </div>
                  {% else %}
                    <div class="text-center text-muted pt-3">
                      <i class="fas fa-signature me-2"></i>Click to Sign Agreement
                    </div>
                  {% endif %}
                </div>
                <div class="text-center mt-2">
                  <small class="text-muted">{{ "now"|date("F j, Y") }}</small>
                </div>
              </div>
            </div>
          </div>
          {% else %}
          <!-- Pre-signed Agreement Notice -->
          <div class="alert alert-success mt-4">
            <i class="fas fa-check-circle me-2"></i>
            <strong>Agreement Fully Executed:</strong> This agreement has been approved and is ready for immediate use. No additional signatures are required.
          </div>
          {% endif %}

          <!-- Agreement Footer -->
          <div class="text-center mt-5 pt-4 border-top">
            <small class="text-muted">
              Agreement ID: {{ agreement.id }} | Created: {{ agreement.createdAt|date('M j, Y g:i A') }}<br>
              Generated through LocalLendables Community Platform
            </small>
          </div>

        </div>
      </div>

    </div>
  </div>
</div>

<!-- Signature Modal -->
<div class="modal fade" id="signatureModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Digital Signature</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p>By signing this agreement, you confirm that you have read, understood, and agree to all terms and conditions.</p>
        
        <div class="mb-3">
          <label class="form-label">Full Name (as it appears in your profile)</label>
          <input type="text" class="form-control" id="signerName" readonly>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Digital Signature Confirmation</label>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" id="confirmSignature">
            <label class="form-check-label" for="confirmSignature">
              I hereby electronically sign this agreement with the same legal effect as a handwritten signature.
            </label>
          </div>
        </div>
        
        <div class="alert alert-info">
          <i class="fas fa-info-circle me-2"></i>
          <strong>How Digital Signatures Work:</strong> Your typed name serves as your digital signature and will be recorded with a timestamp, IP address, and cannot be undone. This system provides the same legal validity as handwritten signatures while maintaining a digital audit trail.
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-success" id="confirmSignBtn">
          <i class="fas fa-signature me-2"></i>Sign Agreement
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Validation Alert Modal -->
<div class="modal fade" id="validationModal" tabindex="-1" aria-labelledby="validationModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-warning text-dark">
        <h5 class="modal-title" id="validationModalLabel">
          <i class="fas fa-exclamation-triangle me-2"></i>Validation Required
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p class="mb-0">Please click the Digital Signature Confirmation checkbox.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>

<!-- Success Modal -->
<div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title" id="successModalLabel">
          <i class="fas fa-check-circle me-2"></i>Success
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p class="mb-0">Agreement signed successfully!</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-success" onclick="location.reload()">Continue</button>
      </div>
    </div>
  </div>
</div>

<style>
.signature-box {
  background: #fafafa;
}

.signature-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.signature-line {
  padding-bottom: 10px;
  font-size: 1.1em;
  font-weight: bold;
  text-align: center;
  font-family: cursive, serif;
}

@media print {
  .btn, .alert { display: none !important; }
  .card { border: none !important; box-shadow: none !important; }
}
</style>

<script>
let currentSignerType = null;

function showSignatureModal(signerType) {
  currentSignerType = signerType;
  const modal = new bootstrap.Modal(document.getElementById('signatureModal'));
  
  // Set signer name
  const signerName = signerType === 'owner' ? 
    '{{ owner.firstName ~ " " ~ owner.lastName }}' : 
    '{{ borrower.firstName ~ " " ~ borrower.lastName }}';
  
  document.getElementById('signerName').value = signerName;
  modal.show();
}

// Optional: Visual feedback when checkbox is checked (but button stays enabled)
document.getElementById('confirmSignature').addEventListener('change', function() {
  const btn = document.getElementById('confirmSignBtn');
  if (this.checked) {
    btn.classList.remove('btn-success');
    btn.classList.add('btn-primary');
  } else {
    btn.classList.remove('btn-primary');
    btn.classList.add('btn-success');
  }
});

// Handle signature confirmation
document.getElementById('confirmSignBtn').addEventListener('click', async function() {
  // Check if checkbox is checked
  const checkbox = document.getElementById('confirmSignature');
  if (!checkbox.checked) {
    const validationModal = new bootstrap.Modal(document.getElementById('validationModal'));
    validationModal.show();
    return;
  }
  
  try {
    console.log('Starting signature process for signerType:', currentSignerType);
    this.disabled = true;
    this.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Signing...';
    
    const requestBody = {
      signerType: currentSignerType,
      signature: document.getElementById('signerName').value,
      timestamp: new Date().toISOString()
    };
    console.log('Request body:', requestBody);
    
    const response = await fetch('/api/agreements/{{ agreement.id }}/sign', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestBody)
    });
    
    console.log('Response status:', response.status);
    const result = await response.json();
    console.log('Response result:', result);
    
    if (result.success) {
      const successModal = new bootstrap.Modal(document.getElementById('successModal'));
      successModal.show();
    } else {
      alert('Error signing agreement: ' + result.error);
      this.disabled = false;
      this.innerHTML = '<i class="fas fa-signature me-2"></i>Sign Agreement';
    }
  } catch (error) {
    console.error('Error signing agreement:', error);
    alert('Failed to sign agreement: ' + error.message);
    this.disabled = false;
    this.innerHTML = '<i class="fas fa-signature me-2"></i>Sign Agreement';
  }
});
</script>
{% endblock %}