<?php
include "../config/koneksi.php";
include "../middleware/auth.php";
include "../config/komplain_workflow.php";
sikompro_require_role('admin');
$profileUser = komplain_user_profile($conn, (int) $_SESSION['user_id']);
$adminNotifCount = komplain_notification_count($conn, 'admin');
$mulai = $_GET['mulai'] ?? date('Y-m-01');
$selesai = $_GET['selesai'] ?? date('Y-m-t');

if (isset($_POST['edit_gaji'])) {
    $uid = (int) $_POST['user_id'];
    $gaji = komplain_parse_money($_POST['gaji_harian'] ?? 0);
    $lembur = komplain_parse_money($_POST['gaji_lembur_per_jam'] ?? 0);
    $lemburTotal = komplain_parse_money($_POST['gaji_lembur_total'] ?? 0);
    mysqli_query($conn, "UPDATE users SET gaji_harian='{$gaji}', gaji_lembur_per_jam='{$lembur}', gaji_lembur_total='{$lemburTotal}' WHERE id='{$uid}'");
    header("Location: gaji.php?mulai=" . urlencode($mulai) . "&selesai=" . urlencode($selesai) . "&msg=edit");
    exit;
}

if (isset($_POST['hapus_gaji'])) {
    $uid = (int) $_POST['user_id'];
    mysqli_query($conn, "UPDATE users SET gaji_harian=0, gaji_lembur_per_jam=0, gaji_lembur_total=0 WHERE id='{$uid}'");
    header("Location: gaji.php?mulai=" . urlencode($mulai) . "&selesai=" . urlencode($selesai) . "&msg=hapus");
    exit;
}

