<?php

namespace App\Controllers\Superadmin;

use App\Controllers\BaseController;
use App\Models\BackupModel;
use App\Models\ActivityLogModel;

class Backup extends BaseController
{
    protected $backupModel;
    protected $activityModel;
    protected $db;

    public function __construct()
    {
        $this->backupModel   = new BackupModel();
        $this->activityModel = new ActivityLogModel();
        $this->db            = \Config\Database::connect();
    }

    /*
    |--------------------------------------------------------------------------
    | Daftar Backup
    |--------------------------------------------------------------------------
    */

    public function index()
    {
        $backups = $this->db->table('backup_logs b')
            ->select("
                b.*,
                u.username,
                u.nama_lengkap
            ")
            ->join('users u','u.id_user=b.id_user','left')
            ->orderBy('b.backup_date','DESC')
            ->get()
            ->getResultArray();

        return view('superadmin/backup/index',[
            'title'=>'Backup Database',
            'backups'=>$backups
        ]);
    }

    /*
    |--------------------------------------------------------------------------
    | History Backup
    |--------------------------------------------------------------------------
    */

    public function history()
    {
        return $this->index();
    }

//     public function createBackup()
// {
//     // $util = \Config\Database::utils();

//     $prefs = [
//         'format'   => 'txt',
//         'filename' => 'backup.sql'
//     ];

//     $backup = $util->backup($prefs);

//     $fileName = 'backup_' . date('Ymd_His') . '.sql';

//     $path = WRITEPATH . 'backups/';

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

//     write_file($path . $fileName, $backup);

//     $size = round(filesize($path . $fileName) / 1024 / 1024, 2);

//     $this->backupModel->insert([
//         'id_user'   => session()->get('id_user'),
//         'filename'  => $fileName,
//         'size_mb'   => $size
//     ]);

//     $this->activityModel->logActivity(
//         session()->get('id_user'),
//         'Melakukan Backup Database'
//     );

//     return redirect()->back()
//         ->with('success','Backup berhasil dibuat.');
// }

public function download($id)
{
    $backup = $this->backupModel->find($id);

    if (!$backup) {
        throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
    }

    $file = WRITEPATH . 'backups/' . $backup['filename'];

    if (!file_exists($file)) {
        return redirect()->back()
            ->with('error','File backup tidak ditemukan.');
    }

    return $this->response->download($file, null);
}

public function delete($id)
{
    $backup = $this->backupModel->find($id);

    if (!$backup) {
        throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
    }

    $file = WRITEPATH . 'backups/' . $backup['filename'];

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

    $this->backupModel->delete($id);

    $this->activityModel->logActivity(
        session()->get('id_user'),
        'Menghapus Backup Database'
    );

    return redirect()->back()
        ->with('success','Backup berhasil dihapus.');
}

}