<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Models\HomepageBlockModel;

final class HomepageBlockController extends Controller
{
    public function index(): void
    {
        require_permission('homepage_blocks.view');

        $this->view('admin/homepage_blocks/index', [
            'rows' => (new HomepageBlockModel())->all(),
        ]);
    }

    public function create(): void
    {
        require_permission('homepage_blocks.manage');

        if ($this->isPost()) {
            csrf_check();

            $data = $this->postData();

            if (!empty($_FILES['image_file']['name'])) {
                $upload = handle_uploaded_submission_file($_FILES['image_file'], 'homepage/blocks');
                $data['image_path'] = base_path('../storage/' . $upload['relative_path']);
            }

            $data['created_by'] = auth_id();

            (new HomepageBlockModel())->create($data);

            flash('success', trans('save'));
            redirect('admin/homepage-blocks');
        }

        $this->view('admin/homepage_blocks/create');
    }

    public function edit(): void
    {
        require_permission('homepage_blocks.manage');

        $id = (int) ($_GET['id'] ?? 0);
        $model = new HomepageBlockModel();
        $row = $model->findById($id);

        if (!$row) {
            redirect('admin/homepage-blocks');
        }

        if ($this->isPost()) {
            csrf_check();

            $data = $this->postData();
            $data['image_path'] = trim((string) ($_POST['image_path_existing'] ?? ($row['image_path'] ?? '')));

            if (!empty($_FILES['image_file']['name'])) {
                $upload = handle_uploaded_submission_file($_FILES['image_file'], 'homepage/blocks');
                $data['image_path'] = base_path('../storage/' . $upload['relative_path']);
            }

            $model->update($id, $data);

            flash('success', trans('save'));
            redirect('admin/homepage-blocks');
        }

        $this->view('admin/homepage_blocks/edit', [
            'row' => $row,
        ]);
    }

    public function sort(): void
    {
        require_permission('homepage_blocks.manage');

        if (!$this->isPost()) {
            redirect('admin/homepage-blocks');
        }

        csrf_check();

        $ids = $_POST['ordered_ids'] ?? [];
        if (!is_array($ids)) {
            $ids = [];
        }

        $db = \App\Core\Database::getInstance();
        $stmt = $db->prepare("UPDATE homepage_blocks SET sort_order = :sort_order WHERE id = :id");

        $sort = 1;
        foreach ($ids as $id) {
            $stmt->execute([
                ':sort_order' => $sort++,
                ':id' => (int) $id,
            ]);
        }

        flash('success', trans('save'));
        redirect('admin/homepage-blocks');
    }

    private function postData(): array
    {
        return [
            'block_type' => trim((string) ($_POST['block_type'] ?? 'feature')),
            'title_en' => trim((string) ($_POST['title_en'] ?? '')),
            'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
            'body_en' => trim((string) ($_POST['body_en'] ?? '')),
            'body_ar' => trim((string) ($_POST['body_ar'] ?? '')),
            'image_path' => trim((string) ($_POST['image_path'] ?? '')),
            'link_url' => trim((string) ($_POST['link_url'] ?? '')),
            'sort_order' => (int) ($_POST['sort_order'] ?? 0),
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
        ];
    }
}