$mulaiSql = mysqli_real_escape_string($conn, $mulai);
$selesaiSql = mysqli_real_escape_string($conn, $selesai);
$data = mysqli_query($conn, "SELECT u.id, u.username, u.role, u.gaji_harian, u.gaji_lembur_per_jam, u.gaji_lembur_total, COUNT(a.id) AS hari_masuk, COALESCE(SUM(CASE WHEN a.jam_lembur_mulai IS NOT NULL AND a.jam_lembur_selesai IS NOT NULL THEN LEAST(TIMESTAMPDIFF(MINUTE, a.jam_lembur_mulai, a.jam_lembur_selesai), 1440) ELSE 0 END),0) AS lembur_menit FROM users u LEFT JOIN absensi a ON a.user_id=u.id AND a.tanggal BETWEEN '{$mulaiSql}' AND '{$selesaiSql}' AND a.jam_masuk IS NOT NULL WHERE u.role IN ('admin','pelaksana','teknisi') GROUP BY u.id,u.username,u.role,u.gaji_harian,u.gaji_lembur_per_jam,u.gaji_lembur_total ORDER BY FIELD(u.role,'admin','pelaksana','teknisi'),u.username");
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Rangkuman Gaji / Salary Summary | 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">
<link rel="stylesheet" href="../assets/sikompro-ux.css?v=20260722.11">
<style>
.salary-shell { max-width: 1180px; margin: 0 auto; }
.salary-hero { background: linear-gradient(135deg, #fff 0%, #eef5ff 100%); border-radius: 24px; padding: 26px; margin-bottom: 18px; box-shadow: 0 14px 34px rgba(31,45,61,.08); }
.salary-card { border: 0; border-radius: 18px; box-shadow: 0 12px 28px rgba(31,45,61,.08); overflow: hidden; }
.salary-toolbar { display:flex; gap:10px; flex-wrap:wrap; align-items:center; }
.money-input { min-width:160px; text-align:right; }
.table td { vertical-align: middle; }
.salary-note { display:inline-flex; align-items:center; gap:8px; padding:8px 12px; border-radius:999px; background:#f4f8ff; color:#2e67d8; font-weight:700; }
@media (max-width: 768px) { .salary-hero { padding:18px; border-radius:18px; } .money-input { min-width: 120px; } }
</style>
</head>
<body class="hold-transition sidebar-mini dashboard-shell">
<div class="wrapper">
<nav class="main-header navbar navbar-expand navbar-white navbar-light"><ul class="navbar-nav"><li class="nav-item"><a class="nav-link" data-widget="pushmenu" href="#"><i class="fas fa-bars"></i></a></li></ul><ul class="navbar-nav ms-auto align-items-center"><li class="nav-item"><button type="button" class="btn btn-outline-light btn-sm dashboard-theme-toggle" data-theme-toggle><i data-theme-toggle-icon class="fa fa-adjust"></i><span data-theme-toggle-label>Mode Siang</span></button></li></ul></nav>
<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>Admin</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="absen.php" class="nav-link"><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 active"><i class="nav-icon fas fa-money-bill"></i> Gaji / Salary</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="notif.php" class="nav-link"><i class="nav-icon fas fa-bell"></i> Notifikasi <span class="badge bg-warning text-dark float-end"><?= $adminNotifCount ?></span></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>
<li class="nav-item mt-2 px-3"><button type="button" class="btn sidebar-theme-toggle" data-theme-toggle><i data-theme-toggle-icon class="fa fa-adjust"></i><span data-theme-toggle-label>Mode Siang</span></button></li>
</ul>
</div>
</aside>
<div class="content-wrapper p-3">
<div class="salary-shell">
<div class="salary-hero">
<div class="d-flex justify-content-between flex-wrap align-items-center" style="gap:12px;">
<div>
<div class="text-uppercase small text-muted font-weight-bold">Payroll / Penggajian</div>
<h3 class="mb-1">Rangkuman Gaji Per Periode</h3>
<p class="mb-0">Hitung, ubah, dan cetak gaji harian plus lembur manual atau per jam. Lembur tetap ditampilkan sebagai referensi jam.</p>
</div>
<div class="salary-toolbar">
<a href="absen.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Absen / Attendance</a>
<a target="_blank" href="cetak_gaji.php?mulai=<?= urlencode($mulai) ?>&selesai=<?= urlencode($selesai) ?>" class="btn btn-primary"><i class="fas fa-file-pdf"></i> Cetak PDF</a>
</div>
</div>
</div>
<?php if(isset($_GET['msg'])): ?><div class="alert alert-success">Data gaji berhasil diproses / Salary updated.</div><?php endif; ?>
<div class="card salary-card mb-3"><div class="card-body"><div class="d-flex flex-wrap justify-content-between align-items-center" style="gap:12px;">
<form method="get" class="row g-2 align-items-end mb-0">
<label class="me-2">Mulai / Start</label><input type="date" name="mulai" class="form-control mr-2" value="<?= htmlspecialchars($mulai) ?>">
<label class="me-2">Selesai / End</label><input type="date" name="selesai" class="form-control mr-2" value="<?= htmlspecialchars($selesai) ?>">
<button class="btn btn-info"><i class="fas fa-filter"></i> Filter</button>
</form>
<span class="salary-note"><i class="fas fa-calculator"></i> Gaji lembur bisa diisi nominal total, tidak wajib dihitung per jam.</span>
</div></div></div>
<div class="card salary-card"><div class="card-body table-responsive">
<table class="table table-bordered table-striped">
<thead><tr><th>Nama / Name</th><th>Role</th><th>Hari Masuk / Days</th><th>Gaji Harian / Daily Pay</th><th>Gaji Lembur / OT Rate</th><th>Gaji Lembur Total</th><th>Lembur</th><th>Total Gaji / Total</th><th>Aksi</th></tr></thead>
<tbody>
<?php $grand=0; while($r=mysqli_fetch_assoc($data)): $lemburJam=komplain_absensi_overtime_hours($r); $lemburRate=komplain_absensi_overtime_rate($r); $lemburTotal=(float)($r['gaji_lembur_total'] ?? 0); if ($lemburTotal <= 0) { $lemburTotal = komplain_absensi_overtime_subtotal($r, $lemburRate); } $total=((int)$r['hari_masuk']*(float)$r['gaji_harian'])+$lemburTotal; $grand+=$total; ?>
<tr>
<form method="post">
<td><?= htmlspecialchars($r['username']) ?></td>
<td><?= htmlspecialchars($r['role']) ?></td>
<td><?= (int)$r['hari_masuk'] ?></td>
<td><input type="text" name="gaji_harian" class="form-control money-input" value="<?= number_format((float)$r['gaji_harian'],0,',','.') ?>"></td>
<td><input type="text" name="gaji_lembur_per_jam" class="form-control money-input" value="<?= number_format((float)($r['gaji_lembur_per_jam'] ?? 0),0,',','.') ?>"></td>
<td><input type="text" name="gaji_lembur_total" class="form-control money-input" value="<?= number_format((float)($r['gaji_lembur_total'] ?? 0),0,',','.') ?>"></td>
<td>
    <?= number_format($lemburJam, 2, ',', '.') ?> jam
    <br><small class="text-muted">Rp <?= number_format($lemburTotal,0,',','.') ?></small>
</td>
<td>Rp <?= number_format($total,0,',','.') ?></td>
<td><input type="hidden" name="user_id" value="<?= (int)$r['id'] ?>"><button name="edit_gaji" class="btn btn-outline-warning btn-sm"><i class="fas fa-save"></i> Edit</button> <button name="hapus_gaji" class="btn btn-outline-danger btn-sm" onclick="return confirm('Kosongkan gaji harian user ini? / Reset daily pay?')"><i class="fas fa-trash"></i> Hapus</button></td>
</form>
</tr>
<?php endwhile; ?>
<tr><th colspan="7">Total Keseluruhan / Grand Total</th><th colspan="2">Rp <?= number_format($grand,0,',','.') ?></th></tr>
</tbody></table></div></div>
</div></div>
<script>
function rupiah(n){return 'Rp '+String(Math.round(n||0)).replace(/\B(?=(\d{3})+(?!\d))/g,'.');}
function hitungGaji(){
    let grand=0;
    document.querySelectorAll('tbody tr').forEach((row,index,rows)=>{
        if (index === rows.length - 1) {
            rows[index].children[1].textContent=rupiah(grand);
            return;
        }
        const hari=parseInt(row.children[2].textContent)||0;
        const gaji=parseInt(row.children[3].querySelector('input').value.replace(/\D/g,''))||0;
        const lemburRate=parseInt(row.children[4].querySelector('input').value.replace(/\D/g,''))||0;
        const lemburManual=parseInt(row.children[5].querySelector('input').value.replace(/\D/g,''))||0;
        const lemburJam=parseFloat((row.children[6].textContent||'0').replace(/[^0-9.,]/g,'').replace(',', '.'))||0;
        const total=(hari*gaji)+(lemburManual>0 ? lemburManual : (lemburJam*lemburRate));
        grand+=total;
        row.children[7].textContent=rupiah(total);
    });
}
document.querySelectorAll('.money-input').forEach(input=>{input.addEventListener('input',()=>{let v=input.value.replace(/\D/g,'');input.value=v.replace(/\B(?=(\d{3})+(?!\d))/g,'.');hitungGaji();});});
hitungGaji();
</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>












