{% extends "ui/templates/base/layout.html" %}
{% block content %}
<div class="space-y-6">
  <div class="flex flex-wrap items-center justify-between gap-3">
    <div>
      <h2 class="text-xl font-semibold text-slate-900">Engagement Documents</h2>
      <p class="text-sm text-slate-500">{{ engagement.client.client_name if engagement.client else '-' }} · {{ engagement.catalogue.service_name if engagement.catalogue else '-' }} · FY {{ engagement.financial_year }}</p>
    </div>
    <div class="flex flex-wrap gap-2">
      <a href="/services/engagements/{{ engagement.id }}" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">Engagement</a>
      <a href="/documents/udin-register?financial_year={{ engagement.financial_year }}" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">UDIN Register</a>
      <a href="/documents" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">Back</a>
    </div>
  </div>

  {% if request.query_params.get('uploaded') %}<div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800">Document uploaded successfully.</div>{% endif %}
  {% if request.query_params.get('deleted') %}<div class="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">Document archived successfully.</div>{% endif %}
  {% if request.query_params.get('download_queued') %}<div class="rounded-2xl border border-sky-200 bg-sky-50 p-4 text-sm text-sky-800">The file is stored in branch local storage. A secure retrieval request #{{ request.query_params.get('download_queued') }} has been queued. Please refresh after the local storage app fulfils it.</div>{% endif %}
  {% if request.query_params.get('udin_saved') %}<div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800">UDIN details saved successfully.</div>{% endif %}
  {% if request.query_params.get('released') %}<div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800">Document released as final.</div>{% endif %}
  {% if request.query_params.get('reopened') %}<div class="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">Final release reopened to draft.</div>{% endif %}
  {% if request.query_params.get('error') %}<div class="rounded-2xl border border-red-200 bg-red-50 p-4 text-sm text-red-800">Action failed. Please check file size, permission, UDIN, release status and storage path.</div>{% endif %}

  {% if can_upload %}
  <section class="rounded-2xl bg-white p-5 shadow-soft">
    <h3 class="text-sm font-semibold text-slate-900">Upload Document / New Revision</h3>
    <form method="post" action="/documents/engagements/{{ engagement.id }}/upload" enctype="multipart/form-data" class="mt-4 grid gap-4 md:grid-cols-2">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <div>
        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Title</label>
        <input type="text" name="title" placeholder="Document title" class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm">
      </div>
      <div>
        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Document Type</label>
        <select name="document_type" class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm">
          {% for item in document_types %}<option value="{{ item }}">{{ item.replace('_',' ').title() }}</option>{% endfor %}
        </select>
      </div>
      <div>
        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Existing Document</label>
        <select name="existing_document_id" class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm">
          <option value="">Create new document</option>
          {% for doc in documents %}<option value="{{ doc.id }}">Add revision to {{ doc.title }} (v{{ doc.current_version_no }})</option>{% endfor %}
        </select>
      </div>
      <div>
        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">File</label>
        <input type="file" name="file" required class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm">
      </div>
      <div class="md:col-span-2 rounded-xl border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
        <label class="inline-flex items-center gap-2 font-semibold">
          <input type="checkbox" name="udin_required" value="1" class="rounded border-amber-300">
          UDIN required before final release
        </label>
        <p class="mt-1 text-xs text-amber-800">Use this for certificate, audit report, signed output or other deliverable where partner UDIN is applicable.</p>
      </div>
      <div class="md:col-span-2">
        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Description</label>
        <textarea name="description" rows="2" class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"></textarea>
      </div>
      <div class="md:col-span-2">
        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Revision Remarks</label>
        <textarea name="remarks" rows="2" class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"></textarea>
      </div>
      <div class="md:col-span-2">
        <button class="rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700">Upload</button>
      </div>
    </form>
  </section>
  {% endif %}

  <div class="overflow-hidden rounded-2xl bg-white shadow-soft">
    <table class="min-w-full divide-y divide-slate-200">
      <thead class="bg-slate-50">
        <tr>
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Document</th>
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Type</th>
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Latest Version</th>
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Storage</th>
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">UDIN / Release</th>
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Revision History</th>
          <th class="px-4 py-3 text-right text-xs font-semibold uppercase tracking-wide text-slate-500">Action</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-100">
        {% for doc in documents %}
        {% set latest = doc.versions[0] if doc.versions else None %}
        <tr>
          <td class="px-4 py-3 text-sm"><div class="font-medium text-slate-900">{{ doc.title }}</div><div class="text-xs text-slate-500">{{ doc.document_code }}{% if doc.description %} · {{ doc.description }}{% endif %}</div></td>
          <td class="px-4 py-3 text-sm text-slate-700">{{ doc.document_type.replace('_',' ').title() }}</td>
          <td class="px-4 py-3 text-xs text-slate-600">{% if latest %}<div>v{{ latest.version_no }} · {{ latest.original_filename }}</div><div>{{ (latest.file_size_bytes / 1024)|round(1) }} KB · {{ latest.uploaded_at_utc }}</div>{% else %}-{% endif %}</td>
          <td class="px-4 py-3 text-xs text-slate-600">
            {% if latest %}
              <div><span class="rounded-full bg-slate-100 px-2 py-1 text-slate-700">{{ latest.storage_status.replace('_',' ').title() }}</span></div>
              <div class="mt-1 font-mono text-[11px] break-all">{{ latest.local_relative_path }}</div>
            {% else %}-{% endif %}
          </td>
          <td class="px-4 py-3 text-xs text-slate-600">
            <div><span class="rounded-full px-2 py-1 {{ 'bg-emerald-100 text-emerald-800' if doc.final_release_status == 'released' else 'bg-slate-100 text-slate-700' }}">{{ (doc.final_release_status or 'draft').replace('_',' ').title() }}</span></div>
            <div class="mt-2">UDIN: <span class="font-semibold">{{ (doc.udin_status or 'not_required').replace('_',' ').title() }}</span></div>
            {% if doc.udin_number %}<div class="font-mono text-[11px]">{{ doc.udin_number }}</div>{% endif %}
            {% if doc.udin_date %}<div>Date: {{ doc.udin_date }}</div>{% endif %}
            {% if doc.udin_required and not doc.udin_number %}<div class="mt-1 text-red-600">UDIN pending before final release.</div>{% endif %}
          </td>
          <td class="px-4 py-3 text-xs text-slate-600">
            {% for v in doc.versions %}
              <div><a href="/documents/versions/{{ v.id }}/download" class="text-brand-700 hover:underline">v{{ v.version_no }}</a> · {{ v.original_filename }}{% if v.remarks %} · {{ v.remarks }}{% endif %}</div>
            {% endfor %}
          </td>
          <td class="px-4 py-3 text-right text-sm align-top">
            {% if latest %}<a href="/documents/{{ doc.id }}/download" class="font-medium text-brand-700 hover:underline">Download Latest</a>{% endif %}
            {% if 'udin.manage' in current_user_permissions %}
            <details class="mt-3 text-left">
              <summary class="cursor-pointer text-sm font-semibold text-brand-700">UDIN / Release</summary>
              <div class="mt-3 space-y-3 rounded-xl border border-slate-200 bg-slate-50 p-3">
                <form method="post" action="/documents/{{ doc.id }}/udin" class="grid gap-2">
                  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                  <input type="hidden" name="redirect_to" value="/documents/engagements/{{ engagement.id }}">
                  <label class="inline-flex items-center gap-2 text-xs font-semibold text-slate-700"><input type="checkbox" name="udin_required" value="1" {% if doc.udin_required %}checked{% endif %}> UDIN required</label>
                  <input type="text" name="udin_number" value="{{ doc.udin_number or '' }}" placeholder="UDIN number" class="rounded-lg border border-slate-300 px-2 py-1 text-xs">
                  <div class="grid grid-cols-2 gap-2">
                    <input type="date" name="udin_date" value="{{ doc.udin_date or '' }}" class="rounded-lg border border-slate-300 px-2 py-1 text-xs">
                    <input type="date" name="udin_document_date" value="{{ doc.udin_document_date or '' }}" class="rounded-lg border border-slate-300 px-2 py-1 text-xs">
                  </div>
                  <input type="text" name="udin_document_type" value="{{ doc.udin_document_type or doc.document_type.replace('_',' ').title() }}" placeholder="Document type" class="rounded-lg border border-slate-300 px-2 py-1 text-xs">
                  <div class="grid grid-cols-2 gap-2">
                    <input type="text" name="udin_financial_year" value="{{ doc.udin_financial_year or doc.financial_year }}" placeholder="FY" class="rounded-lg border border-slate-300 px-2 py-1 text-xs">
                    <input type="text" name="udin_amount" value="{{ doc.udin_amount or '' }}" placeholder="Amount, if any" class="rounded-lg border border-slate-300 px-2 py-1 text-xs">
                  </div>
                  <input type="text" name="udin_notes" value="{{ doc.udin_notes or '' }}" placeholder="UDIN notes" class="rounded-lg border border-slate-300 px-2 py-1 text-xs">
                  <button class="rounded-lg bg-slate-800 px-3 py-1.5 text-xs font-semibold text-white">Save UDIN</button>
                </form>
                {% if doc.final_release_status != 'released' %}
                <form method="post" action="/documents/{{ doc.id }}/final-release" onsubmit="return confirm('Release this document as final?');" class="grid gap-2">
                  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                  <input type="hidden" name="redirect_to" value="/documents/engagements/{{ engagement.id }}">
                  <input type="text" name="release_notes" placeholder="Release notes" class="rounded-lg border border-slate-300 px-2 py-1 text-xs">
                  <button class="rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-semibold text-white">Release Final</button>
                </form>
                {% else %}
                <form method="post" action="/documents/{{ doc.id }}/reopen-final" onsubmit="return confirm('Reopen this final document to draft?');">
                  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                  <input type="hidden" name="redirect_to" value="/documents/engagements/{{ engagement.id }}">
                  <button class="rounded-lg border border-amber-300 px-3 py-1.5 text-xs font-semibold text-amber-700">Reopen Draft</button>
                </form>
                {% endif %}
              </div>
            </details>
            {% endif %}
            {% if can_upload %}
            <form method="post" action="/documents/{{ doc.id }}/delete" class="ml-3 inline" onsubmit="return confirm('Archive this document?');">
              <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
              <button class="font-medium text-red-600 hover:underline">Archive</button>
            </form>
            {% endif %}
          </td>
        </tr>
        {% else %}
        <tr><td colspan="7" class="px-4 py-8 text-center text-sm text-slate-500">No documents uploaded for this engagement.</td></tr>
        {% endfor %}
      </tbody>
    </table>
  </div>

  {% if download_requests %}
  <section class="rounded-2xl bg-white p-5 shadow-soft">
    <div class="flex items-center justify-between">
      <div>
        <h3 class="text-sm font-semibold text-slate-900">Recent Local Storage Retrieval Requests</h3>
        <p class="text-xs text-slate-500">Used when the ERP staged file is unavailable and the file must be pulled back from branch local storage.</p>
      </div>
      <a href="/documents/download-requests" class="text-sm font-medium text-brand-700 hover:underline">View All</a>
    </div>
    <div class="mt-4 overflow-hidden rounded-xl border border-slate-200">
      <table class="min-w-full divide-y divide-slate-200 text-sm">
        <thead class="bg-slate-50 text-xs uppercase tracking-wide text-slate-500"><tr><th class="px-3 py-2 text-left">Request</th><th class="px-3 py-2 text-left">Version</th><th class="px-3 py-2 text-left">Status</th><th class="px-3 py-2 text-left">Created</th><th class="px-3 py-2 text-right">Action</th></tr></thead>
        <tbody class="divide-y divide-slate-100">
          {% for req in download_requests %}
          <tr>
            <td class="px-3 py-2 font-medium">#{{ req.id }}</td>
            <td class="px-3 py-2">v{{ req.version.version_no if req.version else req.version_id }}</td>
            <td class="px-3 py-2"><span class="rounded-full bg-slate-100 px-2 py-1 text-xs text-slate-700">{{ req.request_status.replace('_',' ').title() }}</span></td>
            <td class="px-3 py-2 text-xs text-slate-500">{{ req.created_at_utc }}</td>
            <td class="px-3 py-2 text-right">{% if req.request_status == 'ready' %}<a href="/documents/download-requests/{{ req.id }}/download" class="font-medium text-brand-700 hover:underline">Download</a>{% else %}<span class="text-xs text-slate-400">Waiting for local app</span>{% endif %}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </section>
  {% endif %}

</div>
{% endblock %}
