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

class Reset extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        if(!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
        
        // Hanya admin yang bisa akses
        $role = $this->session->userdata('role');
        if(!in_array($role, ['admin', 'ketua_rt'])) {
            $this->session->set_flashdata('error', 'Akses ditolak. Hanya Admin atau Ketua RT yang dapat mereset data.');
            redirect('dashboard');
        }

        $this->load->model('Reset_model');
        $this->load->model('User_model');
        $this->load->library('form_validation');
    }

    public function index() {
        $data['title'] = 'Reset Data Sistem';
        
        // Hitung statistik data
        $data['statistik'] = [
            'warga' => $this->db->count_all('warga'),
            'user_non_admin' => $this->Reset_model->count_user_non_admin(),
            'kk' => $this->db->count_all('kartu_keluarga'),
            'tabungan' => $this->db->count_all('tabungan'),
            'pinjaman' => $this->db->count_all('pinjaman'),
            'pengajuan_pinjaman' => $this->db->count_all('pengajuan_pinjaman'),
            'transaksi_kas' => $this->db->count_all('kas_rt'),
            'master_kas' => $this->db->count_all('master_kas'),
            'pembayaran_iuran' => $this->db->count_all('pembayaran_iuran'),
            'inventaris' => $this->db->count_all('inventaris'),
            'arisan' => $this->db->count_all('arisan'),
            'pengumuman' => $this->db->count_all('pengumuman'),
            'pengaduan' => $this->db->count_all('pengaduan'),
            'permohonan_surat' => $this->db->count_all('permohonan_surat'),
            'log_aktivitas' => $this->db->count_all('log_aktivitas'),
        ];

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

    /**
     * Reset Data Warga dan User (kecuali Admin)
     */
    public function reset_warga_user() {
        $this->_validate_password();
        
        $result = $this->Reset_model->reset_warga_dan_user();
        
        if($result['success']) {
            $this->session->set_flashdata('success', 
                "Berhasil mereset data Warga dan User!\n" .
                "- {$result['warga_deleted']} data warga dihapus\n" .
                "- {$result['kk_deleted']} data KK dihapus\n" .
                "- {$result['user_deleted']} user non-admin dihapus\n" .
                "- {$result['users_preserved']} akun admin/petugas dilindungi"
            );
        } else {
            $this->session->set_flashdata('error', 'Gagal mereset data: ' . $result['message']);
        }
        
        redirect('reset');
    }

    /**
     * Reset Data Keuangan (Tabungan, Pinjaman, Kas)
     */
    public function reset_keuangan() {
        $this->_validate_password();
        
        $result = $this->Reset_model->reset_keuangan();
        
        if($result['success']) {
            $this->session->set_flashdata('success', 
                "Berhasil mereset data Keuangan!\n" .
                "- {$result['tabungan_deleted']} data tabungan dihapus\n" .
                "- {$result['transaksi_tabungan_deleted']} transaksi tabungan dihapus\n" .
                "- {$result['pinjaman_deleted']} data pinjaman dihapus\n" .
                "- {$result['pengajuan_pinjaman_deleted']} pengajuan pinjaman dihapus\n" .
                "- {$result['angsuran_deleted']} angsuran dihapus\n" .
                "- {$result['kas_deleted']} transaksi kas dihapus\n" .
                "Saldo Master Kas direset ke saldo awal masing-masing."
            );
        } else {
            $this->session->set_flashdata('error', 'Gagal mereset data: ' . $result['message']);
        }
        
        redirect('reset');
    }

    /**
     * Reset Data Iuran dan Pembayaran
     */
    public function reset_iuran() {
        $this->_validate_password();
        
        $result = $this->Reset_model->reset_iuran();
        
        if($result['success']) {
            $this->session->set_flashdata('success', 
                "Berhasil mereset data Iuran!\n" .
                "- {$result['pembayaran_iuran_deleted']} pembayaran iuran dihapus\n" .
                "- {$result['pengajuan_bayar_deleted']} pengajuan bayar angsuran dihapus\n" .
                "- {$result['pembayaran_pending_deleted']} pembayaran pending dihapus\n" .
                "- {$result['riwayat_pembayaran_pinjaman_deleted']} riwayat pembayaran pinjaman dihapus"
            );
        } else {
            $this->session->set_flashdata('error', 'Gagal mereset data: ' . $result['message']);
        }
        
        redirect('reset');
    }

    /**
     * Reset Data Inventaris
     */
    public function reset_inventaris() {
        $this->_validate_password();
        
        $result = $this->Reset_model->reset_inventaris();
        
        if($result['success']) {
            $this->session->set_flashdata('success', 
                "Berhasil mereset data Inventaris!\n" .
                "- {$result['inventaris_deleted']} item inventaris dihapus\n" .
                "- {$result['gallery_deleted']} foto gallery dihapus\n" .
                "- {$result['rencana_pembelian_deleted']} rencana pembelian dihapus"
            );
        } else {
            $this->session->set_flashdata('error', 'Gagal mereset data: ' . $result['message']);
        }
        
        redirect('reset');
    }

    /**
     * Reset Data Arisan
     */
    public function reset_arisan() {
        $this->_validate_password();
        
        $result = $this->Reset_model->reset_arisan();
        
        if($result['success']) {
            $this->session->set_flashdata('success', 
                "Berhasil mereset data Arisan!\n" .
                "- {$result['arisan_deleted']} data arisan dihapus\n" .
                "- {$result['peserta_deleted']} peserta arisan dihapus\n" .
                "- {$result['pertemuan_deleted']} pertemuan arisan dihapus\n" .
                "- {$result['iuran_deleted']} iuran arisan dihapus\n" .
                "- {$result['riwayat_pemenang_deleted']} riwayat pemenang dihapus"
            );
        } else {
            $this->session->set_flashdata('error', 'Gagal mereset data: ' . $result['message']);
        }
        
        redirect('reset');
    }

    /**
     * Reset Data Administrasi (Surat, Pengumuman, Pengaduan)
     */
    public function reset_administrasi() {
        $this->_validate_password();
        
        $result = $this->Reset_model->reset_administrasi();
        
        if($result['success']) {
            $this->session->set_flashdata('success', 
                "Berhasil mereset data Administrasi!\n" .
                "- {$result['permohonan_surat_deleted']} permohonan surat dihapus\n" .
                "- {$result['pengumuman_deleted']} pengumuman dihapus\n" .
                "- {$result['pengaduan_deleted']} pengaduan dihapus"
            );
        } else {
            $this->session->set_flashdata('error', 'Gagal mereset data: ' . $result['message']);
        }
        
        redirect('reset');
    }

    /**
     * Reset Log Aktivitas Saja
     */
    public function reset_log() {
        $this->_validate_password();
        
        $result = $this->Reset_model->reset_log();
        
        if($result['success']) {
            $this->session->set_flashdata('success', 
                "Berhasil mereset Log Aktivitas!\n" .
                "- {$result['log_deleted']} log aktivitas dihapus"
            );
        } else {
            $this->session->set_flashdata('error', 'Gagal mereset log: ' . $result['message']);
        }
        
        redirect('reset');
    }

    /**
     * RESET TOTAL - HAPUS SEMUA DATA (KECUALI ADMIN & SETTING)
     * PERINGATAN: Ini sangat berbahaya!
     */
    public function reset_total() {
        $this->_validate_password();
        
        // Extra confirmation untuk reset total
        $konfirmasi = $this->input->post('konfirmasi_total');
        if($konfirmasi !== 'RESET TOTAL DATA') {
            $this->session->set_flashdata('error', 'Konfirmasi reset total tidak valid. Ketik "RESET TOTAL DATA" dengan benar.');
            redirect('reset');
        }

        $result = $this->Reset_model->reset_total();
        
        if($result['success']) {
            $this->session->set_flashdata('success', 
                "🚨 RESET TOTAL BERHASIL! 🚨\n" .
                "Semua data telah dihapus kecuali:\n" .
                "- Akun Admin/Petugas ({$result['admin_preserved']} akun)\n" .
                "- Data Master (Jenis Iuran, Jenis Pinjaman, Jenis Surat, Master Kas)\n" .
                "- Pengaturan RT\n\n" .
                "Ringkasan penghapusan:\n" .
                "- {$result['warga_deleted']} warga\n" .
                "- {$result['kk_deleted']} KK\n" .
                "- {$result['user_deleted']} user non-admin\n" .
                "- {$result['tabungan_deleted']} tabungan\n" .
                "- {$result['pinjaman_deleted']} pinjaman\n" .
                "- {$result['kas_deleted']} transaksi kas\n" .
                "- {$result['inventaris_deleted']} inventaris\n" .
                "- {$result['arisan_deleted']} arisan\n" .
                "- {$result['pengumuman_deleted']} pengumuman\n" .
                "- {$result['pengaduan_deleted']} pengaduan\n" .
                "- {$result['log_deleted']} log aktivitas"
            );
        } else {
            $this->session->set_flashdata('error', 'Gagal mereset total: ' . $result['message']);
        }
        
        redirect('reset');
    }

    /**
     * Private method untuk validasi password admin
     */
    private function _validate_password() {
        $this->form_validation->set_rules('password_confirm', 'Password Konfirmasi', 'required');
        
        if($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', 'Password konfirmasi wajib diisi.');
            redirect('reset');
        }

        $password = $this->input->post('password_confirm');
        $user_id = $this->session->userdata('user_id');
        
        // Verifikasi password
        $user = $this->User_model->get_by_id($user_id);
        if(!$user || !password_verify($password, $user->password)) {
            $this->session->set_flashdata('error', 'Password konfirmasi salah. Reset dibatalkan untuk keamanan.');
            redirect('reset');
        }
    }
}