<?php
include "../config/koneksi.php";
include "../middleware/auth.php";
include "../config/komplain_workflow.php";

sikompro_require_role('pelaksana');

$user_id = (int) $_SESSION['user_id'];
$role = $_SESSION['role'];
$today = date('Y-m-d');
$profileUser = komplain_user_profile($conn, $user_id);
$folder = "../uploads/absen/";

if (isset($_POST['masuk'])) {
    $lat = mysqli_real_escape_string($conn, $_POST['lat'] ?? '');
    $lng = mysqli_real_escape_string($conn, $_POST['lng'] ?? '');
    $lokasiNama = komplain_escape($conn, komplain_reverse_geocode_label($lat, $lng));
    $foto = komplain_save_base64_image($_POST['foto_base64'] ?? '', $folder, 'absen_pelaksana_' . $user_id);

    if ($foto === '' && !empty($_FILES['foto']['name'])) {
        $foto = time() . '_' . preg_replace('/[^A-Za-z0-9._-]/', '_', $_FILES['foto']['name']);
        if (!is_dir($folder)) mkdir($folder, 0777, true);
        move_uploaded_file($_FILES['foto']['tmp_name'], $folder . $foto);
    }

    $existing = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id FROM absensi WHERE user_id='{$user_id}' AND tanggal='{$today}' LIMIT 1"));
    if ($existing) {
        mysqli_query($conn, "UPDATE absensi SET role='{$role}', jam_masuk=COALESCE(jam_masuk,NOW()), latitude='{$lat}', longitude='{$lng}', lokasi_nama='{$lokasiNama}', foto='{$foto}', status='Masuk' WHERE id='" . (int)$existing['id'] . "'");
    } else {
        mysqli_query($conn, "INSERT INTO absensi(user_id,role,tanggal,jam_masuk,latitude,longitude,lokasi_nama,foto,status) VALUES('{$user_id}','{$role}','{$today}',NOW(),'{$lat}','{$lng}','{$lokasiNama}','{$foto}','Masuk')");
    }
    header("Location: absen.php?msg=masuk");
    exit;
}

if (isset($_POST['pulang'])) {
    $fotoPulang = komplain_save_base64_image($_POST['foto_pulang_base64'] ?? '', $folder, 'pulang_pelaksana_' . $user_id);
    if ($fotoPulang === '' && !empty($_FILES['foto_pulang']['name'])) {
        $fotoPulang = time() . '_pulang_' . preg_replace('/[^A-Za-z0-9._-]/', '_', $_FILES['foto_pulang']['name']);
        if (!is_dir($folder)) mkdir($folder, 0777, true);
        move_uploaded_file($_FILES['foto_pulang']['tmp_name'], $folder . $fotoPulang);
    }
    mysqli_query($conn, "UPDATE absensi SET jam_pulang=NOW(), foto_pulang='{$fotoPulang}', status='Pulang' WHERE user_id='{$user_id}' AND tanggal='{$today}'");
    header("Location: absen.php?msg=pulang");
    exit;
}

if (isset($_POST['lembur_mulai'])) {
    mysqli_query($conn, "UPDATE absensi SET jam_lembur_mulai=NOW(), status='Lembur' WHERE user_id='{$user_id}' AND tanggal='{$today}'");
    header("Location: absen.php?msg=lembur_mulai");
    exit;
}

if (isset($_POST['lembur_selesai'])) {
    $fotoLembur = komplain_save_base64_image($_POST['foto_lembur_base64'] ?? '', $folder, 'lembur_pelaksana_' . $user_id);
    $keteranganLembur = komplain_escape($conn, $_POST['keterangan_lembur'] ?? '');
    if ($fotoLembur === '' && !empty($_FILES['foto_lembur']['name'])) {
        $fotoLembur = time() . '_lembur_' . preg_replace('/[^A-Za-z0-9._-]/', '_', $_FILES['foto_lembur']['name']);
        if (!is_dir($folder)) mkdir($folder, 0777, true);
        move_uploaded_file($_FILES['foto_lembur']['tmp_name'], $folder . $fotoLembur);
    }
    mysqli_query($conn, "UPDATE absensi SET jam_lembur_selesai=NOW(), foto_lembur='{$fotoLembur}', keterangan_lembur='{$keteranganLembur}', status='Pulang' WHERE user_id='{$user_id}' AND tanggal='{$today}'");
    header("Location: absen.php?msg=lembur_selesai");
    exit;
}

