<?php

$judul = "Import Checklist";
$menu  = "checklist";

include 'layout/header.php';

/* ==========================
   HANDLE IMPORT
========================== */

if(isset($_POST['import'])){

    if(!isset($_FILES['filecsv']) || $_FILES['filecsv']['error'] != 0){
        $msg_error = "File gagal diupload.";
    } else {

        $ext = strtolower(pathinfo($_FILES['filecsv']['name'], PATHINFO_EXTENSION));

        if($ext !== 'csv'){
            $msg_error = "File harus berformat .csv";
        } elseif(($handle = fopen($_FILES['filecsv']['tmp_name'], "r")) !== FALSE){

            $sukses  = 0;
            $gagal   = 0;
            $skipped = 0;

            /* Lewati header */
            fgetcsv($handle);

            while(($data = fgetcsv($handle, 2000, ",")) !== FALSE){

                /* Skip baris kosong */
                if(count(array_filter(array_map('trim', $data))) === 0) continue;

                /* Minimal 5 kolom */
                if(count($data) < 5){
                    $skipped++;
                    continue;
                }

                $job_list        = mysqli_real_escape_string($conn, trim($data[0]));
                $job_desc        = mysqli_real_escape_string($conn, trim($data[1]));
                $waktu           = mysqli_real_escape_string($conn, trim($data[2]));
                $jenis_raw       = trim($data[3]);
                $jabatan_raw     = trim($data[4]);

                /* Validasi field wajib */
                if(empty($job_list)){
                    $skipped++;
                    continue;
                }

                /* Normalisasi jenis */
                $jenis_map = [
                    'daily'   => 'Daily',
                    'weekly'  => 'Weekly',
                    'monthly' => 'Monthly',
                ];
                $jenis = $jenis_map[strtolower($jenis_raw)] ?? null;

                if(!$jenis){
                    $skipped++;
                    continue;
                }

                /* Parse jabatan — bisa satu atau beberapa dipisah koma */
                $jabatan_list = array_filter(
                    array_map('trim', explode(',', $jabatan_raw))
                );

                if(empty($jabatan_list)){
                    $skipped++;
                    continue;
                }

                /* Gabungan jabatan untuk kolom jabatan di checklist_master */
                $jabatan_gabung = mysqli_real_escape_string($conn,
                    implode(',', $jabatan_list)
                );

                /* ── Insert checklist_master ── */
                $q_master = mysqli_query($conn,"
                    INSERT INTO checklist_master
                        (job_list, job_desc, waktu, jenis, jabatan, status, created_at)
                    VALUES
                        ('$job_list','$job_desc','$waktu','$jenis','$jabatan_gabung','aktif',NOW())
                ");

                if(!$q_master){
                    $gagal++;
                    continue;
                }

                $id_checklist = mysqli_insert_id($conn);

                /* ── Insert checklist_pic — satu baris per jabatan ── */
                $pic_ok = true;
                foreach($jabatan_list as $jab){
                    $jab_esc = mysqli_real_escape_string($conn, $jab);

                    $q_pic = mysqli_query($conn,"
                        INSERT INTO checklist_pic
                            (id_checklist, jabatan, created_at)
                        VALUES
                            ('$id_checklist','$jab_esc',NOW())
                    ");

                    if(!$q_pic){
                        $pic_ok = false;
                    }
                }

                if($pic_ok){
                    $sukses++;
                } else {
                    $gagal++;
                }
            }

            fclose($handle);

            $msg_sukses = "Import selesai: <strong>$sukses</strong> checklist berhasil ditambahkan"
                . ($gagal   > 0 ? ", <strong>$gagal</strong> gagal" : "")
                . ($skipped > 0 ? ", <strong>$skipped</strong> baris dilewati" : "")
                . ".";

        } else {
            $msg_error = "File CSV tidak dapat dibaca.";
        }
    }
}

include 'layout/sidebar.php';
?>

<style>

.imp-wrapper {
    padding: 28px 28px 56px;
    max-width: 860px;
    margin: 0 auto;
    font-family: 'DM Sans', 'Inter', sans-serif;
}

.imp-page-head {
    display: flex;
    align-items: center;
    gap: 14px;
    margin-bottom: 28px;
    padding-bottom: 18px;
    border-bottom: 2px solid var(--green-100);
}

.imp-page-head h1 {
    font-size: 1.3rem;
    font-weight: 800;
    color: var(--text-dark);
    letter-spacing: -0.02em;
    margin: 0 0 3px;
}

.imp-page-head p {
    font-size: 0.76rem;
    color: var(--text-muted);
    margin: 0;
}

.back-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #ffffff;
    border: 1.5px solid var(--green-100);
    border-radius: 9px;
    padding: 7px 14px;
    font-size: 0.82rem;
    font-weight: 600;
    color: var(--text-soft);
    text-decoration: none;
    transition: all 0.18s;
    white-space: nowrap;
    flex-shrink: 0;
}

.back-btn:hover {
    background: var(--green-50);
    border-color: var(--green-300);
    color: var(--green-700);
}

/* ── Cards ── */
.imp-card {
    background: #ffffff;
    border: 1.5px solid var(--green-100);
    border-radius: 16px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 20px;
    overflow: hidden;
    animation: fadeUp 0.38s ease both;
}

.imp-card:nth-child(3) { animation-delay: 0.06s; }
.imp-card:nth-child(4) { animation-delay: 0.12s; }

.imp-card-header {
    padding: 14px 22px;
    background: linear-gradient(135deg, #f0fdf4, #e8faf1);
    border-bottom: 1.5px solid var(--green-100);
    font-size: 0.88rem;
    font-weight: 700;
    color: var(--text-dark);
}

.imp-card-body { padding: 22px; }

/* ── Alerts ── */
.alert {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 14px 18px;
    border-radius: 12px;
    font-size: 0.85rem;
    margin-bottom: 20px;
    line-height: 1.6;
}

.alert-success { background: #f0fdf4; border: 1.5px solid #bbf7d0; color: #166534; }
.alert-error   { background: #fef2f2; border: 1.5px solid #fecaca; color: #dc2626; }

/* ── Format table ── */
.format-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.8rem;
    margin-bottom: 18px;
}

.format-table th {
    background: #f0fdf4;
    color: var(--green-700);
    padding: 9px 14px;
    text-align: left;
    font-weight: 700;
    font-size: 0.71rem;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    border-bottom: 2px solid var(--green-100);
}

.format-table td {
    padding: 9px 14px;
    border-bottom: 1px solid #f0fdf4;
    color: var(--text-dark);
    vertical-align: top;
}

.format-table tr:last-child td { border-bottom: none; }
.format-table tr:hover td { background: #f8fffe; }

.format-table td code {
    background: #dcfce7;
    color: #166534;
    padding: 2px 7px;
    border-radius: 5px;
    font-size: 0.74rem;
    font-family: 'Space Mono', monospace;
}

.req-mark { color: #dc2626; font-weight: 700; font-size: 0.75rem; }

/* ── CSV Preview ── */
.csv-preview-wrap {
    background: var(--green-50);
    border: 1.5px solid var(--green-100);
    border-radius: 12px;
    padding: 16px 18px;
    margin-bottom: 16px;
}

.csv-preview-wrap h6 {
    font-size: 0.75rem;
    font-weight: 700;
    color: var(--green-700);
    letter-spacing: 0.07em;
    text-transform: uppercase;
    margin: 0 0 10px;
}

.csv-preview {
    background: #0f2018;
    border-radius: 9px;
    padding: 14px 16px;
    font-family: 'Space Mono', monospace;
    font-size: 0.73rem;
    line-height: 1.9;
    overflow-x: auto;
}

.csv-header { color: #4ade80; font-weight: 700; display: block; }
.csv-row    { color: #86efac; display: block; }

/* ── Rules ── */
.rules-list {
    list-style: none;
    padding: 0; margin: 0;
}

.rules-list li {
    display: flex;
    align-items: flex-start;
    gap: 9px;
    font-size: 0.82rem;
    color: var(--text-soft);
    padding: 7px 0;
    border-bottom: 1px solid #f0fdf4;
    line-height: 1.5;
}

.rules-list li:last-child { border-bottom: none; }

.rule-dot {
    width: 20px; height: 20px;
    border-radius: 50%;
    background: #dcfce7;
    border: 1px solid #bbf7d0;
    display: flex; align-items: center; justify-content: center;
    font-size: 10px;
    flex-shrink: 0;
    margin-top: 1px;
}

/* ── DB Schema info ── */
.schema-info {
    display: flex;
    gap: 12px;
    margin-bottom: 18px;
    flex-wrap: wrap;
}

.schema-box {
    flex: 1;
    min-width: 200px;
    background: var(--green-50);
    border: 1.5px solid var(--green-100);
    border-radius: 10px;
    padding: 12px 14px;
}

.schema-box h6 {
    font-size: 0.72rem;
    font-weight: 700;
    color: var(--green-700);
    letter-spacing: 0.07em;
    text-transform: uppercase;
    margin: 0 0 8px;
}

.schema-box ul {
    list-style: none;
    padding: 0; margin: 0;
}

.schema-box ul li {
    font-size: 0.76rem;
    font-family: 'Space Mono', monospace;
    color: var(--text-soft);
    padding: 2px 0;
}

.schema-box ul li span {
    color: var(--green-700);
    font-weight: 700;
}

/* ── Upload zone ── */
.upload-zone {
    border: 2px dashed var(--green-200);
    border-radius: 14px;
    padding: 36px 24px;
    text-align: center;
    background: var(--green-50);
    cursor: pointer;
    transition: all 0.22s;
    position: relative;
    margin-bottom: 20px;
}

.upload-zone:hover,
.upload-zone.drag-over {
    border-color: var(--green-500);
    background: #dcfce7;
}

.upload-zone input[type="file"] {
    position: absolute;
    inset: 0;
    opacity: 0;
    cursor: pointer;
    width: 100%;
    height: 100%;
}

.upload-icon-big { font-size: 40px; display: block; margin-bottom: 10px; }

.upload-text {
    font-size: 0.92rem;
    font-weight: 700;
    color: var(--text-dark);
    margin-bottom: 4px;
}

.upload-sub { font-size: 0.76rem; color: var(--text-muted); }

.upload-filename {
    margin-top: 12px;
    font-size: 0.78rem;
    color: var(--green-700);
    font-family: 'Space Mono', monospace;
    font-weight: 600;
    min-height: 20px;
}

/* ── Buttons ── */
.btn-import {
    width: 100%;
    height: 52px;
    border: none;
    border-radius: 12px;
    background: linear-gradient(135deg, var(--green-600), var(--green-400));
    color: #fff;
    font-family: 'DM Sans', sans-serif;
    font-size: 0.95rem;
    font-weight: 700;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    box-shadow: 0 4px 16px rgba(34,197,94,0.28);
    transition: opacity 0.2s, transform 0.18s;
}

.btn-import:hover  { opacity: 0.9; transform: translateY(-1px); }
.btn-import:active { transform: translateY(1px); }

.btn-template {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #ffffff;
    border: 1.5px solid var(--green-200);
    border-radius: 8px;
    padding: 7px 16px;
    font-size: 0.8rem;
    font-weight: 600;
    color: var(--green-700);
    cursor: pointer;
    transition: all 0.18s;
    margin-top: 10px;
    font-family: 'DM Sans', sans-serif;
}

.btn-template:hover {
    background: var(--green-50);
    border-color: var(--green-400);
}

@keyframes fadeUp {
    from { opacity: 0; transform: translateY(12px); }
    to   { opacity: 1; transform: translateY(0); }
}

</style>

<div class="imp-wrapper">

    <!-- Page head -->
    <div class="imp-page-head">
        <a href="checklist.php" class="back-btn">← Kembali</a>
        <div>
            <h1>📥 Import Checklist CSV</h1>
            <p>Tambah checklist secara massal via file CSV</p>
        </div>
    </div>

    <!-- Alert hasil -->
    <?php if(isset($msg_sukses)): ?>
    <div class="alert alert-success">
        <span style="font-size:20px;">✅</span>
        <div><?= $msg_sukses ?> <a href="checklist.php" style="color:var(--green-700);font-weight:700;">Lihat checklist →</a></div>
    </div>
    <?php endif; ?>

    <?php if(isset($msg_error)): ?>
    <div class="alert alert-error">
        <span style="font-size:20px;">❌</span>
        <div><?= htmlspecialchars($msg_error) ?></div>
    </div>
    <?php endif; ?>

    <!-- Upload form -->
    <div class="imp-card">
        <div class="imp-card-header">⬆️ Upload File CSV</div>
        <div class="imp-card-body">

            <form method="POST" enctype="multipart/form-data" id="import-form">

                <div class="upload-zone" id="upload-zone">
                    <input type="file" name="filecsv" accept=".csv"
                           required id="file-input"
                           onchange="showFileName(this)">
                    <span class="upload-icon-big">📂</span>
                    <div class="upload-text">Klik atau seret file CSV ke sini</div>
                    <div class="upload-sub">Hanya file .csv yang diterima</div>
                    <div class="upload-filename" id="file-name"></div>
                </div>

                <button type="submit" name="import" class="btn-import">
                    ⬆️ Mulai Import Checklist
                </button>

            </form>

        </div>
    </div>

</div>

<script>
function showFileName(input) {
    const el   = document.getElementById('file-name');
    const zone = document.getElementById('upload-zone');
    if(input.files && input.files[0]) {
        const f = input.files[0];
        el.textContent        = '📎 ' + f.name + ' (' + (f.size/1024).toFixed(1) + ' KB)';
        zone.style.borderColor = '#22c55e';
        zone.style.background  = '#dcfce7';
    }
}

const zone = document.getElementById('upload-zone');
if(zone) {
    zone.addEventListener('dragover',  e => { e.preventDefault(); zone.classList.add('drag-over'); });
    zone.addEventListener('dragleave', ()  => zone.classList.remove('drag-over'));
    zone.addEventListener('drop', e => {
        e.preventDefault();
        zone.classList.remove('drag-over');
        const fi = document.getElementById('file-input');
        fi.files = e.dataTransfer.files;
        showFileName(fi);
    });
}

function downloadTemplate() {
    const rows = [
        'job_list,job_desc,waktu,jenis,jabatan',
        'Cek Gudang,ASSET HANDLING,Pagi,Daily,Store_Manager',
        'Review Absensi Karyawan,HR HANDLING,Pagi,Daily,kadiv_ops',
        '"Monitoring Omzet Harian","SALES MONITORING",Sore,Daily,"Store_Manager,kadiv_ops"',
        '"Evaluasi Pelayanan Customer","SERVICE QUALITY",Sore,Monthly,"Store_Manager,kadiv_ops,kadiv_cs"',
    ];
    const blob = new Blob([rows.join('\n')], { type: 'text/csv' });
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement('a');
    a.href     = url;
    a.download = 'template_checklist.csv';
    a.click();
    URL.revokeObjectURL(url);
}

document.getElementById('import-form').addEventListener('submit', function(e) {
    const fi = document.getElementById('file-input');
    if(!fi.files || fi.files.length === 0) {
        e.preventDefault();
        alert('Pilih file CSV terlebih dahulu.');
        return;
    }
    if(!confirm('Yakin ingin mengimport checklist dari file ini?')) {
        e.preventDefault();
    }
});
</script>

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