<?php
namespace App\Controllers;

use Core\Controller;
use Core\Database;
use App\Models\NilaiModel;

class UploadNilaiController extends Controller
{
    protected $nilaiModel;
    protected $pdo;

    public function __construct()
    {
        if (session_status() === PHP_SESSION_NONE) session_start();

        $this->pdo = Database::getConnection();
        $this->nilaiModel = new NilaiModel($this->pdo);
    }

    public function index()
    {
        require_once __DIR__ . '/../Views/pegawai/upload_nilai.php';
    }

    public function upload()
    {
        try {
            // ✅ Validasi CSRF
            if (empty($_POST['csrf_token']) || $_POST['csrf_token'] !== ($_SESSION['csrf_token'] ?? '')) {
                $_SESSION['pesan'] = 'Token CSRF tidak valid.';
                header('Location: /dashboard/pegawai-up_nilai');
                exit;
            }

            // ✅ Validasi File
            if (!isset($_FILES['excelFile']) || $_FILES['excelFile']['error'] !== UPLOAD_ERR_OK) {
                $_SESSION['pesan'] = 'File tidak ditemukan.';
                header('Location: /dashboard/pegawai-up_nilai');
                exit;
            }

            $fileTmp = $_FILES['excelFile']['tmp_name'];
            $fileName = $_FILES['excelFile']['name'];
            $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

            if (!in_array($ext, ['xls', 'xlsx'])) {
                $_SESSION['pesan'] = 'Format file harus .xls atau .xlsx';
                header('Location: /dashboard/pegawai-up_nilai');
                exit;
            }

            if ($_FILES['excelFile']['size'] > 5 * 1024 * 1024) {
                $_SESSION['pesan'] = 'Ukuran file terlalu besar (maks 5MB).';
                header('Location: /dashboard/pegawai-up_nilai');
                exit;
            }

            // ✅ Load Library PHPExcel
            require_once __DIR__ . '/../../vendor/phpoffice/phpexcel/Classes/PHPExcel.php';
            require_once __DIR__ . '/../../vendor/phpoffice/phpexcel/Classes/PHPExcel/IOFactory.php';

            // ✅ Load File Excel
            $excelType = \PHPExcel_IOFactory::identify($fileTmp);
            $reader = \PHPExcel_IOFactory::createReader($excelType);
            $spreadsheet = $reader->load($fileTmp);
            $sheet = $spreadsheet->getSheet(0);
            $highestRow = $sheet->getHighestDataRow();
            $highestColumn = $sheet->getHighestDataColumn();

            // ✅ Mulai transaksi
            $this->pdo->beginTransaction();

            $berhasil = [];
            $gagal = [];

            for ($row = 2; $row <= $highestRow; $row++) {
                $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);

                if (empty($rowData) || empty($rowData[0][0])) continue;

                $nim = trim($rowData[0][1] ?? '');
                $kode_mk = trim($rowData[0][2] ?? '');
                $smt = trim($rowData[0][5] ?? '');
                $angka = trim($rowData[0][6] ?? '');
                $mutu = trim($rowData[0][7] ?? '');
                $bobot = trim($rowData[0][8] ?? '');
                $sks_x_bobot = trim($rowData[0][9] ?? '');
                $status = trim($rowData[0][10] ?? '');

                if (empty($nim) || empty($kode_mk) || !is_numeric($angka)) {
                    $gagal[] = "Row $row: Data tidak valid (NIM/Kode MK/Angka kosong)";
                    continue;
                }

                try {
                    $this->nilaiModel->upsertNilai([
                        'nim' => $nim,
                        'kode_mk' => $kode_mk,
                        'smt' => $smt,
                        'nilai' => (float)$angka,
                        'mutu' => $mutu,
                        'bobot' => $bobot,
                        'sks_x_bobot' => $sks_x_bobot,
                        'accept' => $status
                    ]);
                    $berhasil[] = "Row $row: $nim - $kode_mk";
                } catch (\Exception $e) {
                    $gagal[] = "Row $row: " . $e->getMessage();
                }
            }

            $this->pdo->commit();

            // ✅ Buat pesan hasil upload
            $_SESSION['pesan'] = "
                <strong>Proses Upload Selesai</strong><br>
                ✅ Berhasil update: " . count($berhasil) . " data.<br>
                ❌ Gagal update: " . count($gagal) . " data.<br><br>
                <u>Detail Berhasil:</u><br>" . implode('<br>', $berhasil) . "<br><br>
                <u>Detail Gagal:</u><br>" . implode('<br>', $gagal);

            header('Location: /dashboard/pegawai-up_nilai');
            exit;

        } catch (\Exception $e) {
            if ($this->pdo->inTransaction()) $this->pdo->rollBack();
            error_log('Upload Nilai Error: ' . $e->getMessage());
            $_SESSION['pesan'] = 'Terjadi kesalahan saat upload.';
            header('Location: /dashboard/pegawai-up_nilai');
            exit;
        }
    }

    public function downloadTemplate()
    {
        $file = __DIR__ . '/../../public/template_excel/Format_Upload_nilai.xlsx';
    
        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment; filename="Format_Upload_nilai.xlsx"');
            header('Content-Length: ' . filesize($file));
            readfile($file);
            exit;
        } else {
            http_response_code(404);
            echo "File tidak ditemukan.";
        }
    }

}
