<?php
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../core/helpers.php';
requireLogin();

$pageTitle  = 'Profil Pendamping';
$activePage = 'profil';

$profil   = Database::fetchOne("SELECT * FROM profil_pendamping LIMIT 1");
$riwayat  = $profil ? Database::fetchAll("SELECT * FROM riwayat_tugas WHERE profil_id=? ORDER BY tahun_mulai DESC", [$profil['id']]) : [];

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isAdmin()) {
    if (!csrf_verify()) { $errors[] = 'Token tidak valid.'; }

    $action = $_POST['action'] ?? 'profil';

    if ($action === 'profil') {
        $fields = [
            'nama_lengkap' => sanitize($_POST['nama_lengkap'] ?? ''),
            'nip'          => sanitize($_POST['nip'] ?? ''),
            'jabatan'      => sanitize($_POST['jabatan'] ?? ''),
            'unit_kerja'   => sanitize($_POST['unit_kerja'] ?? ''),
            'pangkat'      => sanitize($_POST['pangkat'] ?? ''),
            'golongan'     => sanitize($_POST['golongan'] ?? ''),
            'pendidikan'   => sanitize($_POST['pendidikan'] ?? ''),
            'telepon'      => sanitize($_POST['telepon'] ?? ''),
            'email'        => sanitize($_POST['email'] ?? ''),
            'alamat'       => sanitize($_POST['alamat'] ?? ''),
            'tentang'      => sanitize($_POST['tentang'] ?? ''),
        ];

        if (empty($fields['nama_lengkap'])) $errors[] = 'Nama wajib diisi.';

        // Upload foto profil
        if (!empty($_FILES['foto']['name'])) {
            $up = uploadFile($_FILES['foto'], 'foto_profil', ALLOWED_IMAGE, MAX_IMAGE_SIZE);
            if (!$up['success']) { $errors[] = $up['error']; }
            else {
                if ($profil && !empty($profil['foto'])) deleteFile('foto_profil', $profil['foto']);
                $fields['foto'] = $up['filename'];
            }
        }

        if (empty($errors)) {
            if ($profil) {
                $set  = implode(',', array_map(fn($k) => "{$k}=?", array_keys($fields)));
                $vals = array_values($fields); $vals[] = $profil['id'];
                Database::execute("UPDATE profil_pendamping SET {$set} WHERE id=?", $vals);
            } else {
                $cols = implode(',', array_keys($fields));
                $pls  = implode(',', array_fill(0, count($fields), '?'));
                Database::execute("INSERT INTO profil_pendamping ({$cols}) VALUES ({$pls})", array_values($fields));
            }
            auditLog('UPDATE','profil_pendamping',1,'Update profil');
            setFlash('success','Profil berhasil diperbarui.');
            redirect(BASE_URL.'/modules/profil/index.php');
        }
    } elseif ($action === 'riwayat') {
        $rf = [
            'profil_id'      => $profil['id'],
            'jabatan'        => sanitize($_POST['rw_jabatan'] ?? ''),
            'unit_kerja'     => sanitize($_POST['rw_unit_kerja'] ?? ''),
            'tahun_mulai'    => (int)($_POST['rw_tahun_mulai'] ?? 0),
            'tahun_selesai'  => (int)($_POST['rw_tahun_selesai'] ?? 0) ?: null,
            'keterangan'     => sanitize($_POST['rw_keterangan'] ?? ''),
        ];
        if (!empty($rf['jabatan'])) {
            Database::execute("INSERT INTO riwayat_tugas (profil_id,jabatan,unit_kerja,tahun_mulai,tahun_selesai,keterangan) VALUES (?,?,?,?,?,?)",
                [$rf['profil_id'],$rf['jabatan'],$rf['unit_kerja'],$rf['tahun_mulai'],$rf['tahun_selesai'],$rf['keterangan']]);
            setFlash('success','Riwayat tugas ditambahkan.');
        }
        redirect(BASE_URL.'/modules/profil/index.php');
    }
}

// Hapus riwayat
if (isset($_GET['del_riwayat']) && isAdmin()) {
    $rId = (int)$_GET['del_riwayat'];
    Database::execute("DELETE FROM riwayat_tugas WHERE id=? AND profil_id=?", [$rId, $profil['id'] ?? 0]);
    setFlash('success','Riwayat dihapus.');
    redirect(BASE_URL.'/modules/profil/index.php');
}

