<?php

namespace App\Controllers\Superadmin;

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

class Restore extends BaseController
{
    protected $activityModel;
    protected $db;

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

    /*
    |--------------------------------------------------------------------------
    | Halaman Restore
    |--------------------------------------------------------------------------
    */

    public function index()
    {
        return view('superadmin/restore/index',[
            'title'=>'Restore Database'
        ]);
    }

    public function process()
{
    $file = $this->request->getFile('database');

    if (!$file->isValid()) {

        return redirect()->back()
            ->with('error','File tidak valid.');

    }

    if ($file->getExtension() != 'sql') {

        return redirect()->back()
            ->with('error','File harus SQL.');

    }

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

    $queries = explode(";", $sql);

    foreach ($queries as $query) {

        $query = trim($query);

        if ($query != '') {

            try{

                $this->db->query($query);

            }catch(\Exception $e){

                // lanjutkan query berikutnya

            }

        }

    }

    $this->activityModel->logActivity(

        session()->get('id_user'),

        'Melakukan Restore Database'

    );

    return redirect()

        ->back()

        ->with('success','Restore Database berhasil.');
}

}