<?php

namespace App\Http\Controllers;

use App\Models\Mahasiswa;
use Illuminate\Http\Request;


class MahasiswaController extends Controller
{
    public function index()
    {
        $mahasiswa = Mahasiswa::all();
        return view('mahasiswa.index', compact('mahasiswa'));
    }

    public function create()
    {
        return view('mahasiswa.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'nim' => 'required|unique:mahasiswa,nim',
            'nama' => 'required',
            'alamat' => 'required',
            'bagian' => 'required',
        ]);

        Mahasiswa::create($request->all());

        return redirect()->route('mahasiswa.index')->with('success', 'Data mahasiswa berhasil ditambahkan.');
    }

    public function edit(Mahasiswa $mahasiswa)
    {
        return view('mahasiswa.edit', compact('mahasiswa'));
    }

    public function update(Request $request, Mahasiswa $mahasiswa)
    {
        $request->validate([
            'nama' => 'required',
            'alamat' => 'required',
            'bagian' => 'required',
        ]);

        $mahasiswa->update($request->all());

        return redirect()->route('mahasiswa.index')->with('success', 'Data mahasiswa berhasil diperbarui.');
    }

    public function destroy(Mahasiswa $mahasiswa)
    {
        $mahasiswa->delete();
        return redirect()->route('mahasiswa.index')->with('success', 'Data mahasiswa berhasil dihapus.');
    }

    public function export()
    {
        $headers = [
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=mahasiswa.csv",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        ];

        $items = Mahasiswa::all();
        $columns = ['NIM', 'Nama', 'Alamat', 'Bagian', 'Jurusan', 'Jenjang Program', 'Judul Skripsi'];

        $callback = function() use($items, $columns) {
            $file = fopen('php://output', 'w');
            fputcsv($file, $columns);

            foreach ($items as $item) {
                fputcsv($file, [
                    $item->nim, 
                    $item->nama, 
                    $item->alamat, 
                    $item->bagian, 
                    $item->jurusan, 
                    $item->jenjang_program,
                    $item->judul_skripsi
                ]);
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }


    public function import(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:csv,txt'
        ]);

        $file = $request->file('file');
        $handle = fopen($file->getRealPath(), "r");
        $header = fgetcsv($handle); // skip header

        while (($data = fgetcsv($handle)) !== FALSE) {
            Mahasiswa::updateOrCreate(
                ['nim' => $data[0]],
                [
                    'nama' => $data[1],
                    'alamat' => $data[2],
                    'bagian' => $data[3],
                    'jurusan' => $data[4],
                    'jenjang_program' => $data[5],
                    'judul_skripsi' => $data[6] ?? null,
                ]
            );
        }

        fclose($handle);

        return back()->with('success', 'Data mahasiswa berhasil diimpor.');
    }


    public function downloadTemplate()
    {
        $headers = ['NIM', 'Nama', 'Alamat', 'Bagian', 'Jurusan', 'Jenjang Program', 'Judul Skripsi'];
        $callback = function() use ($headers) {
            $file = fopen('php://output', 'w');
            fputcsv($file, $headers, "\t");
            fclose($file);
        };
        return response()->stream($callback, 200, [
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=template_mahasiswa.csv",
        ]);
    }

    public function getDetail(string $nim)
    {
        $mahasiswa = Mahasiswa::find($nim);
        if ($mahasiswa) {
            return response()->json($mahasiswa);
        }
        return response()->json(['error' => 'Not found'], 404);
    }
}
