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

class Kalender extends CI_Controller
{
    private $warga_id  = 0;
    private $is_admin  = false;
    private $user_id   = 0;

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('authorization');
        check_login();
        $this->load->model('Kalender_model');

        $this->user_id  = (int) $this->session->userdata('user_id');
        $this->is_admin = is_admin();

        // Cari warga_id dari tabel warga (untuk warga biasa)
        // Admin boleh tidak punya record warga — tetap bisa kelola kegiatan RT
        if ($this->user_id) {
            $w = $this->db->get_where('warga', ['user_id' => $this->user_id])->row();
            $this->warga_id = $w ? (int) $w->id : 0;
        }
    }

    // ── Halaman utama ─────────────────────────────────────────
    public function index()
    {
        $bulan = (int)($this->input->get('bulan') ?: date('n'));
        $tahun = (int)($this->input->get('tahun') ?: date('Y'));
        if ($bulan < 1)  { $bulan = 12; $tahun--; }
        if ($bulan > 12) { $bulan = 1;  $tahun++; }

        $data['kalender']     = $this->Kalender_model->get_kalender_bulanan($tahun, $bulan);
        $data['jadwal_map']   = $this->warga_id
            ? $this->Kalender_model->get_jadwal_warga($this->warga_id, $tahun, $bulan)
            : [];
        $data['kegiatan_map'] = $this->Kalender_model->get_kegiatan_rt($tahun, $bulan);
        $data['warga_id']     = $this->warga_id;
        $data['is_admin']     = $this->is_admin;
        // Admin bisa buat jadwal pribadi meski tidak punya warga_id
        $data['bisa_jadwal']  = ($this->warga_id > 0 || $this->is_admin);
        $data['bulan']        = $bulan;
        $data['tahun']        = $tahun;
        $data['title']        = 'Kalender';

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

    // ── AJAX: detail tanggal ──────────────────────────────────
    public function detail_tanggal()
    {
        $this->_json();
        $tgl = $this->input->post('tanggal');
        if (!$tgl || !$this->_valid_date($tgl)) {
            echo json_encode(['status'=>'error','msg'=>'Tanggal tidak valid']); return;
        }

        $bulan  = (int) date('n', strtotime($tgl));
        $tahun  = (int) date('Y', strtotime($tgl));
        $liburs = $this->Kalender_model->get_hari_libur($tahun, $bulan);
        $libur_nama = '';
        foreach ($liburs as $h) {
            if ($h['date'] === $tgl) { $libur_nama = $h['name']; break; }
        }

        $detail = $this->Kalender_model->get_detail_tanggal($tgl, $this->warga_id);
        echo json_encode([
            'status'   => 'ok',
            'weton'    => $detail['weton'],
            'libur'    => $libur_nama,
            'jadwal'   => $detail['jadwal'],
            'kegiatan' => $detail['kegiatan'],
        ]);
    }

    // ── AJAX: simpan/edit jadwal pribadi ─────────────────────
    public function simpan_jadwal()
    {
        $this->_json();

        // Admin yang tidak punya warga_id: buat dulu record warga sementara
        // atau izinkan dengan user_id sebagai pengganti
        $warga_id = $this->warga_id;

        if (!$warga_id && $this->is_admin) {
            // Admin pakai user_id sebagai warga_id = 0, simpan dengan flag khusus
            // Lebih simple: admin tetap bisa simpan jadwal, warga_id = 0 diizinkan untuk admin
            $warga_id = -1 * $this->user_id; // negatif = admin
        }

        if (!$warga_id && !$this->is_admin) {
            echo json_encode(['status'=>'error','msg'=>'Akun tidak teridentifikasi']); return;
        }

        $tanggal = $this->input->post('tanggal');
        $judul   = trim($this->input->post('judul') ?? '');
        $id_edit = (int) $this->input->post('id_edit');

        if (!$judul) {
            echo json_encode(['status'=>'error','msg'=>'Judul wajib diisi']); return;
        }
        if (!$id_edit && (!$tanggal || !$this->_valid_date($tanggal))) {
            echo json_encode(['status'=>'error','msg'=>'Tanggal tidak valid']); return;
        }

        $warna = $this->input->post('warna') ?: '#3b82f6';
        if (!preg_match('/^#[0-9a-fA-F]{6}$/', $warna)) $warna = '#3b82f6';

        $payload = [
            'judul'         => $this->security->xss_clean($judul),
            'deskripsi'     => $this->security->xss_clean($this->input->post('deskripsi') ?: ''),
            'warna'         => $warna,
            'waktu_mulai'   => $this->_sanitize_time($this->input->post('waktu_mulai')),
            'waktu_selesai' => $this->_sanitize_time($this->input->post('waktu_selesai')),
        ];

        // Gunakan warga_id sesungguhnya (0 untuk admin tanpa warga)
        $real_warga_id = $this->warga_id ?: 0;

        if ($id_edit > 0) {
            // Admin bisa edit jadwal siapapun, warga hanya milik sendiri
            if ($this->is_admin) {
                $this->db->where('id', $id_edit);
                $ok = $this->db->update('jadwal_warga', $payload);
            } else {
                $ok = $this->Kalender_model->update_jadwal($id_edit, $real_warga_id, $payload);
            }
            echo json_encode(['status'=>$ok?'ok':'error','msg'=>$ok?'Jadwal diperbarui':'Gagal','mode'=>'edit']);
        } else {
            $payload['warga_id'] = $real_warga_id;
            $payload['tanggal']  = $tanggal;
            $ok = $this->Kalender_model->simpan_jadwal($payload);
            echo json_encode(['status'=>$ok?'ok':'error','msg'=>$ok?'Jadwal disimpan':'Gagal','mode'=>'tambah']);
        }
    }

    public function hapus_jadwal()
    {
        $this->_json();
        $id = (int) $this->input->post('id');
        if (!$id) { echo json_encode(['status'=>'error']); return; }

        if ($this->is_admin) {
            $ok = $this->db->delete('jadwal_warga', ['id' => $id]);
        } else {
            if (!$this->warga_id) { echo json_encode(['status'=>'error']); return; }
            $ok = $this->Kalender_model->hapus_jadwal($id, $this->warga_id);
        }
        echo json_encode(['status'=>$ok?'ok':'error']);
    }

    public function toggle_selesai()
    {
        $this->_json();
        $id = (int) $this->input->post('id');
        if (!$id) { echo json_encode(['status'=>'error']); return; }

        if ($this->is_admin) {
            $row = $this->db->get_where('jadwal_warga', ['id'=>$id])->row();
            if (!$row) { echo json_encode(['status'=>'error']); return; }
            $this->db->where('id', $id);
            $ok = $this->db->update('jadwal_warga', ['is_selesai' => ($row->is_selesai ? 0 : 1)]);
        } else {
            if (!$this->warga_id) { echo json_encode(['status'=>'error']); return; }
            $ok = $this->Kalender_model->toggle_selesai($id, $this->warga_id);
        }
        echo json_encode(['status'=>$ok?'ok':'error']);
    }

    public function get_jadwal()
    {
        $this->_json();
        $id = (int) $this->input->post('id');
        if ($this->is_admin) {
            $row = $this->db->get_where('jadwal_warga', ['id'=>$id])->row();
        } else {
            $row = $this->Kalender_model->get_jadwal_by_id($id, $this->warga_id);
        }
        if (!$row) { echo json_encode(['status'=>'error']); return; }
        echo json_encode(['status'=>'ok','data'=>$row]);
    }

    // ── AJAX: kegiatan RT (admin only) ───────────────────────
    public function simpan_kegiatan()
    {
        $this->_json();
        $this->_admin_only();

        $tanggal = $this->input->post('tanggal');
        $judul   = trim($this->input->post('judul') ?? '');
        $id_edit = (int) $this->input->post('id_edit');

        if (!$judul || (!$id_edit && (!$tanggal || !$this->_valid_date($tanggal)))) {
            echo json_encode(['status'=>'error','msg'=>'Data tidak lengkap']); return;
        }

        $payload = [
            'judul'       => $this->security->xss_clean($judul),
            'deskripsi'   => $this->security->xss_clean($this->input->post('deskripsi') ?: ''),
            'waktu_mulai' => $this->_sanitize_time($this->input->post('waktu_mulai')),
            'tempat'      => $this->security->xss_clean($this->input->post('tempat') ?: ''),
        ];

        if ($id_edit > 0) {
            $ok = $this->Kalender_model->update_kegiatan($id_edit, $payload);
            echo json_encode(['status'=>$ok?'ok':'error','mode'=>'edit']);
        } else {
            $payload['tanggal']    = $tanggal;
            $payload['created_by'] = $this->user_id;
            $ok = $this->Kalender_model->simpan_kegiatan($payload);
            echo json_encode(['status'=>$ok?'ok':'error','mode'=>'tambah']);
        }
    }

    public function hapus_kegiatan()
    {
        $this->_json();
        $this->_admin_only();
        $id = (int) $this->input->post('id');
        if (!$id) { echo json_encode(['status'=>'error']); return; }
        $ok = $this->Kalender_model->hapus_kegiatan($id);
        echo json_encode(['status'=>$ok?'ok':'error']);
    }

    public function get_kegiatan()
    {
        $this->_json();
        $this->_admin_only();
        $row = $this->Kalender_model->get_kegiatan_by_id((int) $this->input->post('id'));
        if (!$row) { echo json_encode(['status'=>'error']); return; }
        echo json_encode(['status'=>'ok','data'=>$row]);
    }

    // ── Helpers ───────────────────────────────────────────────
    private function _json()   { header('Content-Type: application/json'); }

    private function _admin_only()
    {
        if (!$this->is_admin) {
            echo json_encode(['status'=>'error','msg'=>'Akses ditolak']); exit;
        }
    }

    private function _valid_date($s)
    {
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $s)) return false;
        [$y,$m,$d] = explode('-', $s);
        return checkdate((int)$m, (int)$d, (int)$y);
    }

    private function _sanitize_time($v)
    {
        if (!$v) return null;
        return preg_match('/^\d{2}:\d{2}(:\d{2})?$/', $v) ? $v : null;
    }
}