@extends('layouts.master')

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

@section('page-css')
<link rel="stylesheet" type="text/css" href="{{ url('public/assets/css/permit_show.css') }}">
<style>
    /* TIMELINE & STEPPER CSS */
    /* Vertical Stepper Line */
    .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; }
    .stepper-item.pending .step-title, .stepper-item.pending .step-desc { opacity: 0.6; }

    /* 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; }
    .timeline-item { position: relative; margin-bottom: 1.5rem; }
    .timeline-icon { position: absolute; top: 0; left: -2rem; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1rem; z-index: 1; }
    .timeline-content { margin-left: 0.5rem; background-color: #fff; transition: all 0.2s ease; }
    .timeline-content:hover { box-shadow: 0 .5rem 1rem rgba(0,0,0,.08)!important; }
</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">
    
    <div class="col-lg-7 col-md-12">
      
      <div class="d-flex align-items-center mb-4 mt-2 gap-3">
        <h1 class="display-6 fw-bold text-dark mb-0">{{ $permit_arr['application_code'] }}</h1>
        <span class="badge bg-warning text-dark fs-5 shadow-sm align-middle">{{ $permit_arr['status'] }}</span>
      </div>
      <div class="map-container mb-4 border border-light-subtle shadow-sm rounded overflow-hidden" style="height: 450px; background-color: #f8f9fc;">
          <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:500px;border:0;border-radius:8px;"
                  allow="geolocation; clipboard-write"
                  referrerpolicy="strict-origin-when-cross-origin"
                  loading="lazy"
                  title="Permit location map">
          </iframe>
            <!-- <div class="map-container mb-4 border border-light-subtle shadow-sm rounded p-5 text-center" style="background-color: #f8f9fc;">
                <i class="bi bi-map text-secondary" style="font-size: 3rem;"></i>
                <h5 class="mt-3 text-dark">Map View Available</h5>
                <p class="text-muted">For security reasons, the interactive map must be opened in a secure window.</p>
                <a href="https://pwa.lupmis4luspa.org/embed.php?mode=permit&application_code={{ urlencode($permit_arr['application_code']) }}..." target="_blank" class="btn btn-primary mt-2">
                    <i class="bi bi-box-arrow-up-right me-1"></i> Open Spatial Map
                </a>
            </div> -->
          </div>

      <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-person text-primary fs-5 me-2"></i> 
                <h6 class="fw-bold mb-0 text-dark" style="font-size: 1.1rem;">Applicant & Property Details</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'] }}</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'] }}</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:jmadjanor6@gmail.com" class="text-decoration-none text-primary">{{ $permit_arr['email'] }}</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'] }}</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'] }}</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'] }}</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'] }}</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'] }}</div>
                </div>
                <div class="col-12 mt-2">
                    <div class="border border-dark-subtle rounded p-3">
                        <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'] }}</div>
                    </div>
                </div>
            </div>
        </div>
      </div>

      <div class="card border border-light-subtle shadow-sm mb-4" style="background-color: #f8f9fc;">
          <div class="card-body p-4">
              <h6 class="fw-bold text-uppercase text-secondary mb-4" style="letter-spacing: 0.5px; font-size: 0.85rem;">
                  Actual Project Location & Cadastral Registration
              </h6>
              <div class="row g-3 mb-4">
                  <div class="col-md-4">
                      <label class="form-label fw-bold text-secondary small mb-1">
                          Coordinates <br class="d-none d-md-block"> (Latitude, Longitude) <span class="text-danger">*</span>
                      </label>
                      <div class="input-group shadow-sm">
                          <span class="input-group-text bg-white border-end-0 text-muted font-monospace small pe-1">GPS:</span>
                          <input type="text" class="form-control border-start-0 ps-1 font-monospace" placeholder="e.g., 5.66240, -0.18055" value="">
                      </div>
                  </div>
                  <div class="col-md-4">
                      <label class="form-label fw-bold text-secondary small mb-1">
                          <br class="d-none d-md-block">UPN (Unique Parcel Number)
                      </label>
                      <input type="text" class="form-control shadow-sm" value="">
                  </div>
                  <div class="col-md-4">
                      <label class="form-label fw-bold text-secondary small mb-1">
                          Permit  <br class="d-none d-md-block">Fee (GH₵) <span class="text-danger">*</span>
                      </label>
                      <input type="number" class="form-control shadow-sm fw-bold" value="">
                  </div>
              </div>
              <div class="d-flex flex-wrap gap-2">
                  <button type="button" class="btn fw-bold px-4 text-dark shadow-sm" style="background-color: #ffb400; border-color: #ffb400;">
                      Check Zone Compliance
                  </button>
                  <button type="button" class="btn btn-primary fw-bold px-4 shadow-sm">
                      <i class="bi bi-map me-1"></i> Save Physical Location
                  </button>
              </div>
          </div>
      </div>

      <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-file-earmark-text 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 border-light-subtle rounded p-3 d-flex align-items-center justify-content-between bg-light shadow-sm transition-all">
                      <div class="d-flex align-items-center text-truncate pe-3">
                          <i class="bi bi-file-earmark text-primary fs-4 me-3"></i>
                          <div class="text-truncate">
                              <div class="text-dark fw-medium" style="font-size: 0.95rem;">Site Plan Drawing</div>
                              <div class="text-secondary font-monospace text-uppercase" style="font-size: 0.75rem; letter-spacing: 0.5px;">site_plan.pdf</div>
                          </div>
                      </div>
                      <a href="#" class="text-decoration-none fw-semibold text-nowrap" style="font-size: 0.85rem;">
                          Open File <i class="bi bi-arrow-up-right ms-1"></i>
                      </a>
                  </div>
                  <!-- <div class="border border-light-subtle rounded p-3 d-flex align-items-center justify-content-between bg-light shadow-sm transition-all">
                      <div class="d-flex align-items-center text-truncate pe-3">
                          <i class="bi bi-file-earmark text-primary fs-4 me-3"></i>
                          <div class="text-truncate">
                              <div class="text-dark fw-medium" style="font-size: 0.95rem;">Block Plan Drawing</div>
                              <div class="text-secondary font-monospace text-uppercase" style="font-size: 0.75rem; letter-spacing: 0.5px;">LUSPA_TAIFA_BLOCK2_A.jpg</div>
                          </div>
                      </div>
                      <a href="#" class="text-decoration-none fw-semibold text-nowrap" style="font-size: 0.85rem;">
                          Open File <i class="bi bi-arrow-up-right ms-1"></i>
                      </a>
                  </div> -->
                  <div class="border border-light-subtle rounded p-3 d-flex align-items-center justify-content-between bg-light shadow-sm transition-all">
                      <div class="d-flex align-items-center text-truncate pe-3">
                          <i class="bi bi-file-earmark text-primary fs-4 me-3"></i>
                          <div class="text-truncate">
                              <div class="text-dark fw-medium" style="font-size: 0.95rem;">Architectural Drawings</div>
                              <div class="text-secondary font-monospace text-uppercase" style="font-size: 0.75rem; letter-spacing: 0.5px;">architectural.pdf</div>
                          </div>
                      </div>
                      <a href="#" class="text-decoration-none fw-semibold text-nowrap" style="font-size: 0.85rem;">
                          Open File <i class="bi bi-arrow-up-right ms-1"></i>
                      </a>
                  </div>
              </div>
          </div>
      </div>

    </div>

    <div class="col-lg-5 col-md-12">
      <div class="sticky-top" style="top: 1.5rem; ">
        
        <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" style="font-size: 1.1rem;">Processing & Duration</h6>
                    </div>
                    <div class="text-end">
                        <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.7rem; letter-spacing: 0.5px;">Remaining Days</div>
                        <span class="badge text-dark fs-6 px-3 py-1" style="background-color: #fce4b4;">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"></div>
                            <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.7rem; letter-spacing: 0.5px;">28th Feb 2026, 11:59 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 on 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"></div>
                            <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.7rem; 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 documenets.</p>
                            <span class="badge bg-light text-secondary border fw-medium px-2 py-1">Updated by: Luke Eshun</span>
                        </div>
                        <!-- <div class="stepper-item pending">
                            <div class="stepper-dot pending"></div>
                            <div class="text-uppercase text-secondary fw-semibold mb-1" style="font-size: 0.7rem; letter-spacing: 0.5px;">PENDING PROCESS SCHEDULE • LUPMIS ENGINE</div>
                            <h6 class="fw-bold mb-1 step-title text-secondary">Spatial GIS Alignment</h6>
                            <p class="mb-2 small text-secondary step-desc">Verification of parcel boundaries against Taifa master plan & greenbelt buffers.</p>
                        </div> -->
                    </div>
                </div>
            </div>
        </div>

        <div class="remarks-section 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="fa-solid fa-comments text-primary fs-5 me-2"></i>
              <h6 class="fw-bold mb-0 text-dark" style="font-size: 1.1rem;">Status & Comments</h6>
            </div>
            <div class="mb-4">
              <button class="btn btn-outline-secondary w-100 fw-bold" type="button" data-bs-toggle="offcanvas" data-bs-target="#historyOffcanvas" aria-controls="historyOffcanvas">
                <i class="bi bi-clock-history me-1"></i> View Full History & Comments
              </button>
            </div>
            <div class="mb-4">
              <label for="permitCurrentStatus" class="form-label fw-bold text-secondary small mb-2" style="letter-spacing: 0.5px;">
                <i class="fa-solid fa-temperature-three-quarters text-primary me-1"></i> Status Update
              </label>
              <select class="form-select shadow-sm" 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>
              </select>
            </div>
            <div class="mb-4">       
              <textarea class="form-control shadow-sm commentBody" rows="4" name="comment_body" placeholder="Enter new comment here"></textarea>
              <input type="hidden" class="applicationCode" name="application_code" value="{{ $permit_arr['application_code'] }}">
            </div>
            <button class="btn btn-primary w-100 fw-bold shadow-sm submitPermitCommentBtn" type="button">
              <i class="fa-solid fa-paper-plane me-1"></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="historyTimeline">
      <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-scripts')
<script>
  $(document).ready(function(){ 

  const MAP_ORIGIN = 'https://pwa.lupmis4luspa.org';
  const iframe   = document.getElementById('permit-map');
  const upnInput = document.getElementById('permitUPN');
  const locInput = document.getElementById('permitLocation');
  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']))
                iframe.contentWindow.postMessage(
                  { type: 'set:selected', upn: @json($permit_arr['upn']) },
                  MAP_ORIGIN);
              @endif
              break;
     
            case 'parcel:select':
              upnInput.value = msg.upn || '';
              locInput.value = (msg.lon != null && msg.lat != null)
                ? msg.lat.toFixed(6) + ', ' + msg.lon.toFixed(6)
                : '';
              upnInput.dataset.parcelId = msg.parcel_id || '';
              upnInput.dataset.zoneCode = msg.zone_code || '';
              break;
     
            case 'parcel:cleared':
              upnInput.value = '';
              locInput.value = '';
              delete upnInput.dataset.parcelId;
              delete upnInput.dataset.zoneCode;
              break;
     
            case 'error':
              console.warn('[permit-map]', msg.code, msg.message);
              break;
        }
           
        $('#checkComplianceBtn').on('click', function (e) {
          e.preventDefault();
          const payload = {
            application_code: @json($permit_arr['application_code']),
            upn:        upnInput.value,
            parcel_id:  upnInput.dataset.parcelId || null,
            coordinates: locInput.value,
            zone_code:  upnInput.dataset.zoneCode || null,
          };
          $.ajax({ url: '{{ route("permits.checkCompliance") }}',
                   method: 'POST', data: payload })
            .done(function (res) { /* render compliance result */ });
        });
       
    });
document.addEventListener('DOMContentLoaded', function() {
    // === PDF GENERATION LOGIC ===
    window.generateReportPDF = function() {
      console.log("1. 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 {
          // Lock in the form values AND remove problem images
          const inputs = element.querySelectorAll('input, textarea, select');
          inputs.forEach(input => {
              if (input.tagName === 'TEXTAREA') {
                  input.innerHTML = input.value;
              } else if (input.tagName === 'SELECT') {
                  // Lock the selected value
                  const selectedOption = input.options[input.selectedIndex];
                  if (selectedOption) selectedOption.setAttribute('selected', 'selected');
                  
                  // THE FIX: Remove the SVG background arrow that crashes html2canvas
                  input.style.backgroundImage = 'none';
                  input.style.appearance = 'none'; // Removes native browser arrows
              } else {
                  input.setAttribute('value', input.value);
              }
          });

          console.log("3. Form data locked and SVGs removed. Generating file...");
          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'] 
              }
          };

          // Generate PDF
          html2pdf().set(opt).from(element).save().then(() => {
              console.log("Success: PDF downloaded.");
              
              // THE RESTORE: Put the arrows back on the screen after download finishes
              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);
      }
    }
});

});
</script>
@endsection