$data = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM absensi WHERE user_id='{$user_id}' AND tanggal='{$today}' LIMIT 1"));
$riwayatSaya = mysqli_query($conn, "SELECT * FROM absensi WHERE user_id='{$user_id}' ORDER BY tanggal DESC, id DESC LIMIT 20");
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Absensi Pelaksana | PT Alvindo</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body.dashboard-shell{background:radial-gradient(circle at top left, rgba(14,165,233,.18), transparent 34%), radial-gradient(circle at top right, rgba(249,115,22,.14), transparent 30%), linear-gradient(180deg,#06111f 0%,#0b1730 48%,#0f1f3d 100%);color:#eef5ff}
body.dashboard-shell .content-wrapper{background:transparent}
.main-sidebar{background:linear-gradient(180deg,#10213b 0%,#0c1729 100%)}
.hero{background:linear-gradient(135deg, rgba(9,17,32,.94) 0%, rgba(14,34,63,.88) 100%);border:1px solid rgba(148,163,184,.16);border-radius:22px;padding:24px;margin-bottom:18px;box-shadow:0 18px 38px rgba(2,8,23,.22);color:#eef5ff}
.card{border:1px solid rgba(148,163,184,.16);border-radius:20px;box-shadow:0 16px 34px rgba(2,8,23,.16);background:rgba(9,17,32,.94);color:#eef5ff}
.card-header{background:linear-gradient(135deg, rgba(15,23,42,.92) 0%, rgba(30,41,59,.92) 100%);border-bottom:1px solid rgba(148,163,184,.14)}
.status-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px}
.status-tile{background:linear-gradient(135deg, rgba(15,23,42,.86) 0%, rgba(30,41,59,.76) 100%);border:1px solid rgba(148,163,184,.18);border-radius:14px;padding:14px;color:#eef5ff}
.sidebar-profile{text-align:center;padding:14px 8px;color:#fff;border-bottom:1px solid rgba(255,255,255,.12)}
.sidebar-profile img{width:76px;height:76px;object-fit:cover;border-radius:50%;border:3px solid rgba(255,255,255,.45)}
.thumb{width:74px;height:74px;object-fit:cover;border-radius:10px;border:1px solid rgba(148,163,184,.18)}
.camera-box{display:grid;grid-template-columns:minmax(220px,360px) 1fr;gap:14px;align-items:start}
.camera-box video,.camera-box img{width:100%;border-radius:12px;border:1px solid rgba(148,163,184,.16);background:#07101d;aspect-ratio:4/3;object-fit:cover}
@media(max-width:768px){.camera-box{grid-template-columns:1fr}.content-wrapper{padding:12px!important}.hero{padding:18px;border-radius:18px}}
</style>
<link rel="stylesheet" href="../assets/sikompro-ux.css?v=20260722.11">
</head>
<body class="hold-transition sidebar-mini layout-fixed dashboard-shell"><div class="wrapper">
<aside class="main-sidebar sidebar-dark-primary elevation-4"><a href="dashboard.php" class="brand-link text-center">PT. ALVINDO</a><div class="sidebar"><div class="sidebar-profile"><img src="<?= komplain_profile_photo_url($profileUser) ?>" alt="Foto profil"><div class="mt-2 font-weight-bold"><?= htmlspecialchars($profileUser['username']) ?></div><small><?= htmlspecialchars(ucfirst($profileUser['role'])) ?></small></div><ul class="nav nav-pills nav-sidebar flex-column">
<li class="nav-item"><a href="dashboard.php" class="nav-link"><i class="nav-icon fas fa-home"></i> Dashboard</a></li>
<li class="nav-item"><a href="data_komplain.php?filter=total" class="nav-link"><i class="nav-icon fas fa-table"></i> Data Komplain</a></li>
<li class="nav-item"><a href="absen.php" class="nav-link active"><i class="nav-icon fas fa-user-check"></i> Absen Saya</a></li>
<li class="nav-item"><a href="data_absensi.php" class="nav-link"><i class="nav-icon fas fa-users"></i> Data Absensi</a></li>
<li class="nav-item"><a href="gaji.php" class="nav-link"><i class="nav-icon fas fa-money-bill-wave"></i> Gaji</a></li>
<li class="nav-item"><a href="users.php" class="nav-link"><i class="nav-icon fas fa-user-cog"></i> Akses User</a></li>
<li class="nav-item"><a href="profil.php" class="nav-link"><i class="nav-icon fas fa-user-circle"></i> Profil</a></li>
<li class="nav-item"><a href="../middleware/logout.php" class="nav-link"><i class="nav-icon fas fa-sign-out-alt"></i> Logout</a></li>
</ul></div></aside>
<div class="content-wrapper p-3"><div class="container-fluid">
<div class="hero"><div class="d-flex justify-content-between flex-wrap align-items-center" style="gap:10px;"><div><h4 class="mb-1">Absensi Pelaksana</h4><p class="mb-0">Gunakan kamera realtime HP Android untuk absen masuk, pulang, dan lembur.</p></div><div><a href="data_absensi.php" class="btn btn-outline-primary"><i class="fas fa-users"></i> Data Absensi</a> <a href="gaji.php" class="btn btn-outline-success"><i class="fas fa-money-bill"></i> Gaji</a></div></div></div>
<?php if(isset($_GET['msg'])): ?><div class="alert alert-success"><?= htmlspecialchars($_GET['msg']) ?></div><?php endif; ?>
<div class="card mb-3"><div class="card-header bg-primary text-white"><h5 class="mb-0"><i class="fas fa-camera mr-1"></i> Absen Saya Hari Ini</h5></div><div class="card-body">
<div class="status-grid mb-3"><div class="status-tile"><small>Tanggal</small><h5><?= date('d-m-Y') ?></h5></div><div class="status-tile"><small>Masuk</small><h5><?= $data && $data['jam_masuk'] ? htmlspecialchars($data['jam_masuk']) : '-' ?></h5></div><div class="status-tile"><small>Pulang</small><h5><?= $data && $data['jam_pulang'] ? htmlspecialchars($data['jam_pulang']) : '-' ?></h5></div><div class="status-tile"><small>Status</small><h5><?= $data ? htmlspecialchars($data['status'] ?: '-') : 'Belum Absen' ?></h5></div></div>
<?php if(!$data): ?>
<form method="post" enctype="multipart/form-data" id="absenForm">
<input type="hidden" name="lat" id="lat"><input type="hidden" name="lng" id="lng"><input type="hidden" name="foto_base64" id="foto_base64">
<div class="camera-box mb-3"><video id="cameraVideo" autoplay playsinline muted></video><div><img id="cameraPreview" alt="Preview foto" style="display:none"><div class="alert alert-info mb-2">Tekan Ambil Foto dulu, lalu simpan absen. Jika kamera browser ditolak, gunakan pilih file.</div><input type="file" name="foto" accept="image/*" capture="user" class="form-control"></div></div>
<button type="button" class="btn btn-outline-primary" id="captureBtn"><i class="fas fa-camera"></i> Ambil Foto</button>
<button name="masuk" class="btn btn-success"><i class="fas fa-check"></i> Absen Masuk</button>
</form>
<?php elseif(!$data['jam_pulang']): ?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="foto_pulang_base64" id="foto_pulang_base64">
<div class="camera-box mb-3"><video id="cameraVideoPulang" autoplay playsinline muted></video><div><img id="cameraPreviewPulang" alt="Preview pulang" style="display:none"><div class="alert alert-warning mb-2">Absen pulang wajib ambil foto kamera atau pilih file.</div><input type="file" name="foto_pulang" accept="image/*" capture="user" class="form-control"></div></div>
<button type="button" class="btn btn-outline-primary" id="capturePulangBtn"><i class="fas fa-camera"></i> Ambil Foto Pulang</button>
<button name="pulang" class="btn btn-danger"><i class="fas fa-clock"></i> Absen Pulang</button>
</form>
<?php else: ?><div class="alert alert-success mb-0">Absensi hari ini sudah lengkap.</div><?php endif; ?>
<?php if($data && $data['jam_masuk']): ?>
<form method="post" enctype="multipart/form-data" class="mt-3">
<?php if(empty($data['jam_lembur_mulai'])): ?>
<button name="lembur_mulai" class="btn btn-outline-dark"><i class="fas fa-business-time"></i> Mulai Lembur</button>
<?php elseif(empty($data['jam_lembur_selesai'])): ?>
<input type="hidden" name="foto_lembur_base64" id="foto_lembur_base64">
<div class="camera-box mb-3"><video id="cameraVideoLembur" autoplay playsinline muted></video><div><img id="cameraPreviewLembur" alt="Preview lembur" style="display:none"><textarea name="keterangan_lembur" class="form-control mb-2" placeholder="Keterangan lembur (opsional)"></textarea><input type="file" name="foto_lembur" accept="image/*" capture="user" class="form-control"></div></div>
<button type="button" class="btn btn-outline-primary" id="captureLemburBtn"><i class="fas fa-camera"></i> Ambil Foto Lembur</button>
<button name="lembur_selesai" class="btn btn-dark"><i class="fas fa-check"></i> Selesai Lembur</button>
<?php endif; ?>
</form>
<?php endif; ?>
</div></div>
<div class="card"><div class="card-header"><h5 class="mb-0"><i class="fas fa-history mr-1"></i> Data Absen Saya</h5></div><div class="card-body table-responsive"><table class="table table-bordered table-striped"><thead><tr><th>Tanggal</th><th>Masuk</th><th>Pulang</th><th>Lembur</th><th>Lokasi</th><th>Foto Masuk</th><th>Foto Pulang</th><th>Foto Lembur</th></tr></thead><tbody>
<?php while($row=mysqli_fetch_assoc($riwayatSaya)): ?><tr><td><?= htmlspecialchars($row['tanggal']) ?></td><td><?= htmlspecialchars((string)$row['jam_masuk']) ?></td><td><?= htmlspecialchars((string)($row['jam_pulang'] ?: '-')) ?></td><td><?= htmlspecialchars(trim(($row['jam_lembur_mulai'] ?? '') . ' - ' . ($row['jam_lembur_selesai'] ?? '')) ?: '-') ?><br><small class="text-muted"><?= htmlspecialchars(komplain_absensi_overtime_label($row)) ?></small></td><td><?= htmlspecialchars(komplain_absensi_location_label($row)) ?></td><td><?php if($row['foto']): ?><img class="thumb" src="../uploads/absen/<?= rawurlencode($row['foto']) ?>" alt="Foto masuk"><?php else: ?>-<?php endif; ?></td><td><?php if(!empty($row['foto_pulang'])): ?><img class="thumb" src="../uploads/absen/<?= rawurlencode($row['foto_pulang']) ?>" alt="Foto pulang"><?php else: ?>-<?php endif; ?></td><td><?php if(!empty($row['foto_lembur'])): ?><img class="thumb" src="../uploads/absen/<?= rawurlencode($row['foto_lembur']) ?>" alt="Foto lembur"><?php else: ?>-<?php endif; ?><br><small class="text-muted"><?= htmlspecialchars((string)($row['keterangan_lembur'] ?? '-')) ?></small></td></tr><?php endwhile; ?>
</tbody></table></div></div>
</div></div></div>
<script>
if (navigator.geolocation) navigator.geolocation.getCurrentPosition(pos=>{lat.value=pos.coords.latitude;lng.value=pos.coords.longitude;});
const video=document.getElementById('cameraVideo'), preview=document.getElementById('cameraPreview'), fotoBase64=document.getElementById('foto_base64');
if (video && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) navigator.mediaDevices.getUserMedia({video:{facingMode:'user'},audio:false}).then(s=>video.srcObject=s).catch(()=>{});
document.getElementById('captureBtn')?.addEventListener('click',()=>{const c=document.createElement('canvas');c.width=video.videoWidth||640;c.height=video.videoHeight||480;c.getContext('2d').drawImage(video,0,0,c.width,c.height);fotoBase64.value=c.toDataURL('image/jpeg',.86);preview.src=fotoBase64.value;preview.style.display='block';});
function setupCamera(videoId, previewId, inputId, buttonId){const v=document.getElementById(videoId),p=document.getElementById(previewId),i=document.getElementById(inputId);if(v&&navigator.mediaDevices)navigator.mediaDevices.getUserMedia({video:{facingMode:'user'},audio:false}).then(s=>v.srcObject=s).catch(()=>{});document.getElementById(buttonId)?.addEventListener('click',()=>{const c=document.createElement('canvas');c.width=v.videoWidth||640;c.height=v.videoHeight||480;c.getContext('2d').drawImage(v,0,0,c.width,c.height);i.value=c.toDataURL('image/jpeg',.86);p.src=i.value;p.style.display='block';});}
setupCamera('cameraVideoPulang','cameraPreviewPulang','foto_pulang_base64','capturePulangBtn');
setupCamera('cameraVideoLembur','cameraPreviewLembur','foto_lembur_base64','captureLemburBtn');
document.querySelectorAll('form').forEach(form=>form.addEventListener('submit',e=>{const foto=form.querySelector('input[type="file"]');const hidden=form.querySelector('input[name$="_base64"], input[name="foto_base64"]');if(hidden&&!hidden.value&&foto&&!foto.value){e.preventDefault();alert('Ambil foto kamera atau pilih foto dari folder terlebih dahulu.');}}));</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script>
<script src="../assets/bootstrap5-compat.js"></script>
<script src="../assets/sikompro-theme.js?v=20260722.11"></script>
<?php include '../partials/mobile_nav.php'; ?>
</body></html>
















