<?php

namespace App\Controllers;

use Core\Database;
use PDO;

class PegawaiUTokenController
{
    private $db;

    public function __construct()
    {
        $this->db = Database::getConnection();
    }

    public function index()
    {
        $username = $_SESSION['user']['username'] ?? null;
        if (!$username) {
            header("Location: /login");
            exit();
        }

        // Kalau ada submit form, proses upload
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['uploadstaftoken'])) {
            $this->prosesUpload();
            return; // penting supaya tidak lanjut render ulang saat proses upload
        }

        // Ambil data token untuk ditampilkan di tabel
        $stmt = $this->db->query("SELECT * FROM tb_token ORDER BY id_token DESC");
        $tokens = $stmt->fetchAll(PDO::FETCH_ASSOC);

        require __DIR__ . '/../Views/pegawai/upload_token.php';
    }

    public function prosesUpload()
    {
        ini_set('upload_tmp_dir', '/home/babunnaj/tmp');
    
        require_once __DIR__ . '/../libraries/PHPExcel/PHPExcel.php';
        require_once __DIR__ . '/../libraries/PHPExcel/IOFactory.php';
    
        try {
            if (!isset($_FILES['excelFile']) || $_FILES['excelFile']['error'] !== UPLOAD_ERR_OK) {
                $_SESSION['pesan'] = "File belum dipilih atau terjadi kesalahan saat upload.";
                header("Location: /dashboard/pegawai-uploadstaftoken");
                exit();
            }
    
            $excelFile = $_FILES['excelFile']['tmp_name'];
            $excelFileType = \PHPExcel_IOFactory::identify($excelFile);
            $reader = \PHPExcel_IOFactory::createReader($excelFileType);
            $objPHPExcel = $reader->load($excelFile);
    
            $sheet = $objPHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestDataRow();
            $highestColumn = $sheet->getHighestDataColumn();
    
            $insertCount = 0;
            $duplicateCount = 0;
            $duplicateInfo = [];
    
            // Loop baris mulai baris 2 (header di baris 1)
            for ($row = 2; $row <= $highestRow; $row++) {
                $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
                $token = trim($rowData[0][1] ?? '');     // Kolom B
                $kegiatan = trim($rowData[0][2] ?? '');  // Kolom C
    
                if ($token === '') continue;
    
                // Cek apakah token sudah ada
                $stmtCheck = $this->db->prepare("SELECT COUNT(*) FROM tb_token WHERE token = ?");
                $stmtCheck->execute([$token]);
                $exists = $stmtCheck->fetchColumn() > 0;
    
                if ($exists) {
                    $duplicateCount++;
                    $duplicateInfo[] = "Baris {$row} (token: {$token})";
                    continue;
                }
    
                // Insert token baru
                $stmtInsert = $this->db->prepare("INSERT INTO tb_token (token, kegiatan) VALUES (?, ?)");
                $stmtInsert->execute([$token, $kegiatan]);
                $insertCount++;
            }
    
            // Buat pesan laporan
            $msg = "Upload selesai. Berhasil: {$insertCount} data";
            if ($duplicateCount > 0) {
                $msg .= ", Gagal: {$duplicateCount} data duplikat → " . implode('; ', $duplicateInfo);
            }
    
            $_SESSION['pesan'] = $msg;
            header("Location: /dashboard/pegawai-uploadstaftoken");
            exit();
    
        } catch (\Exception $e) {
            $_SESSION['pesan'] = "Terjadi kesalahan: " . $e->getMessage();
            header("Location: /dashboard/pegawai-uploadstaftoken");
            exit();
        }
    }

}
