<?php
namespace App\Controllers\Admin;

use App\Models\Banner;

class BannerController extends AdminController
{
    public function index()
    {
        return $this->view('admin/banners', [
            'banners' => (new Banner())->all(),
            'seg'     => $this->seg(),
        ]);
    }

    public function create()
    {
        return $this->view('admin/banner_form', ['b' => null]);
    }

    public function store()
    {
        if (!csrf_check()) { $this->redirect('admin/banners'); }
        $image = $this->uploadFile('image') ?? $this->post('image', 'linear-gradient(135deg,#0ea5e9,#14b8a6)');
        (new Banner())->insert([
            'title'       => $this->post('title'),
            'subtitle'    => $this->post('subtitle'),
            'image'       => $image,
            'link'        => $this->post('link', ''),
            'sort_order'  => (int)$this->post('sort_order', 0),
            'status'      => $this->post('status', 1) ? 1 : 0,
        ]);
        $this->redirect('admin/banners');
    }

    public function edit($id)
    {
        $b = (new Banner())->find($id);
        if (!$b) { $this->redirect('admin/banners'); }
        return $this->view('admin/banner_form', ['b' => $b]);
    }

    public function update($id)
    {
        if (!csrf_check()) { $this->redirect('admin/banners'); }
        $banner = new Banner();
        $b = $banner->find($id);
        if (!$b) { $this->redirect('admin/banners'); }
        $image = $this->uploadFile('image');
        if (!$image && $this->post('image')) $image = $this->post('image');
        if (!$image) $image = $b['image'] ?? '';
        $banner->update($id, [
            'title'      => $this->post('title'),
            'subtitle'   => $this->post('subtitle'),
            'image'      => $image,
            'link'       => $this->post('link', ''),
            'sort_order' => (int)$this->post('sort_order', 0),
            'status'     => $this->post('status', 1) ? 1 : 0,
        ]);
        $this->redirect('admin/banners');
    }

    public function delete($id)
    {
        if (csrf_check()) { (new Banner())->delete($id); }
        $this->redirect('admin/banners');
    }
}
