@extends('layouts.master')

@section('page-title') 
    Permits | {{ $page_title ?? 'Details' }}
@endsection

@section('page-css')
<link rel="stylesheet" type="text/css" href="{{ url('public/assets/css/permit_show.css') }}">
<style>
    /* TIMELINE & STEPPER CSS */
    .planning-stepper { position: relative; padding-left: 1.25rem; }
    .planning-stepper::before { content: ''; position: absolute; top: 6px; bottom: 0; left: 4px; width: 2px; background-color: #e9ecef; z-index: 0; }
    .stepper-item { position: relative; padding-bottom: 1.75rem; }
    .stepper-item:last-child { padding-bottom: 0; }
    .stepper-dot { position: absolute; left: -1.25rem; top: 0.25rem; width: 10px; height: 10px; border-radius: 50%; z-index: 1; background-color: #dee2e6; }
    .stepper-dot.completed { background-color: #20c997; }
    .stepper-dot.active { background-color: #fd7e14; box-shadow: 0 0 0 5px rgba(253, 126, 20, 0.15); }
    .stepper-dot.pending { background-color: #e2e8f0; }
    
    /* Offcanvas Timeline CSS */
    .timeline { position: relative; padding-left: 2rem; margin-top: 1rem; }
    .timeline::before { content: ''; position: absolute; top: 0; bottom: 0; left: 0.85rem; width: 2px; background-color: #dee2e6; z-index: 0; }
    
    /* Custom Tab Styling to match mockup */
    .nav-tabs .nav-link { color: #6c757d; font-weight: 500; border: none; padding: 1rem 1.5rem; margin-bottom: -1px; }
    .nav-tabs .nav-link:hover { color: #0d6efd; border-color: transparent; }
    .nav-tabs .nav-link.active { color: #0d6efd; background-color: transparent; border-bottom: 2px solid #0d6efd; font-weight: 600; }
    
    body { background-color: #f4f5f7; } /* Slightly darker background to make white cards pop like the image */
</style>
@endsection

@section('page-content')

@include('permits.partials.pdf-modal')
@include('layouts.partials.permits-navbar')
@include('permits.partials.site-inspection')

<div class="container py-4">
  <div class="row g-4">
    
    <!-- LEFT COLUMN (Main Content) -->
    <div class="col-lg-8 col-md-12">
      
      <!-- Title & Badge -->
      <div class="d-flex align-items-center mb-3 mt-1 gap-3">
        <h1 class="display-6 fw-bold text-dark mb-0 fs-2">{{ $permit_arr['application_code'] ?? 'REQ-20260312-22AL' }}</h1>
        <span class="badge rounded-pill shadow-sm align-middle fs-6 px-3 py-2" style="background-color: #f39c12; color: #fff;">{{ $permit_arr['status'] ?? 'SUBMITTED' }}</span>
      </div>

      <!-- Map Container -->
      <div class="map-container mb-4 border border-light-subtle shadow-sm rounded overflow-hidden" style="height: 400px; background-color: #e9ecef; position: relative;">
          <!-- Map Iframe -->
          <iframe id="permit-map"
                  src="https://pwa.lupmis4luspa.org/embed.php?mode=permit&application_code={{ urlencode($permit_arr['application_code'] ?? '') }}{{ !empty($permit_arr['lon']) ? '&lon='.urlencode($permit_arr['lon']).'&lat='.urlencode($permit_arr['lat']) : '' }}{{ !empty($permit_arr['upn']) ? '&upn='.urlencode($permit_arr['upn']) : '' }}"
                  style="width:100%;height:100%;border:0;"
                  allow="geolocation; clipboard-write"
                  referrerpolicy="strict-origin-when-cross-origin"
                  loading="lazy"
                  title="Permit location map">
          </iframe>
      </div>

      <!-- Tabs Section (Matches Image Layout) -->
      <div class="card border border-light-subtle shadow-sm mb-4 bg-white">
          <div class="card-header bg-white border-bottom-0 p-0 pt-2 px-3">
              <ul class="nav nav-tabs border-bottom" id="permitDetailTabs" role="tablist">
                  <li class="nav-item" role="presentation">
                      <button class="nav-link active" id="applicant-tab" data-bs-toggle="tab" data-bs-target="#applicant-tab-pane" type="button" role="tab" aria-controls="applicant-tab-pane" aria-selected="true">Applicant Details</button>
                  </li>
                  <li class="nav-item" role="presentation">
                      <button class="nav-link" id="location-tab" data-bs-toggle="tab" data-bs-target="#location-tab-pane" type="button" role="tab" aria-controls="location-tab-pane" aria-selected="false">Project Location</button>
                  </li>
                  <li class="nav-item" role="presentation">
                      <button class="nav-link" id="documents-tab" data-bs-toggle="tab" data-bs-target="#documents-tab-pane" type="button" role="tab" aria-controls="documents-tab-pane" aria-selected="false">Documents</button>
                  </li>
                  <li class="nav-item" role="presentation">
                      <button class="nav-link" id="inspection-tab" data-bs-toggle="tab" data-bs-target="#inspection-tab-pane" type="button" role="tab" aria-controls="inspection-tab-pane" aria-selected="false">Site Inspection</button>
                  </li>
                  <li class="nav-item" role="presentation">
                      <button class="nav-link" id="fees-tab" data-bs-toggle="tab" data-bs-target="#fees-tab-pane" type="button" role="tab" aria-controls="fees-tab-pane" aria-selected="false">Payments</button>
                  </li>
                  
              </ul>
          </div>
          <div class="card-body p-4">
              <div class="tab-content" id="permitDetailTabsContent">
                  
                  <!-- TAB 1: Applicant Details -->
                  <div class="tab-pane fade show active" id="applicant-tab-pane" role="tabpanel" aria-labelledby="applicant-tab" tabindex="0">
                      <div class="d-flex align-items-center mb-4">
                          <i class="bi bi-person text-primary fs-5 me-2"></i> 
                          <h6 class="fw-bold mb-0 text-dark" style="font-size: 1.1rem;">Applicant & Property Profile</h6>
                      </div>
                      <div class="row gy-4">
                          <div class="col-12">
                              <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.75rem; letter-spacing: 0.5px;">Applicant Name:</div>
                              <div class="fw-bold text-dark fs-5">{{ $permit_arr['applicant_name'] ?? 'N/A' }}</div>
                          </div>
                          <div class="col-md-6">
                              <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.75rem; letter-spacing: 0.5px;">Nationality:</div>
                              <div class="text-dark fw-medium">{{ $permit_arr['nationality'] ?? 'N/A' }}</div>
                          </div>
                          <div class="col-md-6">
                              <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.75rem; letter-spacing: 0.5px;">Email Address:</div>
                              <div><a href="mailto:{{ $permit_arr['email'] ?? '' }}" class="text-decoration-none text-primary">{{ $permit_arr['email'] ?? 'N/A' }}</a></div>
                          </div>
                          <div class="col-md-6">
                              <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.75rem; letter-spacing: 0.5px;">Telephone Number:</div>
                              <div class="text-dark">{{ $permit_arr['phone'] ?? 'N/A' }}</div>
                          </div>
                          <div class="col-md-6">
                              <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.75rem; letter-spacing: 0.5px;">Project Location:</div>
                              <div class="text-dark fw-bold">{{ $permit_arr['project_location'] ?? 'N/A' }}</div>
                          </div>
                          <div class="col-12">
                              <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.75rem; letter-spacing: 0.5px;">Mailing Address:</div>
                              <div class="text-dark">{{ $permit_arr['address'] ?? 'N/A' }}</div>
                          </div>
                          <div class="col-md-6">
                              <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.75rem; letter-spacing: 0.5px;">Permit Type Requested</div>
                              <div class="text-dark fw-bold">{{ $permit_arr['permit_type'] ?? 'N/A' }}</div>
                          </div>
                          <div class="col-md-6">
                              <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.75rem; letter-spacing: 0.5px;">Purpose</div>
                              <div class="fw-bold" style="color: #e67e22;">{{ $permit_arr['land_request_use'] ?? 'N/A' }}</div>
                          </div>
                          <div class="col-12 mt-2">
                              <div class="border border-dark-subtle rounded p-3 bg-light">
                                  <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.75rem; letter-spacing: 0.5px;">Project Scope:</div>
                                  <div class="text-dark fst-italic" style="font-size: 0.95rem;">{{ $permit_arr['project_description'] ?? 'No scope provided.' }}</div>
                              </div>
                          </div>
                      </div>
                  </div>

                  <!-- TAB 2: Project Location  -->
                  <div class="tab-pane fade" id="location-tab-pane" role="tabpanel" aria-labelledby="location-tab" tabindex="0">
                      <div class="d-flex align-items-center mb-4">
                          <i class="bi bi-geo-alt-fill text-primary fs-5 me-2"></i> 
                          <h6 class="fw-bold mb-0 text-primary" style="font-size: 1.1rem;">Actual Project Location</h6>
                      </div>
                      
                      <div class="row g-3 mb-4">
                          <div class="col-md-6">
                              <label class="form-label fw-bold text-secondary mb-1" style="font-size: 0.75rem;">
                                  COORDINATES (LATITUDE, LONGITUDE) <span class="text-danger">*</span>
                              </label>
                              <div class="input-group">
                                  <span class="input-group-text bg-white text-muted">GPS:</span>
                                  <input type="text" class="form-control ps-1" id="permitLocation" placeholder="e.g., 5.66240, -0.18055" value="">
                              </div>
                          </div>
                          <div class="col-md-6">
                              <label class="form-label fw-bold text-secondary mb-1" style="font-size: 0.75rem;">
                                  UPN (UNIQUE PARCEL NUMBER)
                              </label>
                              <input type="text" class="form-control" id="permitUPN" value="">
                          </div>
                      </div>
                      
                      <div class="d-flex gap-3">
                          <button type="button" id="checkComplianceBtn" class="btn fw-bold px-4 text-white shadow-sm" style="background-color: #f39c12; border: none;">
                              Check Zone Compliance
                          </button>
                          <button type="button" class="btn btn-primary fw-bold px-4 shadow-sm" style="background-color: #3b82f6; border: none;">
                              <i class="bi bi-download me-1"></i> Save Physical Location
                          </button>
                      </div>
                  </div>
                  <!-- TAB 5: Documents -->
                  <div class="tab-pane fade" id="documents-tab-pane" role="tabpanel" aria-labelledby="documents-tab" tabindex="0">
                      <div class="d-flex align-items-center mb-4">
                          <i class="bi bi-file-earmark-pdf text-primary fs-5 me-2"></i> 
                          <h6 class="fw-bold mb-0 text-dark" style="font-size: 1.1rem;">Uploaded Documents</h6>
                      </div>
                      <div class="d-flex flex-column gap-3">
                          <div class="border rounded p-3 d-flex align-items-center justify-content-between bg-light">
                              <div class="d-flex align-items-center">
                                  <i class="bi bi-file-earmark-text text-primary fs-3 me-3"></i>
                                  <div>
                                      <div class="text-dark fw-medium">Site Plan Drawing</div>
                                      <div class="text-secondary font-monospace" style="font-size: 0.75rem;">site_plan.pdf</div>
                                  </div>
                              </div>
                              <a href="#" class="btn btn-sm btn-outline-secondary fw-semibold">Open File <i class="bi bi-box-arrow-up-right ms-1"></i></a>
                          </div>
                          <div class="border rounded p-3 d-flex align-items-center justify-content-between bg-light">
                              <div class="d-flex align-items-center">
                                  <i class="bi bi-file-earmark-text text-primary fs-3 me-3"></i>
                                  <div>
                                      <div class="text-dark fw-medium">Architectural Drawings</div>
                                      <div class="text-secondary font-monospace" style="font-size: 0.75rem;">architectural.pdf</div>
                                  </div>
                              </div>
                              <a href="#" class="btn btn-sm btn-outline-secondary fw-semibold">Open File <i class="bi bi-box-arrow-up-right ms-1"></i></a>
                          </div>
                      </div>
                      <hr class="my-4 text-secondary">
                    <div class="d-flex align-items-center mb-3">
                        <i class="bi bi-plus-square-dotted text-warning fs-5 me-2"></i> 
                        <h6 class="fw-bold mb-0 text-dark" style="font-size: 1.1rem;">Request Required Documents</h6>
                    </div>
                    <div class="card border border-light-subtle shadow-sm bg-white">
                        <div class="card-body p-4">
                            <p class="text-muted small mb-3">Select the missing documents the applicant must upload before processing can continue.</p>
                            
                            <form id="requestDocumentsForm">
                                <div class="row g-3 mb-4">
                                    <div class="col-md-6">
                                        <div class="form-check mb-2">
                                            <input class="form-check-input req-doc-checkbox" type="checkbox" name="requested_docs[]" value="structural_drawings" id="doc1">
                                            <label class="form-check-label fw-medium" for="doc1">Structural Drawings</label>
                                        </div>
                                        <div class="form-check mb-2">
                                            <input class="form-check-input req-doc-checkbox" type="checkbox" name="requested_docs[]" value="fire_report" id="doc2">
                                            <label class="form-check-label fw-medium" for="doc2">Fire Service Report</label>
                                        </div>
                                        <div class="form-check mb-2">
                                            <input class="form-check-input req-doc-checkbox" type="checkbox" name="requested_docs[]" value="epa_certificate" id="doc3">
                                            <label class="form-check-label fw-medium" for="doc3">EPA Certificate</label>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-check mb-2">
                                            <input class="form-check-input req-doc-checkbox" type="checkbox" name="requested_docs[]" value="title_certificate" id="doc4">
                                            <label class="form-check-label fw-medium" for="doc4">Land Title Certificate</label>
                                        </div>
                                        <div class="form-check mb-2">
                                            <input class="form-check-input req-doc-checkbox" type="checkbox" name="requested_docs[]" value="soil_test" id="doc5">
                                            <label class="form-check-label fw-medium" for="doc5">Soil Test Report</label>
                                        </div>
                                        <div class="form-check mb-2">
                                            <input class="form-check-input req-doc-checkbox" type="checkbox" name="requested_docs[]" value="block_plan" id="doc6">
                                            <label class="form-check-label fw-medium" for="doc6">Block Plan</label>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label fw-bold text-secondary small" style="font-size: 0.75rem;">ADDITIONAL NOTES (OPTIONAL)</label>
                                    <textarea class="form-control" id="docRequestNotes" rows="2" placeholder="e.g., Please ensure the EPA certificate is dated this year..."></textarea>
                                </div>

                                <div class="d-flex align-items-center gap-3">
                                    <button type="button" class="btn fw-bold px-4 text-dark shadow-sm" id="sendDocRequestBtn" style="background-color: #f39c12; border: none;">
                                        <i class="bi bi-send me-1"></i> Request from Applicant
                                    </button>
                                    <span class="text-success small fw-bold d-none" id="docRequestSuccessMsg">
                                        <i class="bi bi-check-circle-fill me-1"></i> Request Sent!
                                    </span>
                                </div>
                            </form>
                        </div>
                    </div>
                  </div>

                  <!-- TAB 3: Site Inspection -->
                  <div class="tab-pane fade" id="inspection-tab-pane" role="tabpanel" aria-labelledby="inspection-tab" tabindex="0">
                      <div class="d-flex align-items-center mb-4">
                          <i class="bi bi-clipboard-check text-primary fs-5 me-2"></i> 
                          <h6 class="fw-bold mb-0 text-dark" style="font-size: 1.1rem;">Site Inspection</h6>
                      </div>
                      <p class="text-muted mb-4">Generate and manage the official site inspection report for this application.</p>
                      <button type="button" class="btn btn-outline-primary px-4 py-2" data-bs-toggle="modal" data-bs-target="#inspectionReportModal">
                          <i class="bi bi-file-earmark-text me-2"></i> Open Site Inspection Report
                      </button>
                  </div>

                  <!-- TAB 4: Permit Fees -->
                  <div class="tab-pane fade" id="fees-tab-pane" role="tabpanel" aria-labelledby="fees-tab" tabindex="0">
                      <div class="d-flex align-items-center mb-4">
                          <i class="bi bi-cash-stack text-success fs-5 me-2"></i> 
                          <h6 class="fw-bold mb-0 text-dark" style="font-size: 1.1rem;">Payments</h6>
                      </div>
                      <div class="row g-3 mb-4">
                          <div class="col-md-6">
                              <label class="form-label fw-bold text-secondary mb-1" style="font-size: 0.75rem;">
                                   PERMIT FEE (GH₵) <span class="text-danger">*</span>
                              </label>
                              <input type="number" class="form-control fw-bold" placeholder="0.00">
                          </div>
                      </div>
                      <button type="button" class="btn btn-success fw-bold px-4 shadow-sm">
                          Apply Fee
                      </button>
                  </div>

                  

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

    </div>

    <!-- RIGHT COLUMN (Sidebar Layout exactly like image) -->
    <div class="col-lg-4 col-md-12">
      <div class="sticky-top" style="top: 1.5rem;">
        
        <!-- Processing & Duration Card -->
        <div class="card border border-light-subtle shadow-sm mb-4">
            <div class="card-body p-4">
                <div class="d-flex justify-content-between align-items-start border-bottom pb-3 mb-4">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-clock text-primary fs-5 me-2"></i>
                        <h6 class="fw-bold mb-0 text-dark">Processing & Duration</h6>
                    </div>
                    <div class="text-end">
                        <div class="text-uppercase text-secondary fw-bold mb-1" style="font-size: 0.65rem; letter-spacing: 0.5px;">REMAINING DAYS</div>
                        <span class="badge text-dark fs-6 px-3 py-1 bg-light border">N/A</span>
                    </div>
                </div>
                
                <div class="overflow-auto pe-2" style="max-height: 450px;">
                    <div class="planning-stepper">
                        <div class="stepper-item">
                            <div class="stepper-dot completed" style="background-color: #2ecc71;"></div>
                            <div class="text-uppercase text-secondary fw-bold mb-1" style="font-size: 0.65rem; letter-spacing: 0.5px;">28TH FEB 2026, 11:58 PM - LUPMIS ENGINE</div>
                            <h6 class="fw-bold mb-1 text-dark">Submission Received</h6>
                            <p class="mb-2 small text-secondary">Application successfully uploaded to the Portal by applicant.</p>
                            <span class="badge bg-light text-secondary border fw-medium px-2 py-1">Verified by: Applicant Portal</span>
                        </div>
                        <div class="stepper-item">
                            <div class="stepper-dot active" style="background-color: #e67e22; box-shadow: none;"></div>
                            <div class="text-uppercase text-secondary fw-bold mb-1" style="font-size: 0.65rem; letter-spacing: 0.5px;">PENDING PROCESS SCHEDULE - LUPMIS ENGINE</div>
                            <h6 class="fw-bold mb-1" style="color: #e67e22;">Applicant to Review</h6>
                            <p class="mb-2 small text-secondary">Applicant asked to review attached documents.</p>
                            <span class="badge bg-light text-secondary border fw-medium px-2 py-1">Updated by: Luke Eshun</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Status & Comments Card -->
        <div class="card border border-light-subtle shadow-sm mb-4">
          <div class="card-body p-4">
            <div class="d-flex align-items-center border-bottom pb-3 mb-4">
              <i class="bi bi-chat-dots-fill text-primary fs-5 me-2"></i>
              <h6 class="fw-bold mb-0 text-dark">Status & Comments</h6>
            </div>
            
            <div class="mb-4">
              <button class="btn btn-outline-secondary w-100 fw-bold py-2" type="button" data-bs-toggle="offcanvas" data-bs-target="#historyOffcanvas" aria-controls="historyOffcanvas">
                <i class="bi bi-clock-history me-2"></i> View Full History & Comments
              </button>
            </div>
            
            <div class="mb-3">
              <label for="permitCurrentStatus" class="form-label fw-bold text-secondary mb-2" style="font-size: 0.75rem; letter-spacing: 0.5px;">
                <i class="bi bi-info-circle text-primary me-1"></i> STATUS UPDATE
              </label>
              <select class="form-select py-2" id="permitCurrentStatus">
                  <option value="" selected disabled>Select status ...</option>
                  <option value="status_zero">Applicant to Review</option>
                  <option value="status_one">Application Received</option>   
                  <option value="status_two" disabled>Application Accepted</option>                
                  <option value="status_three" disabled>Permit Pending TSC Review</option>
                  <option value="status_four" disabled>Permit Pending SPC Decision</option>
                  <option value="status_five" disabled>Permit Approved (In Principle)</option>
                  <option value="status_six" disabled>Permit Approved</option>
                  <option value="status_seven" disabled>Permit Refused</option>
                  <option value="status_eight" disabled>Permit Deferred</option>
              </select>
            </div>
            
            <div class="mb-4">       
              <textarea class="form-control commentBody py-2" rows="4" name="comment_body" placeholder="Enter new comment here" style="resize: none; font-style: italic;"></textarea>
              <input type="hidden" class="applicationCode" name="application_code" value="{{ $permit_arr['application_code'] ?? '' }}">

            </div>
            
            <button class="btn w-100 fw-bold shadow-sm submitPermitCommentBtn py-2 text-white" type="button" style="background-color: #3b82f6;">
              <i class="bi bi-send-fill me-2"></i> Submit
            </button>
          </div>
        </div>

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

<div class="offcanvas offcanvas-end shadow-lg" tabindex="-1" id="historyOffcanvas" aria-labelledby="historyOffcanvasLabel" style="width: 450px;">
  <div class="offcanvas-header border-bottom bg-light sticky-top z-3">
    <h5 class="offcanvas-title fw-bold" id="historyOffcanvasLabel">Application History</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
    <div class="timeline" id="commentsTimeline">
      <div class="text-center text-muted mt-5">
          <i class="bi bi-arrow-clockwise fs-1"></i>
          <p class="mt-2">Loading application history...</p>
      </div>
    </div>
  </div>
</div>

@endsection

@section('page-js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script src="{{ url('public/assets/js/permit_comments.js') }}" type="text/javascript"></script>

<script type="text/javascript">

// 1. Global Functions (Keep OUTSIDE document.ready so buttons can trigger them)
window.generateReportPDF = function() {
    console.log("Button clicked. Starting PDF process...");

    if (typeof html2pdf === 'undefined') {
        $.alert("ERROR: The html2pdf library is not loaded.");
        return;
    }

    const element = document.getElementById('report-pdf-content');
    if (!element) {
        $.alert("ERROR: Could not find the div with id='report-pdf-content'.");
        return;
    }

    try {
        const inputs = element.querySelectorAll('input, textarea, select');
        inputs.forEach(input => {
            if (input.tagName === 'TEXTAREA') {
                input.innerHTML = input.value;
            } else if (input.tagName === 'SELECT') {
                const selectedOption = input.options[input.selectedIndex];
                if (selectedOption) selectedOption.setAttribute('selected', 'selected');
                input.style.backgroundImage = 'none';
                input.style.appearance = 'none'; 
            } else {
                input.setAttribute('value', input.value);
            }
        });


        const opt = {
            margin:       0.5,
            filename:     'Site_Inspection_Report.pdf',
            image:        { type: 'jpeg', quality: 0.98 },
            html2canvas:  { 
                scale: 2, 
                useCORS: true, 
                logging: false,
                scrollY: 0, 
                windowY: 0  
            },               
            jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' },
            pagebreak: { 
                mode: 'css', 
                avoid: ['.row', 'h6'] 
            }
        };

        html2pdf().set(opt).from(element).save().then(() => {
            console.log("Success: PDF downloaded.");
            inputs.forEach(input => {
                if (input.tagName === 'SELECT') {
                    input.style.backgroundImage = '';
                    input.style.appearance = '';
                }
            });
        }).catch(err => {
            console.error("PDF Generation Error:", err);
            alert("Failed to build the PDF. Check the browser console.");
        });

    } catch (error) {
        console.error("Critical Execution Error:", error);
        alert("A javascript error occurred: " + error.message);
    }
};

// 2. DOM Dependencies and Listeners (Keep INSIDE document.ready)
$(document).ready(function(){ 

    // Define all DOM elements first
    const MAP_ORIGIN = 'https://pwa.lupmis4luspa.org';
    const iframe   = document.getElementById('permit-map');
    const upnInput = document.getElementById('permitUPN');
    const locInput = document.getElementById('permitLocation');
    var pdfModal   = document.getElementById('pdfModal');

    // PDF Modal Logic
    if(pdfModal) {
        pdfModal.addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var pdfUrl = button.getAttribute('data-pdf-url');
            var pdfIframe = document.getElementById('pdfIframe');
            if(pdfIframe) pdfIframe.src = pdfUrl;
        });

        pdfModal.addEventListener('hidden.bs.modal', function () {
            var pdfIframe = document.getElementById('pdfIframe');
            if(pdfIframe) pdfIframe.src = '';
        });
    }

    // Map Iframe Logic
    window.addEventListener('message', function (event) {
      if (event.origin !== MAP_ORIGIN) return;
      const msg = event.data;
      if (!msg || typeof msg !== 'object') return;
 
      switch (msg.type) {
        case 'ready':
          @if(!empty($permit_arr['upn']))
            if(iframe) {
                iframe.contentWindow.postMessage(
                  { type: 'set:selected', upn: @json($permit_arr['upn']) },
                  MAP_ORIGIN);
            }
          @endif
          break;
 
        case 'parcel:select':
          if(upnInput) upnInput.value = msg.upn || '';
          if(locInput) {
              locInput.value = (msg.lon != null && msg.lat != null)
                ? msg.lat.toFixed(6) + ', ' + msg.lon.toFixed(6)
                : '';
          }
          if(upnInput) {
              upnInput.dataset.parcelId = msg.parcel_id || '';
              upnInput.dataset.zoneCode = msg.zone_code || '';
          }
          break;
 
        case 'parcel:cleared':
          if(upnInput) {
              upnInput.value = '';
              delete upnInput.dataset.parcelId;
              delete upnInput.dataset.zoneCode;
          }
          if(locInput) locInput.value = '';
          break;
 
        case 'error':
          console.warn('[permit-map]', msg.code, msg.message);
          break;
      }
    });

    // Check Compliance Logic
    $('#checkComplianceBtn').on('click', function (e) {
      e.preventDefault();
      const payload = {
        application_code: @json($permit_arr['application_code'] ?? ''),
        upn:        upnInput ? upnInput.value : '',
        parcel_id:  upnInput ? (upnInput.dataset.parcelId || null) : null,
        coordinates: locInput ? locInput.value : '',
        zone_code:  upnInput ? (upnInput.dataset.zoneCode || null) : null,
      };
      $.ajax({ 
          url: '{{ route("permits.checkCompliance") }}',
          method: 'POST', 
          data: payload 
      }).done(function (res) { 
          /* render compliance result */ 
      });
    });
   
    // Download PDF Button Logic
    const downloadBtn = document.getElementById('downloadPdfBtn');
    if(downloadBtn) {
        downloadBtn.addEventListener('click', function() {
            const element = document.getElementById('report-pdf-content');
            if(!element) return;

            const inputs = element.querySelectorAll('input, textarea, select');
            inputs.forEach(input => {
                if (input.tagName === 'TEXTAREA') {
                    input.innerHTML = input.value;
                } else if (input.tagName === 'SELECT') {
                    const selectedOption = input.options[input.selectedIndex];
                    if (selectedOption) selectedOption.setAttribute('selected', 'selected');
                } else {
                    input.setAttribute('value', input.value);
                }
            });
            const originalText = downloadBtn.innerHTML;
            downloadBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> Generating...';
            downloadBtn.disabled = true;

            const opt = {
                margin:       0.5,
                filename:     'Site_Inspection_Report.pdf',
                image:        { type: 'jpeg', quality: 0.98 },
                html2canvas:  { scale: 2, useCORS: true, logging: false },
                jsPDF:        { unit: 'in', format: 'a4', orientation: 'portrait' }
            };

            html2pdf().set(opt).from(element).save().then(() => {
                downloadBtn.innerHTML = originalText;
                downloadBtn.disabled = false;
            });
        });
    }

});
</script>
@endsection



