<?php
require_once __DIR__.'/../../config/app.php';
require_once __DIR__.'/../../app/Models/Vehicle.php';
require_once __DIR__.'/../../app/Models/Document.php';
require_once __DIR__.'/../../app/Models/DocumentTemplate.php';

$user     = requireAuth(['owner']);
Document::refreshStatuses();
$vehicles = Vehicle::byOwner($user['id']);
$errors   = [];

if($_SERVER['REQUEST_METHOD']==='POST') {
    verifyCsrf();
    $vid    = (int)($_POST['vehicle_id'] ?? 0);
    $type   = $_POST['doc_type'] ?? '';
    $expiry = $_POST['expiry_date'] ?? '';
    $v      = Vehicle::find($vid);

    if(!$v || $v['owner_id'] !== $user['id']) redirect(BASE_URL.'/owner/documents.php');

    $allowed = array_column(DocumentTemplate::active('vehicle'), 'code');
    if(!in_array($type,$allowed,true) || !$expiry) {
        $errors[] = t('fill_all_fields');
    } else {
        $filePath = 'uploads/placeholder.pdf'; // MVP - store path only
        if(!empty($_FILES['doc_file']['name'])) {
            $file = $_FILES['doc_file'];
            if($file['size'] > MAX_UPLOAD) {
                $errors[] = t('file_too_large');
            } elseif(!in_array($file['type'], ALLOWED_MIME, true)) {
                $errors[] = t('file_invalid');
            } else {
                @mkdir(UPLOAD_DIR, 0755, true);
                $ext      = pathinfo($file['name'], PATHINFO_EXTENSION);
                $fname    = uniqid('doc_', true).'.'.$ext;
                move_uploaded_file($file['tmp_name'], UPLOAD_DIR.$fname);
                $filePath = 'uploads/'.$fname;
            }
        }
        if(empty($errors)) {
            Document::upsert(['user_id'=>$user['id'],'vehicle_id'=>$vid,'type'=>$type,'file_path'=>$filePath,'expiry_date'=>$expiry]);
            flash('dash', t('doc_uploaded'));
            redirect(BASE_URL.'/owner/documents.php?vehicle='.$vid);
        }
    }
}

$selectedVid = (int)($_GET['vehicle'] ?? ($vehicles[0]['id'] ?? 0));
$selectedV   = $selectedVid ? Vehicle::find($selectedVid) : null;
$docs        = $selectedVid ? Document::byVehicle($selectedVid) : [];
$docMap      = [];
foreach($docs as $d) $docMap[$d['type']] = $d;

$docTypes = [];
foreach(DocumentTemplate::active('vehicle') as $tpl) {
    $col = 'name_'.lang();
    $docTypes[$tpl['code']] = ['label'=>$tpl[$col] ?? $tpl['name_en'], 'icon'=>$tpl['icon']];
}

$pageTitle  = t('documents');
$activePage = BASE_URL.'/owner/documents.php';
require __DIR__.'/../../app/Views/shared/layout.php';
?>

<!-- Vehicle selector -->
<div class="card" style="margin-bottom:20px">
  <div class="card-body" style="padding:14px 18px">
    <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
      <span style="color:var(--text-muted);font-size:13px"><?= t('my_vehicles') ?>:</span>
      <?php foreach($vehicles as $v): ?>
      <a href="?vehicle=<?= $v['id'] ?>"
         class="btn btn-sm <?= $selectedVid===$v['id']?'btn-primary':'btn-secondary' ?>">
        🚗 <?= e($v['brand'].' '.$v['model']) ?> — <?= e($v['plate_number']) ?>
      </a>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<?php foreach($errors as $e): ?>
<div class="alert alert-danger"><?= e($e) ?></div>
<?php endforeach; ?>

<?php if(!$selectedV): ?>
<div class="card"><div class="empty-state">
  <div class="empty-state-icon">📄</div>
  <h3><?= t('documents') ?></h3>
  <p><?= t('no_vehicles_hint') ?></p>
