<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Dokumen extends CI_Controller {

    public function __construct() {
        parent::__construct();
        check_role([3]); // hanya siswa
        $this->load->model('DokumenSiswa_model');
        $this->load->library(['session','upload']);
        $this->load->helper(['url','form']);
    }

    public function index() {
        $siswaID = $this->session->userdata('siswa_id');
        $data['title'] = 'Dokumen Saya';
        $data['dokumen'] = $this->DokumenSiswa_model->get_by_siswa($siswaID);

        // load dengan template konsisten
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('templates/topbar', $data);
        $this->load->view('dashboard/dokumen_saya', $data);
        $this->load->view('templates/footer', $data);
    }

    // contoh fungsi hapus dokumen
    public function hapus($id) {
        $this->DokumenSiswa_model->delete($id);
        $this->session->set_flashdata('success', 'Dokumen berhasil dihapus');
        redirect('dokumen');
    }

    // upload dokumen
    public function upload() {
    $siswaID = $this->session->userdata('siswa_id');

    // validasi upload
    $config['upload_path']   = './uploads/siswa/';
    $config['allowed_types'] = 'jpg|png|pdf';
    $config['max_size']      = 2048; // 2MB
    $config['file_name']     = 'DOC_' . $siswaID . '_' . time();

    $this->upload->initialize($config);

    if (!$this->upload->do_upload('file_dokumen')) {
        $this->session->set_flashdata('error', $this->upload->display_errors());
        redirect('dokumen');
    }

    $fileData = $this->upload->data();

    $data = [
        'SiswaID'     => $siswaID,
        'JenisDokumen'=> $this->input->post('jenis_dokumen'),
        'FilePath'    => 'uploads/siswa/' . $fileData['file_name'],
        'UploadedAt'  => date('Y-m-d H:i:s')
    ];

    $this->DokumenSiswa_model->insert($data);

    $this->session->set_flashdata('success', 'Dokumen berhasil diupload');
    redirect('dokumen');
}

}
