<?php

namespace App\Controllers;

use App\Models\SettingModel;
use CodeIgniter\Controller;

class Setting extends Controller
{
    protected $settingModel;

    public function __construct()
    {
        $this->settingModel = new SettingModel();
    }

    // =========================
    // VIEW DESAIN STRUK
    // =========================
    public function receipt()
    {
        $data = [
            'title'   => 'Desain Struk',
            'setting' => $this->settingModel->getReceiptSetting()
        ];
        return view('setting/receipt', $data);
    }

    public function receiptSave()
    {
        $header = $this->request->getPost('header');
        $footer = $this->request->getPost('footer');

        // Ambil data lama
        $oldData  = $this->settingModel->getReceiptSetting();
        $logoName = $oldData['logo'] ?? '';

        // Upload logo baru
        $file = $this->request->getFile('logo');
        if ($file && $file->isValid() && !$file->hasMoved()) {
            $logoName = 'logo_' . time() . '.' . $file->getExtension();
            $file->move(FCPATH . 'uploads', $logoName);

            // Hapus logo lama jika ada
            if (!empty($oldData['logo']) && file_exists(FCPATH . 'uploads/' . $oldData['logo'])) {
                @unlink(FCPATH . 'uploads/' . $oldData['logo']);
            }
        }

        // Simpan data baru
        $newData = [
            'header' => $header,
            'footer' => $footer,
            'logo'   => $logoName
        ];

        $this->settingModel->saveSetting('receipt', json_encode($newData));

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

    public function printer()
{
    $data = [
        'title'   => 'Koneksi Printer',
        'printer' => $this->settingModel->get('printer_name'),
        'receipt_layout' => json_decode($this->settingModel->get('receipt_layout') ?? '{}', true),
        'receipt_setting' => $this->settingModel->getReceiptSetting()
    ];
    return view('setting/printer', $data);
}


    public function printerSave()
    {
        $printer = $this->request->getPost('printer_name');
        $this->settingModel->saveSetting('printer_name', $printer);
        return redirect()->back()->with('success', 'Printer berhasil disimpan.');
    }

    public function exportForm()
{
    return view('setting/export');
}

    public function export()
{
    helper('filesystem');

    $db       = \Config\Database::connect();
    $dbName   = $db->getDatabase();
    $request  = \Config\Services::request();

    $format   = $request->getPost('format') ?? 'sql';
    $rawName  = $request->getPost('filename');
    $dateSuffix = date('Ymd_His');
    $cleanName = $rawName
    ? preg_replace('/[^a-zA-Z0-9_-]/', '', $rawName) . '_' . $dateSuffix : 'backup_' . $dateSuffix;


    $ext = ($format === 'zip') ? 'zip' : 'sql';
    $filenameFull = $cleanName . '.' . $ext;

    $pathDir  = WRITEPATH . 'exports/';
    $pathFull = $pathDir . $filenameFull;

    if (!is_dir($pathDir)) {
        mkdir($pathDir, 0775, true);
    }

    $user = getenv('database.default.username');
    $pass = getenv('database.default.password');

    $userEsc   = escapeshellarg($user);
    $passPlain = str_replace("'", '', $pass);

    if ($format === 'zip') {
        $tempSql = $pathDir . $cleanName . '.sql';
        $dumpCmd = "mysqldump -u {$userEsc} -p{$passPlain} {$dbName} > {$tempSql}";
        system($dumpCmd);

        $zip = new \ZipArchive();
        if ($zip->open($pathFull, \ZipArchive::CREATE) === TRUE) {
            $zip->addFile($tempSql, basename($tempSql));
            $zip->close();
            unlink($tempSql);
        }
    } else {
        $dumpCmd = "mysqldump -u {$userEsc} -p{$passPlain} {$dbName} > {$pathFull}";
        system($dumpCmd);
    }

    return $this->response->download($pathFull, null)->setFileName($filenameFull);
}



    public function layout()
    {
        $layout = $this->settingModel->get('receipt_layout');
        $data = [
            'title'  => 'Layout Struk Dinamis',
            'layout' => $layout ? json_decode($layout, true) : []
        ];
        return view('setting/layout', $data);
    }

    public function layoutSave()
    {
        $json = $this->request->getPost('json');
        $this->settingModel->saveSetting('receipt_layout', $json);
        return redirect()->back()->with('success', 'Layout berhasil disimpan.');
    }
}