</div></div>
<?php else: ?>

<div class="card">
  <div class="card-header">
    <div>
      <span class="card-title">📄 <?= e($selectedV['brand'].' '.$selectedV['model']) ?></span>
      <span class="vehicle-plate-badge" style="margin-inline-start:10px"><?= e($selectedV['plate_number']) ?></span>
    </div>
  </div>
  <div class="card-body">
    <div class="doc-grid">
      <?php foreach($docTypes as $type => $info):
        $doc = $docMap[$type] ?? null;
        $st  = $doc ? docStatus($doc['expiry_date']) : null;
      ?>
      <div class="doc-card" style="<?= $st==='expired'?'border-color:var(--danger)':'' ?>">
        <div class="doc-icon"><?= $info['icon'] ?></div>
        <div style="flex:1;min-width:0">
          <div class="doc-name"><?= $info['label'] ?></div>
          <?php if($doc): ?>
            <div class="doc-meta"><?= t('expiry_date') ?>: <?= e($doc['expiry_date']) ?></div>
            <div style="margin-top:5px"><?= statusBadge($st, lang()) ?></div>
            <?php $hasFile = !empty($doc['file_path']) && $doc['file_path'] !== 'uploads/placeholder.pdf'; ?>
            <?php if($hasFile): ?>
            <a href="<?= BASE_URL.'/'.e($doc['file_path']) ?>" target="_blank" class="btn btn-sm btn-secondary" style="margin-top:6px">🔗 <?= t('view_document') ?></a>
            <?php endif; ?>
          <?php else: ?>
            <div class="doc-meta" style="color:var(--text-muted)">— <?= t('not_set') ?></div>
          <?php endif; ?>
        </div>
        <button class="btn btn-sm btn-secondary" onclick="showUploadForm('<?= $type ?>','<?= $selectedV['id'] ?>')">
          <?= $doc ? '🔄' : '⬆️' ?>
        </button>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- Upload Form (hidden, toggled by JS) -->
    <div id="uploadForm" style="display:none;margin-top:20px;padding:20px;background:var(--bg-primary);border-radius:var(--radius-md)">
      <h4 style="margin-bottom:14px">📤 <?= t('upload_doc') ?></h4>
      <form method="POST" enctype="multipart/form-data">
        <?= csrfField() ?>
        <input type="hidden" name="vehicle_id" id="formVehicleId">
        <div class="form-row">
          <div class="form-group">
            <label class="form-label"><?= t('doc_type') ?></label>
            <select name="doc_type" id="formDocType" class="form-control">
              <?php foreach($docTypes as $k=>$v): ?>
              <option value="<?= $k ?>"><?= $v['label'] ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label"><?= t('expiry_date') ?> *</label>
            <input type="date" name="expiry_date" class="form-control" required>
          </div>
        </div>
        <div class="form-group">
          <label class="form-label"><?= t('upload_file') ?></label>
          <input type="file" name="doc_file" class="form-control" accept=".pdf,.jpg,.jpeg,.png">
          <div style="font-size:12px;color:var(--text-muted);margin-top:4px"><?= t('doc_insurance').' PDF, JPG, PNG — 5MB' ?></div>
        </div>
        <div style="display:flex;gap:10px">
          <button type="submit" class="btn btn-primary">💾 <?= t('save') ?></button>
          <button type="button" class="btn btn-secondary" onclick="document.getElementById('uploadForm').style.display='none'"><?= t('cancel') ?></button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endif; ?>

<script>
function showUploadForm(type, vehicleId) {
  document.getElementById('uploadForm').style.display = 'block';
  document.getElementById('formVehicleId').value = vehicleId;
  document.getElementById('formDocType').value = type;
  document.getElementById('uploadForm').scrollIntoView({behavior:'smooth'});
}
</script>

<?php require __DIR__.'/../../app/Views/shared/layout_end.php'; ?>
