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

$user   = requireAuth(['owner']);
Document::refreshStatuses();
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $act = $_POST['action'] ?? '';

    if ($act === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id) { Document::delete($id, $user['id']); flash('dash', t('delete')); }
        redirect(BASE_URL.'/owner/personal.php');
    }

    // upload / update
    $type   = $_POST['doc_type'] ?? '';
    $expiry = $_POST['expiry_date'] ?? '';
    $allowed = array_column(DocumentTemplate::active('driver'), 'code');
    if (!in_array($type, $allowed, true) || !$expiry) {
        $errors[] = t('fill_all_fields');
    } else {
        $fp = 'uploads/placeholder.pdf';
        if (!empty($_FILES['doc_file']['name'])) {
            $f = $_FILES['doc_file'];
            if ($f['size'] > MAX_UPLOAD)                         $errors[] = t('file_too_large');
            elseif (!in_array($f['type'], ALLOWED_MIME, true))   $errors[] = t('file_invalid');
            else {
                @mkdir(UPLOAD_DIR, 0755, true);
                $fname = uniqid('per_', true).'.'.pathinfo($f['name'], PATHINFO_EXTENSION);
                move_uploaded_file($f['tmp_name'], UPLOAD_DIR.$fname);
                $fp = 'uploads/'.$fname;
            }
        }
        if (empty($errors)) {
            Document::upsert(['user_id'=>$user['id'],'vehicle_id'=>null,'type'=>$type,'file_path'=>$fp,'expiry_date'=>$expiry]);
            flash('dash', t('doc_uploaded'));
            redirect(BASE_URL.'/owner/personal.php');
        }
    }
}

$templates = DocumentTemplate::active('driver');
$mine = [];
foreach (Document::personalByUser($user['id']) as $d) $mine[$d['type']] = $d;

$pageTitle  = t('my_documents');
$activePage = BASE_URL.'/owner/personal.php';
require __DIR__.'/../../app/Views/shared/layout.php';
?>
<div class="page-header"><h2>🪪 <?= t('personal_documents') ?></h2>
  <p style="color:var(--text-muted);font-size:13px"><?= t('personal_docs_hint') ?></p>
</div>

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

<?php if (empty($templates)): ?>
<div class="card"><div class="empty-state"><div class="empty-state-icon">🪪</div><p><?= t('no_data') ?></p></div></div>
<?php else: ?>
<div class="doc-grid">
  <?php foreach($templates as $tpl):
    $code = $tpl['code'];
    $label= $tpl['name_'.lang()] ?? $tpl['name_en'];
    $doc  = $mine[$code] ?? null;
    $st   = $doc ? docStatus($doc['expiry_date']) : null;
    $hasFile = $doc && !empty($doc['file_path']) && $doc['file_path'] !== 'uploads/placeholder.pdf';
  ?>
  <div class="doc-card" style="<?= $st==='expired'?'border-color:var(--danger)':'' ?>">
    <div class="doc-icon"><?= e($tpl['icon']) ?></div>
    <div style="flex:1;min-width:0">
      <div class="doc-name"><?= e($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 if($hasFile): ?>
        <a href="<?= BASE_URL.'/'.e($doc['file_path']) ?>" target="_blank" class="btn btn-sm btn-secondary" style="margin-top:8px">🔗 <?= 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="openForm('<?= e($code) ?>')"><?= $doc?'🔄':'⬆️' ?></button>
  </div>
  <?php endforeach; ?>
</div>

<div id="uploadForm" class="card" style="display:none;margin-top:20px">
  <div class="card-header"><span class="card-title">📤 <?= t('upload_doc') ?></span></div>
  <div class="card-body">
    <form method="POST" enctype="multipart/form-data">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="upload">
      <div class="form-row">
        <div class="form-group">
          <label class="form-label"><?= t('doc_type') ?></label>
          <select name="doc_type" id="fType" class="form-control">
            <?php foreach($templates as $tpl): ?>
            <option value="<?= e($tpl['code']) ?>"><?= e($tpl['name_'.lang()] ?? $tpl['name_en']) ?></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">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>

<script>
function openForm(code){
  document.getElementById('uploadForm').style.display='block';
  document.getElementById('fType').value=code;
  document.getElementById('uploadForm').scrollIntoView({behavior:'smooth'});
}
</script>
<?php endif; ?>
<?php require __DIR__.'/../../app/Views/shared/layout_end.php'; ?>
