<?php
$judul = "MOD – Jadwal Shift";
$menu  = "mod";

include 'layout/header.php';

// Hanya Store Manager yang boleh akses
if ($_SESSION['role'] !== 'Store_Manager') {
    header('Location: dashboard.php'); exit;
}

$id_user = $_SESSION['id_user'];
$today   = date('Y-m-d');

/* =========================================================
   HANDLE FORM SUBMIT
   ========================================================= */
$error   = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $aksi = $_POST['aksi'] ?? '';

    // -- Tambah / Edit --
    if ($aksi === 'simpan') {
        $tanggal    = mysqli_real_escape_string($conn, $_POST['tanggal']    ?? $today);
        $shift      = mysqli_real_escape_string($conn, $_POST['shift']      ?? '');
        $id_petugas = (int)($_POST['id_petugas'] ?? 0);
        $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan'] ?? '');
        $id_mod     = (int)($_POST['id_mod']     ?? 0);

        if (!$tanggal || !$shift || !$id_petugas) {
            $error = 'Tanggal, shift, dan petugas wajib diisi.';
        } else {
            // Cek duplikat shift di tanggal yang sama (kecuali saat edit)
            $dup_sql = "SELECT id_mod FROM mod_harian
                        WHERE tanggal='$tanggal' AND shift='$shift'
                        " . ($id_mod ? "AND id_mod <> $id_mod" : "") . "
                        LIMIT 1";
            $dup = mysqli_fetch_assoc(mysqli_query($conn, $dup_sql));
            if ($dup) {
                $error = "Shift <strong>$shift</strong> pada tanggal <strong>$tanggal</strong> sudah ada.";
            } else {
                if ($id_mod) {
                    // Update
                    mysqli_query($conn, "
                        UPDATE mod_harian
                        SET tanggal='$tanggal', shift='$shift',
                            id_petugas=$id_petugas, keterangan='$keterangan'
                        WHERE id_mod=$id_mod AND id_user=$id_user
                    ");
                    $success = 'Jadwal berhasil diperbarui.';
                } else {
                    // Insert
                    mysqli_query($conn, "
                        INSERT INTO mod_harian (tanggal, shift, id_petugas, id_user, keterangan)
                        VALUES ('$tanggal','$shift',$id_petugas,$id_user,'$keterangan')
                    ");
                    $success = 'Jadwal shift berhasil disimpan.';
                }
            }
        }
    }

    // -- Hapus --
    if ($aksi === 'hapus') {
        $id_mod = (int)($_POST['id_mod'] ?? 0);
        if ($id_mod) {
            mysqli_query($conn, "DELETE FROM mod_harian WHERE id_mod=$id_mod AND id_user=$id_user");
            $success = 'Jadwal berhasil dihapus.';
        }
    }
}

/* =========================================================
   DATA
   ========================================================= */
// Filter bulan
$filter_bulan = $_GET['bulan'] ?? date('Y-m');
[$fy, $fm]    = explode('-', $filter_bulan . '-01');
$start = $filter_bulan . '-01';
$end   = date('Y-m-t', strtotime($start));

// Daftar user untuk dropdown (semua user aktif kecuali admin/direktur)
$users_q = mysqli_query($conn, "
    SELECT id_user, nama, role FROM users
    WHERE status='aktif'
    AND role NOT IN ('admin','direktur')
    ORDER BY nama
");

// Jadwal bulan ini
$jadwal_q = mysqli_query($conn, "
    SELECT mh.*, u.nama, u.role
    FROM mod_harian mh
    INNER JOIN users u ON mh.id_petugas = u.id_user
    WHERE mh.tanggal BETWEEN '$start' AND '$end'
    ORDER BY mh.tanggal ASC, FIELD(mh.shift,'Pagi','Siang')
");

// Data untuk edit (jika ada ?edit=)
$edit_data = null;
if (isset($_GET['edit'])) {
    $edit_id   = (int)$_GET['edit'];
    $edit_data = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT * FROM mod_harian WHERE id_mod=$edit_id AND id_user=$id_user LIMIT 1"
    ));
}
?>

<style>
/* ── Card dasar ── */
.mod-card {
    background: var(--surface-1) !important;
    border: 1px solid var(--mint-border) !important;
    border-radius: 14px !important;
}
.mod-card .card-body { padding: 22px 24px; }
.section-title {
    font-size: 0.78rem; font-weight: 700; letter-spacing: 0.08em;
    text-transform: uppercase; color: var(--text-secondary);
    margin-bottom: 16px;
}

/* ── Form inputs ── */
.mod-input, .mod-select {
    background: #ffffff !important;
    border: 1.5px solid #d1d5db !important;
    color: #111827 !important;
    border-radius: 8px; padding: 9px 13px; font-size: 0.875rem;
    width: 100%; transition: border-color 0.2s, box-shadow 0.2s;
}
.mod-input:focus, .mod-select:focus {
    outline: none;
    border-color: var(--emerald-400) !important;
    box-shadow: 0 0 0 3px rgba(16,185,129,0.18);
}
.mod-input::placeholder { color: #9ca3af; }
.mod-select option {
    background: #ffffff;
    color: #111827;
}

/* ── Shift badge ── */
.badge-pagi  { background: rgba(251,191,36,0.15); color: #fbbf24; border: 1px solid rgba(251,191,36,0.3); }
.badge-siang { background: rgba(96,165,250,0.15);  color: #60a5fa;  border: 1px solid rgba(96,165,250,0.3);  }
.shift-badge {
    display: inline-block; padding: 3px 12px;
    border-radius: 999px; font-size: 0.72rem; font-weight: 700;
    letter-spacing: 0.06em; text-transform: uppercase;
}

/* ── Tabel jadwal ── */
.mod-table { width: 100%; border-collapse: collapse; }
.mod-table th {
    font-size: 0.72rem; font-weight: 700; letter-spacing: 0.07em;
    text-transform: uppercase; color: var(--text-secondary);
    padding: 10px 14px; border-bottom: 1px solid var(--mint-border);
    text-align: left;
}
.mod-table td {
    padding: 11px 14px; font-size: 0.85rem;
    color: var(--text-primary); border-bottom: 1px solid rgba(255,255,255,0.04);
    vertical-align: middle;
}
.mod-table tr:last-child td { border-bottom: none; }
.mod-table tr:hover td { background: rgba(16,185,129,0.04); }

/* ── Today highlight ── */
.row-today td { background: rgba(16,185,129,0.07) !important; }
.today-dot {
    display: inline-block; width: 7px; height: 7px;
    background: var(--emerald-400); border-radius: 50%;
    margin-right: 6px; vertical-align: middle;
}

/* ── Tombol aksi ── */
.btn-mod-edit {
    background: rgba(96,165,250,0.12); border: 1px solid rgba(96,165,250,0.3);
    color: #60a5fa; border-radius: 7px; padding: 4px 11px;
    font-size: 0.75rem; font-weight: 600; cursor: pointer;
    text-decoration: none; display: inline-flex; align-items: center; gap: 5px;
    transition: background 0.2s, border-color 0.2s;
}
.btn-mod-edit:hover { background: rgba(96,165,250,0.25); color: #60a5fa; }
.btn-mod-del {
    background: rgba(239,68,68,0.1); border: 1px solid rgba(239,68,68,0.25);
    color: #f87171; border-radius: 7px; padding: 4px 11px;
    font-size: 0.75rem; font-weight: 600; cursor: pointer;
    transition: background 0.2s;
}
.btn-mod-del:hover { background: rgba(239,68,68,0.22); }

/* ── Submit button ── */
.btn-save {
    background: linear-gradient(135deg, var(--emerald-600), var(--emerald-400));
    border: none; color: #fff; font-weight: 700; font-size: 0.875rem;
    border-radius: 9px; padding: 10px 26px; cursor: pointer;
    box-shadow: 0 4px 14px rgba(16,185,129,0.25);
    transition: opacity 0.2s, transform 0.15s;
}
.btn-save:hover { opacity: 0.9; transform: translateY(-1px); }

/* ── Filter bulan ── */
.filter-bar {
    display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
    margin-bottom: 16px;
}
.filter-bar label { font-size: 0.78rem; color: var(--text-secondary); font-weight: 600; }

/* ── Empty state ── */
.empty-state {
    text-align: center; padding: 40px 20px;
    color: var(--text-muted); font-size: 0.85rem;
}
.empty-state .empty-icon { font-size: 2.5rem; margin-bottom: 10px; display: block; }

/* ── Alert ── */
.mod-alert {
    border-radius: 10px; padding: 11px 16px; font-size: 0.84rem;
    margin-bottom: 16px; border: 1px solid transparent;
}
.mod-alert-success { background: rgba(16,185,129,0.1); border-color: rgba(16,185,129,0.3); color: #34d399; }
.mod-alert-danger  { background: rgba(239,68,68,0.1);  border-color: rgba(239,68,68,0.3);  color: #f87171; }
</style>

<?php include 'layout/sidebar.php'; ?>

<!-- Alert -->
<?php if ($success): ?>
    <div class="mod-alert mod-alert-success">✅ <?= $success ?></div>
<?php endif; ?>
<?php if ($error): ?>
    <div class="mod-alert mod-alert-danger">⚠️ <?= $error ?></div>
<?php endif; ?>

<!-- ══════════════════════════════════════
     FORM INPUT / EDIT
     ══════════════════════════════════════ -->
<div class="card mod-card shadow-sm mb-3">
    <div class="card-body">
        <div class="section-title">
            <?= $edit_data ? '✏️ Edit Jadwal Shift' : '➕ Tambah Jadwal Shift' ?>
        </div>

        <form method="POST" action="mod.php">
            <input type="hidden" name="aksi"   value="simpan">
            <input type="hidden" name="id_mod"  value="<?= $edit_data['id_mod'] ?? '' ?>">

            <div class="row g-3">
                <!-- Tanggal -->
                <div class="col-6 col-md-3">
                    <label class="section-title mb-1" style="margin:0 0 6px;display:block;">Tanggal</label>
                    <input type="date" name="tanggal" class="mod-input"
                           value="<?= htmlspecialchars($edit_data['tanggal'] ?? $today) ?>" required>
                </div>

                <!-- Shift -->
                <div class="col-6 col-md-2">
                    <label class="section-title mb-1" style="margin:0 0 6px;display:block;">Shift</label>
                    <select name="shift" class="mod-select" required>
                        <option value="">— Pilih —</option>
                        <option value="Pagi"  <?= ($edit_data['shift'] ?? '') === 'Pagi'  ? 'selected' : '' ?>>☀️ Pagi</option>
                        <option value="Siang" <?= ($edit_data['shift'] ?? '') === 'Siang' ? 'selected' : '' ?>>🌤 Siang</option>
                    </select>
                </div>

                <!-- Petugas -->
                <div class="col-12 col-md-4">
                    <label class="section-title mb-1" style="margin:0 0 6px;display:block;">Petugas</label>
                    <select name="id_petugas" class="mod-select" required>
                        <option value="">— Pilih Petugas —</option>
                        <?php
                        mysqli_data_seek($users_q, 0);
                        while ($u = mysqli_fetch_assoc($users_q)):
                            $sel = ($edit_data['id_petugas'] ?? '') == $u['id_user'] ? 'selected' : '';
                        ?>
                            <option value="<?= $u['id_user'] ?>" <?= $sel ?>>
                                <?= htmlspecialchars($u['nama']) ?>
                                (<?= htmlspecialchars($u['role']) ?>)
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <!-- Keterangan -->
                <div class="col-12 col-md-3">
                    <label class="section-title mb-1" style="margin:0 0 6px;display:block;">Keterangan <span style="color:var(--text-muted);font-size:0.7rem;">(opsional)</span></label>
                    <input type="text" name="keterangan" class="mod-input"
                           placeholder="cth: Ganti shift, Lembur…"
                           value="<?= htmlspecialchars($edit_data['keterangan'] ?? '') ?>">
                </div>
            </div>

            <div class="mt-3 d-flex gap-2 align-items-center">
                <button type="submit" class="btn-save">
                    <?= $edit_data ? '💾 Perbarui' : '✅ Simpan Jadwal' ?>
                </button>
                <?php if ($edit_data): ?>
                    <a href="mod.php" style="font-size:0.82rem;color:var(--text-muted);">Batal</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<!-- ══════════════════════════════════════
     TABEL JADWAL
     ══════════════════════════════════════ -->
<div class="card mod-card shadow-sm">
    <div class="card-body">

        <!-- Filter bulan -->
        <div class="filter-bar">
            <span class="section-title" style="margin:0;">📋 Jadwal Shift</span>
            <form method="GET" action="mod.php" style="display:flex;align-items:center;gap:8px;margin-left:auto;">
                <label>Bulan:</label>
                <input type="month" name="bulan" class="mod-input" style="width:auto;padding:6px 12px;"
                       value="<?= htmlspecialchars($filter_bulan) ?>"
                       onchange="this.form.submit()">
            </form>
        </div>

        <?php $rows = mysqli_num_rows($jadwal_q); ?>
        <?php if ($rows === 0): ?>
            <div class="empty-state">
                <span class="empty-icon">📭</span>
                Belum ada jadwal shift untuk bulan ini.
            </div>
        <?php else: ?>
        <div style="overflow-x:auto;">
        <table class="mod-table">
            <thead>
                <tr>
                    <th>Tanggal</th>
                    <th>Hari</th>
                    <th>Shift</th>
                    <th>Petugas</th>
                    <th>Role</th>
                    <th>Keterangan</th>
                    <th style="text-align:center;">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $days_id = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
                while ($row = mysqli_fetch_assoc($jadwal_q)):
                    $is_today = ($row['tanggal'] === $today);
                    $hari     = $days_id[date('w', strtotime($row['tanggal']))];
                ?>
                <tr class="<?= $is_today ? 'row-today' : '' ?>">
                    <td style="font-family:'Space Mono',monospace;font-size:0.8rem;">
                        <?= $is_today ? '<span class="today-dot"></span>' : '' ?>
                        <?= date('d M Y', strtotime($row['tanggal'])) ?>
                    </td>
                    <td style="color:var(--text-secondary);font-size:0.82rem;"><?= $hari ?></td>
                    <td>
                        <span class="shift-badge <?= $row['shift']==='Pagi' ? 'badge-pagi' : 'badge-siang' ?>">
                            <?= $row['shift']==='Pagi' ? '☀️' : '🌤' ?> <?= $row['shift'] ?>
                        </span>
                    </td>
                    <td style="font-weight:600;"><?= htmlspecialchars($row['nama']) ?></td>
                    <td style="font-size:0.75rem;color:var(--text-muted);">
                        <?= htmlspecialchars($row['role']) ?>
                    </td>
                    <td style="font-size:0.8rem;color:var(--text-secondary);">
                        <?= $row['keterangan'] ? htmlspecialchars($row['keterangan']) : '<span style="color:var(--text-muted);">—</span>' ?>
                    </td>
                    <td style="text-align:center;">
                        <div style="display:flex;gap:6px;justify-content:center;">
                            <a href="mod.php?edit=<?= $row['id_mod'] ?>&bulan=<?= $filter_bulan ?>"
                               class="btn-mod-edit">✏️ Edit</a>

                            <form method="POST" action="mod.php" style="display:inline;"
                                  onsubmit="return confirm('Hapus jadwal ini?')">
                                <input type="hidden" name="aksi"   value="hapus">
                                <input type="hidden" name="id_mod"  value="<?= $row['id_mod'] ?>">
                                <button type="submit" class="btn-mod-del">🗑</button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>

    </div>
</div>

<?php include 'layout/footer.php'; ?>