<?php

namespace App\Controllers;

use App\Models\PengaturanModel;
use App\Models\UserModel;

class Pengaturan extends BaseController
{

    protected $pengaturanModel;
    protected $userModel;


    public function __construct()
    {
        $this->pengaturanModel = new PengaturanModel();
        $this->userModel       = new UserModel();
    }



    // ===============================
    // HALAMAN UTAMA
    // ===============================
    public function index()
    {

        $pengaturan = $this->pengaturanModel->first();


        if(!$pengaturan){

            $id = $this->pengaturanModel->insert([

                'nama_perpustakaan'=>'Perpustakaan',
                'nama_sekolah'=>'Nama Sekolah',

                'deskripsi'=>'',
                'alamat'=>'',
                'telepon'=>'',
                'email'=>'',
                'website'=>'',
                'logo'=>'',

                'lama_pinjam'=>7,
                'maksimal_buku'=>3,
                'denda_perhari'=>1000,

                'ukuran_kertas'=>'A4',
                'footer_cetak'=>'Terima Kasih'

            ]);


            $pengaturan = $this->pengaturanModel->find($id);

        }


        return view('pengaturan/index',[

            'title'=>'Pengaturan',
            'pengaturan'=>$pengaturan

        ]);

    }





    // ===============================
    // HALAMAN SEKOLAH
    // ===============================
    public function sekolah()
    {

        $pengaturan = $this->pengaturanModel->first();


        if(!$pengaturan){

            return redirect()->to('/pengaturan');

        }


        return view('pengaturan/sekolah',[

            'title'=>'Informasi Sekolah',
            'pengaturan'=>$pengaturan

        ]);

    }





    // ===============================
// SIMPAN SEKOLAH
// ===============================
public function updateSekolah()
{
    $id = $this->request->getPost('id');

    $data = [
        'nama_perpustakaan' => $this->request->getPost('nama_perpustakaan'),
        'nama_sekolah'      => $this->request->getPost('nama_sekolah'),
        'deskripsi'         => $this->request->getPost('deskripsi'),
        'alamat'            => $this->request->getPost('alamat'),
        'telepon'           => $this->request->getPost('telepon'),
        'email'             => $this->request->getPost('email'),
        'website'           => $this->request->getPost('website'),
    ];

    // Upload logo
    $logo = $this->request->getFile('logo');

    if ($logo && $logo->isValid() && !$logo->hasMoved()) {

        $folder = FCPATH . 'uploads/logo';

        if (!is_dir($folder)) {
            mkdir($folder, 0777, true);
        }

        $namaLogo = $logo->getRandomName();
        $logo->move($folder, $namaLogo);

        // Hapus logo lama
        $pengaturan = $this->pengaturanModel->find($id);

        if ($pengaturan && !empty($pengaturan['logo'])) {
            $logoLama = $folder . '/' . $pengaturan['logo'];

            if (file_exists($logoLama)) {
                unlink($logoLama);
            }
        }

        $data['logo'] = $namaLogo;
    }

    $this->pengaturanModel->update($id, $data);

    return redirect()
        ->back()
        ->with('success', 'Informasi sekolah berhasil disimpan.');
    }





    // ===============================
    // AKUN
    // ===============================
    public function akun()
    {
        $userId = session()->get('id_user');
        $user   = $this->userModel->find($userId);

        if (!$user) {
            return redirect()->to('/login')->with('error', 'Sesi tidak valid.');
        }

        return view('pengaturan/akun', [
            'title' => 'Pengaturan Akun',
            'user'  => $user,
        ]);
    }

    public function updateProfil()
    {
        $id       = $this->request->getPost('id');
        $username = $this->request->getPost('username');
        $nama     = $this->request->getPost('nama');

        // Cek username sudah dipakai user lain?
        $cek = $this->userModel->where('username', $username)->where('id !=', $id)->first();
        if ($cek) {
            return redirect()->back()->with('error', 'Username sudah digunakan oleh user lain.');
        }

        $this->userModel->update($id, [
            'username' => $username,
            'nama'     => $nama,
        ]);

        // Update session
        session()->set('username', $username);
        session()->set('nama', $nama);

        return redirect()->back()->with('success', 'Profil berhasil diperbarui.');
    }

