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

class Jadwal extends CI_Controller {

    public function __construct() {
        parent::__construct();

        $this->load->helper('authorization');
        $this->load->library('session');
        $this->load->model('Jadwal_model');
        $this->load->model('Warga_model');

        check_login();
    }

    public function index() {
        if(cannot('jadwal', 'view')) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses ke halaman ini!');
            redirect('dashboard');
        }

        $data['title'] = 'Jadwal Kegiatan';
        
        $filters = [];
        if($this->input->get('kategori')) $filters['kategori'] = $this->input->get('kategori');
        if($this->input->get('status')) $filters['status'] = $this->input->get('status');
        
        $data['jadwal'] = $this->Jadwal_model->get_all($filters);
        $data['statistik'] = $this->Jadwal_model->get_statistik();
        $data['jadwal_hari_ini'] = $this->Jadwal_model->get_jadwal_hari_ini();

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('jadwal/index', $data);
        $this->load->view('templates/footer');
    }

    public function tambah() {
        if(cannot('jadwal', 'create')) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses untuk menambah jadwal!');
            redirect('jadwal');
        }

        $data['title'] = 'Tambah Jadwal';
        $data['warga'] = $this->Warga_model->get_all();

        if($this->input->post()) {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('nama_kegiatan', 'Nama Kegiatan', 'required');
            $this->form_validation->set_rules('kategori', 'Kategori', 'required');
            $this->form_validation->set_rules('jenis_jadwal', 'Jenis Jadwal', 'required');

            if($this->form_validation->run()) {
                $insert_data = array(
                    'nama_kegiatan' => $this->input->post('nama_kegiatan'),
                    'kategori' => $this->input->post('kategori'),
                    'deskripsi' => $this->input->post('deskripsi'),
                    'jenis_jadwal' => $this->input->post('jenis_jadwal'),
                    'lokasi' => $this->input->post('lokasi'),
                    'penanggung_jawab_id' => $this->input->post('penanggung_jawab_id') ?: null,
                    'status' => 'aktif',
                    'created_by' => $this->session->userdata('user_id')
                );

                // Set tanggal/waktu berdasarkan jenis jadwal
                $jenis = $this->input->post('jenis_jadwal');
                if($jenis == 'harian') {
                    $insert_data['waktu_mulai'] = $this->input->post('waktu_mulai');
                    $insert_data['waktu_selesai'] = $this->input->post('waktu_selesai');
                } elseif($jenis == 'mingguan') {
                    $insert_data['hari'] = $this->input->post('hari');
                    $insert_data['waktu_mulai'] = $this->input->post('waktu_mulai');
                } elseif($jenis == 'tanggal_tentu') {
                    $insert_data['tanggal_mulai'] = $this->input->post('tanggal_mulai');
                    $insert_data['waktu_mulai'] = $this->input->post('waktu_mulai');
                } elseif($jenis == 'range_tanggal') {
                    $insert_data['tanggal_mulai'] = $this->input->post('tanggal_mulai');
                    $insert_data['tanggal_selesai'] = $this->input->post('tanggal_selesai');
                    $insert_data['waktu_mulai'] = $this->input->post('waktu_mulai');
                }

                if($this->Jadwal_model->insert($insert_data)) {
                    $jadwal_id = $this->db->insert_id();
                    
                    // Simpan petugas/kelompok jika ada
                    $this->_simpan_petugas($jadwal_id);
                    
                    $this->session->set_flashdata('success', 'Jadwal berhasil ditambahkan!');
                    redirect('jadwal');
                } else {
                    $this->session->set_flashdata('error', 'Gagal menambahkan jadwal!');
                }
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('jadwal/form', $data);
        $this->load->view('templates/footer');
    }

    public function edit($id) {
        if(cannot('jadwal', 'edit')) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses untuk mengedit jadwal!');
            redirect('jadwal');
        }

        $data['title'] = 'Edit Jadwal';
        $data['j'] = $this->Jadwal_model->get_by_id($id);
        $data['warga'] = $this->Warga_model->get_all();
        $data['petugas'] = $this->Jadwal_model->get_petugas_by_jadwal($id);

        if(!$data['j']) {
            $this->session->set_flashdata('error', 'Jadwal tidak ditemukan!');
            redirect('jadwal');
        }

        if($this->input->post()) {
            $update_data = array(
                'nama_kegiatan' => $this->input->post('nama_kegiatan'),
                'kategori' => $this->input->post('kategori'),
                'deskripsi' => $this->input->post('deskripsi'),
                'jenis_jadwal' => $this->input->post('jenis_jadwal'),
                'lokasi' => $this->input->post('lokasi'),
                'penanggung_jawab_id' => $this->input->post('penanggung_jawab_id') ?: null,
                'status' => $this->input->post('status')
            );

            $jenis = $this->input->post('jenis_jadwal');
            if($jenis == 'harian') {
                $update_data['waktu_mulai'] = $this->input->post('waktu_mulai');
                $update_data['waktu_selesai'] = $this->input->post('waktu_selesai');
                $update_data['hari'] = null;
                $update_data['tanggal_mulai'] = null;
                $update_data['tanggal_selesai'] = null;
            } elseif($jenis == 'mingguan') {
                $update_data['hari'] = $this->input->post('hari');
                $update_data['waktu_mulai'] = $this->input->post('waktu_mulai');
                $update_data['waktu_selesai'] = null;
                $update_data['tanggal_mulai'] = null;
                $update_data['tanggal_selesai'] = null;
            } elseif($jenis == 'tanggal_tentu') {
                $update_data['tanggal_mulai'] = $this->input->post('tanggal_mulai');
                $update_data['waktu_mulai'] = $this->input->post('waktu_mulai');
                $update_data['hari'] = null;
                $update_data['tanggal_selesai'] = null;
            } elseif($jenis == 'range_tanggal') {
                $update_data['tanggal_mulai'] = $this->input->post('tanggal_mulai');
                $update_data['tanggal_selesai'] = $this->input->post('tanggal_selesai');
                $update_data['waktu_mulai'] = $this->input->post('waktu_mulai');
                $update_data['hari'] = null;
            }

            if($this->Jadwal_model->update($id, $update_data)) {
                // Update petugas
                $this->Jadwal_model->delete_petugas($id);
                $this->_simpan_petugas($id);
                
                $this->session->set_flashdata('success', 'Jadwal berhasil diupdate!');
                redirect('jadwal');
            } else {
                $this->session->set_flashdata('error', 'Gagal mengupdate jadwal!');
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('jadwal/form', $data);
        $this->load->view('templates/footer');
    }

    public function detail($id) {
        if(cannot('jadwal', 'view')) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses!');
            redirect('dashboard');
        }

        $data['title'] = 'Detail Jadwal';
        $data['j'] = $this->Jadwal_model->get_by_id($id);
        $data['petugas'] = $this->Jadwal_model->get_petugas_by_jadwal($id);

        if(!$data['j']) {
            $this->session->set_flashdata('error', 'Jadwal tidak ditemukan!');
            redirect('jadwal');
        }

        // Kelompokkan petugas
        $data['kelompok'] = array();
        foreach($data['petugas'] as $p) {
            $key = $p->kelompok ?: 'Tanpa Kelompok';
            if(!isset($data['kelompok'][$key])) {
                $data['kelompok'][$key] = array();
            }
            $data['kelompok'][$key][] = $p;
        }

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('jadwal/detail', $data);
        $this->load->view('templates/footer');
    }

    public function hapus($id) {
        if(cannot('jadwal', 'delete')) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses untuk menghapus jadwal!');
            redirect('jadwal');
        }
        
        if($this->Jadwal_model->delete($id)) {
            $this->session->set_flashdata('success', 'Jadwal berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus jadwal!');
        }
        redirect('jadwal');
    }

    private function _simpan_petugas($jadwal_id) {
        $petugas = $this->input->post('petugas');
        $kelompok = $this->input->post('kelompok');
        
        if(!empty($petugas) && is_array($petugas)) {
            foreach($petugas as $i => $warga_id) {
                if(!empty($warga_id)) {
                    $this->Jadwal_model->insert_petugas(array(
                        'jadwal_id' => $jadwal_id,
                        'warga_id' => $warga_id,
                        'kelompok' => !empty($kelompok[$i]) ? $kelompok[$i] : null,
                        'urutan' => $i + 1
                    ));
                }
            }
        }
    }
}