// Refresh setelah POST
$profil  = Database::fetchOne("SELECT * FROM profil_pendamping LIMIT 1");
$riwayat = $profil ? Database::fetchAll("SELECT * FROM riwayat_tugas WHERE profil_id=? ORDER BY tahun_mulai DESC", [$profil['id']]) : [];

require_once ROOT_PATH . '/views/layouts/header.php';
?>

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-person-badge me-2 text-primary"></i>Profil Pendamping</h1>
    <nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/dashboard/index.php">Dashboard</a></li><li class="breadcrumb-item active">Profil</li></ol></nav>
  </div>
</div>

<?php if($errors): ?>
<div class="alert alert-danger border-0 mb-3"><ul class="mb-0 ps-3"><?php foreach($errors as $e): ?><li><?= e($e) ?></li><?php endforeach; ?></ul></div>
<?php endif; ?>

<div class="row g-3">
  <!-- Profil Card -->
  <div class="col-lg-4">
    <div class="card text-center mb-3">
      <div class="card-body py-4">
        <?php if($profil && $profil['foto']): ?>
        <img src="<?= BASE_URL ?>/uploads/foto_profil/<?= e($profil['foto']) ?>" alt="Foto Profil"
             class="rounded-circle mb-3" style="width:100px;height:100px;object-fit:cover;border:3px solid var(--border)">
        <?php else: ?>
        <div class="rounded-circle bg-primary d-flex align-items-center justify-content-center mx-auto mb-3"
             style="width:100px;height:100px;font-size:2.5rem;color:rgba(255,255,255,.9)">
          <i class="bi bi-person-fill"></i>
        </div>
        <?php endif; ?>
        <h5 class="fw-700 mb-1"><?= e($profil['nama_lengkap'] ?? 'Nama Pendamping') ?></h5>
        <p class="text-muted mb-1" style="font-size:.85rem"><?= e($profil['jabatan'] ?? '') ?></p>
        <p class="text-muted mb-1" style="font-size:.8rem"><?= e($profil['unit_kerja'] ?? '') ?></p>
        <?php if($profil['pangkat'] ?? ''): ?>
        <span class="badge bg-primary-subtle text-primary"><?= e($profil['pangkat']) ?> / <?= e($profil['golongan']) ?></span>
        <?php endif; ?>
      </div>
      <?php if($profil && $profil['tentang']): ?>
      <div class="card-footer text-muted" style="font-size:.82rem;line-height:1.6"><?= nl2br(e($profil['tentang'])) ?></div>
      <?php endif; ?>
    </div>

    <!-- Kontak -->
    <?php if($profil): ?>
    <div class="card mb-3">
      <div class="card-header"><span class="card-header-title"><i class="bi bi-person-lines-fill me-2"></i>Kontak</span></div>
      <div class="card-body" style="font-size:.84rem">
        <?php if($profil['nip']): ?><div class="mb-2"><span class="text-muted">NIP:</span> <?= e($profil['nip']) ?></div><?php endif; ?>
        <?php if($profil['telepon']): ?><div class="mb-2"><i class="bi bi-telephone text-muted me-2"></i><?= e($profil['telepon']) ?></div><?php endif; ?>
        <?php if($profil['email']): ?><div class="mb-2"><i class="bi bi-envelope text-muted me-2"></i><?= e($profil['email']) ?></div><?php endif; ?>
        <?php if($profil['pendidikan']): ?><div class="mb-2"><i class="bi bi-mortarboard text-muted me-2"></i><?= e($profil['pendidikan']) ?></div><?php endif; ?>
        <?php if($profil['alamat']): ?><div><i class="bi bi-house text-muted me-2"></i><?= e($profil['alamat']) ?></div><?php endif; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>

  <div class="col-lg-8">
    <?php if(isAdmin()): ?>
    <!-- Form Edit Profil -->
    <div class="card mb-3">
      <div class="card-header"><span class="card-header-title"><i class="bi bi-pencil-square me-2"></i>Edit Profil</span></div>
      <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="profil">
          <div class="row g-3">
            <div class="col-md-8"><label class="form-label">Nama Lengkap</label><input type="text" name="nama_lengkap" class="form-control" value="<?= e($profil['nama_lengkap'] ?? '') ?>" required></div>
            <div class="col-md-4"><label class="form-label">NIP</label><input type="text" name="nip" class="form-control" value="<?= e($profil['nip'] ?? '') ?>"></div>
            <div class="col-md-8"><label class="form-label">Jabatan</label><input type="text" name="jabatan" class="form-control" value="<?= e($profil['jabatan'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">Golongan</label><input type="text" name="golongan" class="form-control" value="<?= e($profil['golongan'] ?? '') ?>" placeholder="IV/a"></div>
            <div class="col-md-8"><label class="form-label">Unit Kerja</label><input type="text" name="unit_kerja" class="form-control" value="<?= e($profil['unit_kerja'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">Pangkat</label><input type="text" name="pangkat" class="form-control" value="<?= e($profil['pangkat'] ?? '') ?>"></div>
            <div class="col-md-6"><label class="form-label">Telepon</label><input type="text" name="telepon" class="form-control" value="<?= e($profil['telepon'] ?? '') ?>"></div>
            <div class="col-md-6"><label class="form-label">Email</label><input type="email" name="email" class="form-control" value="<?= e($profil['email'] ?? '') ?>"></div>
            <div class="col-md-6"><label class="form-label">Pendidikan Terakhir</label><input type="text" name="pendidikan" class="form-control" value="<?= e($profil['pendidikan'] ?? '') ?>"></div>
            <div class="col-md-6"><label class="form-label">Foto Profil</label><input type="file" name="foto" class="form-control" accept="image/*"></div>
            <div class="col-12"><label class="form-label">Alamat</label><textarea name="alamat" class="form-control" rows="2"><?= e($profil['alamat'] ?? '') ?></textarea></div>
            <div class="col-12"><label class="form-label">Tentang / Deskripsi</label><textarea name="tentang" class="form-control" rows="3"><?= e($profil['tentang'] ?? '') ?></textarea></div>
            <div class="col-12"><button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Simpan Profil</button></div>
          </div>
        </form>
      </div>
    </div>
    <?php endif; ?>

    <!-- Riwayat Tugas -->
    <div class="card">
      <div class="card-header">
        <span class="card-header-title"><i class="bi bi-clock-history me-2"></i>Riwayat Tugas</span>
        <?php if(isAdmin() && $profil): ?>
        <button class="btn btn-sm btn-outline-primary" data-bs-toggle="collapse" data-bs-target="#formRiwayat"><i class="bi bi-plus me-1"></i>Tambah</button>
        <?php endif; ?>
      </div>
      <?php if(isAdmin() && $profil): ?>
      <div class="collapse" id="formRiwayat">
        <div class="card-body border-bottom bg-light">
          <form method="POST">
            <?= csrf_field() ?><input type="hidden" name="action" value="riwayat">
            <div class="row g-2">
              <div class="col-md-5"><input type="text" name="rw_jabatan" class="form-control form-control-sm" placeholder="Jabatan" required></div>
              <div class="col-md-5"><input type="text" name="rw_unit_kerja" class="form-control form-control-sm" placeholder="Unit Kerja" required></div>
              <div class="col-md-2"><input type="number" name="rw_tahun_mulai" class="form-control form-control-sm" placeholder="Th Mulai" required min="1990" max="2030"></div>
              <div class="col-md-2"><input type="number" name="rw_tahun_selesai" class="form-control form-control-sm" placeholder="Th Selesai"></div>
              <div class="col-md-8"><input type="text" name="rw_keterangan" class="form-control form-control-sm" placeholder="Keterangan (opsional)"></div>
              <div class="col-md-2"><button type="submit" class="btn btn-primary btn-sm w-100">Simpan</button></div>
            </div>
          </form>
        </div>
      </div>
      <?php endif; ?>
      <div class="table-responsive">
        <table class="table table-hover mb-0">
          <thead><tr><th>Jabatan</th><th>Unit Kerja</th><th>Periode</th><?php if(isAdmin()): ?><th>Aksi</th><?php endif; ?></tr></thead>
          <tbody>
            <?php if(empty($riwayat)): ?>
            <tr><td colspan="4" class="text-center py-3 text-muted">Belum ada riwayat tugas</td></tr>
            <?php else: ?>
            <?php foreach($riwayat as $rw): ?>
            <tr>
              <td class="fw-600"><?= e($rw['jabatan']) ?></td>
              <td><?= e($rw['unit_kerja']) ?></td>
              <td style="white-space:nowrap"><?= $rw['tahun_mulai'] ?> – <?= $rw['tahun_selesai'] ?? 'Sekarang' ?></td>
              <?php if(isAdmin()): ?>
              <td><a href="?del_riwayat=<?= $rw['id'] ?>" class="btn btn-sm btn-outline-danger" data-confirm="Hapus riwayat ini?"><i class="bi bi-trash"></i></a></td>
              <?php endif; ?>
            </tr>
            <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<?php require_once ROOT_PATH . '/views/layouts/footer.php'; ?>