    public function updatePassword()
    {
        $passwordLama      = $this->request->getPost('password_lama');
        $passwordBaru      = $this->request->getPost('password_baru');
        $passwordKonfirmasi = $this->request->getPost('password_konfirmasi');

        $userId = session()->get('id_user');
        $user   = $this->userModel->find($userId);

        if (!$user) {
            return redirect()->back()->with('error', 'Sesi tidak valid.');
        }

        if (!password_verify($passwordLama, $user['password'])) {
            return redirect()->back()->with('error', 'Password lama salah.');
        }

        if ($passwordBaru !== $passwordKonfirmasi) {
            return redirect()->back()->with('error', 'Password baru dan konfirmasi tidak cocok.');
        }

        if (strlen($passwordBaru) < 4) {
            return redirect()->back()->with('error', 'Password minimal 4 karakter.');
        }

        $this->userModel->update($userId, [
            'password' => password_hash($passwordBaru, PASSWORD_DEFAULT),
        ]);

        return redirect()->back()->with('success', 'Password berhasil diperbarui.');
    }





    // ===============================
    // PEMINJAMAN
    // ===============================
    public function peminjaman()
    {

        $pengaturan=$this->pengaturanModel->first();


        return view('pengaturan/peminjaman',[

            'title'=>'Aturan Peminjaman',

            'pengaturan'=>$pengaturan

        ]);

    }




    public function updatePeminjaman()
    {

        $id=$this->request->getPost('id');


        $data=[

            'lama_pinjam'=>$this->request->getPost('lama_pinjam'),

            'maksimal_buku'=>$this->request->getPost('maksimal_buku'),

            'denda_perhari'=>$this->request->getPost('denda_perhari'),

        ];


        $this->pengaturanModel->update($id,$data);


        return redirect()
        ->back()
        ->with(
            'success',
            'Aturan peminjaman berhasil diperbarui'
        );

    }





    // ===============================
    // CETAK
    // ===============================
    public function cetak()
    {

        $pengaturan=$this->pengaturanModel->first();


        return view('pengaturan/cetak',[

            'title'=>'Pengaturan Cetak',

            'pengaturan'=>$pengaturan

        ]);

    }




public function updateCetak()
    {

        $id=$this->request->getPost('id');


        $data=[

            'ukuran_kertas'=>$this->request->getPost('ukuran_kertas'),

            'footer_cetak'=>$this->request->getPost('footer_cetak'),

        ];


        $this->pengaturanModel->update($id,$data);


        return redirect()
        ->back()
        ->with(
            'success',
            'Pengaturan cetak berhasil diperbarui'
        );

    }





    // ===============================
    // BACKUP & RESTORE DATA
    // ===============================
    public function backup()
    {
        return view('pengaturan/backup', [
            'title' => 'Backup & Restore Data',
        ]);
    }




    // Download backup sebagai file JSON
    public function downloadBackup()
    {
        $db = \Config\Database::connect();
        $tables = $db->listTables();

        $data = [];
        foreach ($tables as $table) {
            $rows = $db->table($table)->get()->getResultArray();
            $data[$table] = $rows;
        }

        $backup = [
            'info' => [
                'app'     => 'Perpustakaan MAS',
                'tanggal' => date('Y-m-d H:i:s'),
                'versi'   => '1.0',
            ],
            'data' => $data,
        ];

        $filename = 'backup_perpustakaan_' . date('Y-m-d_H-i-s') . '.json';
        $json = json_encode($backup, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

        // Force download file
        return $this->response->download($filename, $json);
    }




    // Restore data dari file backup JSON
    public function restoreBackup()
    {
        $file = $this->request->getFile('file_restore');

        if (!$file || !$file->isValid()) {
            return redirect()->back()->with('error', 'Pilih file backup terlebih dahulu.');
        }

        $fileContent = file_get_contents($file->getTempName());

        if (empty($fileContent)) {
            return redirect()->back()->with('error', 'File backup kosong.');
        }

        try {
            $backup = json_decode($fileContent, true);
            if (!$backup || !isset($backup['data'])) {
                return redirect()->back()->with('error', 'File backup tidak valid.');
            }

            $db = \Config\Database::connect();

            foreach ($backup['data'] as $table => $rows) {
                if (empty($rows)) continue;

                $db->table($table)->truncate();

                foreach ($rows as $row) {
                    $db->table($table)->insert($row);
                }
            }

            return redirect()->back()->with('success', 'Data berhasil direstore.');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Gagal restore: ' . $e->getMessage());
        }
    }

}
