<?php

namespace App\Controllers\Admin;

use App\Models\DownloadModel;

class Downloads extends BaseController
{
    protected $downloadModel;

    public function initController($request, $response, $logger)
    {
        parent::initController($request, $response, $logger);
        $this->downloadModel = new DownloadModel();
    }

    public function index()
    {
        $this->data['title'] = 'Download Center';
        $this->data['items'] = $this->downloadModel->orderBy('sort_order', 'ASC')->paginate(10);
        $this->data['pager'] = $this->downloadModel->pager;

        return view('admin/downloads/index', $this->data);
    }

    public function new()
    {
        $this->data['title'] = 'Tambah Download';
        $this->data['item']  = [];
        return view('admin/downloads/form', $this->data);
    }

    public function create()
    {
        $data = $this->request->getPost();
        $data['show'] = $data['show'] ?? 0;

        if (!$this->downloadModel->insert($data)) {
            return redirect()->back()->withInput()->with('error', 'Gagal menyimpan download.');
        }

        return redirect()->to('/admin/downloads')->with('success', 'Download berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $this->data['title'] = 'Edit Download';
        $this->data['item']  = $this->downloadModel->find($id);

        if (!$this->data['item']) {
            return redirect()->to('/admin/downloads')->with('error', 'Download tidak ditemukan.');
        }

        return view('admin/downloads/form', $this->data);
    }

    public function update($id)
    {
        $data = $this->request->getPost();
        $data['show'] = $data['show'] ?? 0;

        if (!$this->downloadModel->update($id, $data)) {
            return redirect()->back()->withInput()->with('error', 'Gagal memperbarui download.');
        }

        return redirect()->to('/admin/downloads')->with('success', 'Download berhasil diperbarui.');
    }

    public function reorder()
    {
        $input = json_decode($this->request->getBody(), true);
        $ids = $input['ids'] ?? [];

        if (empty($ids)) {
            return $this->response->setJSON(['success' => false]);
        }

        $db = \Config\Database::connect();
        $case = '';
        foreach ($ids as $i => $id) {
            $id = (int) $id;
            $case .= "WHEN id = {$id} THEN {$i} ";
        }
        $idsList = implode(',', array_map('intval', $ids));
        $db->query("UPDATE downloads SET sort_order = CASE {$case} END WHERE id IN ({$idsList})");

        return $this->response->setJSON(['success' => true, 'csrfHash' => csrf_hash()]);
    }

    public function delete($id)
    {
        if (!$this->downloadModel->delete($id)) {
            return redirect()->to('/admin/downloads')->with('error', 'Gagal menghapus download.');
        }

        return redirect()->to('/admin/downloads')->with('success', 'Download berhasil dihapus.');
    }
}
