<?php namespace App\Controllers;

use App\Models\WebStoryModel;
use App\Models\CategoryModel;
use App\Services\UploadService;

class AdminWebStoryController extends BaseAdminController
{
    protected $storyModel;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->storyModel = new WebStoryModel();
    }

    public function index()
    {
        checkPermission('web_stories');

        $perPage = $this->perPage ?? 15;
        $data = [
            'title'         => trans("web_stories") ?? 'Web Stories',
            'stories'       => $this->storyModel->getPaginatedStories($perPage),
            'pager'         => $this->storyModel->pager,
            'panelSettings' => panelSettings()
        ];

        return view('admin/web_story/index', $data);
    }

    public function add()
    {
        checkPermission('web_stories');

        if (isPostMethod()) {
            $postData = $this->request->getPost();
            $uploadService = new UploadService($this->config);
            
            $slug = cleanSlug($postData['slug'] ?? '');
            if (empty($slug)) {
                $slug = strSlug($postData['title']);
            }

            $coverImage = $postData['cover_image_url'] ?? '';
            $coverFile = $this->request->getFile('cover_image_file');
            if ($coverFile && $coverFile->isValid() && !$coverFile->hasMoved()) {
                $uploadedCover = $uploadService->uploadRawFile($coverFile, [
                    'folderName' => 'web_stories',
                    'prefix' => 'cover_',
                    'allowedExtensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif']
                ]);
                if (!empty($uploadedCover['path'])) {
                    $coverImage = $uploadedCover['path'];
                }
            }

            $storyContent = [];
            $slideUrls = $postData['slide_image_url'] ?? [];
            $slideFiles = $this->request->getFileMultiple('slide_image_file') ?? [];

            for ($i = 0; $i < count($slideUrls); $i++) {
                $slideImage = $slideUrls[$i] ?? '';
                
                if (isset($slideFiles[$i]) && $slideFiles[$i]->isValid() && !$slideFiles[$i]->hasMoved()) {
                    $uploadedSlide = $uploadService->uploadRawFile($slideFiles[$i], [
                        'folderName' => 'web_stories',
                        'prefix' => 'slide_',
                        'allowedExtensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'mp4', 'webm']
                    ]);
                    if (!empty($uploadedSlide['path'])) {
                        $slideImage = $uploadedSlide['path'];
                    }
                }

                if (!empty($slideImage)) {
                    $storyContent[] = [
                        'image'       => $slideImage,
                        'heading'     => cleanStr($postData['slide_heading'][$i] ?? ''),
                        'description' => cleanStr($postData['slide_description'][$i] ?? ''),
                        'link'        => trim($postData['slide_link'][$i] ?? '')
                    ];
                }
            }

            $data = [
                'lang_id'       => $this->activeLang->id,
                'title'         => cleanStr($postData['title']),
                'slug'          => $slug,
                'summary'       => cleanStr($postData['summary'] ?? ''),
                'cover_image'   => $coverImage,
                'story_content' => json_encode($storyContent, JSON_UNESCAPED_UNICODE),
                'category_id'   => (int)($postData['category_id'] ?? 0),
                'user_id'       => user()->id,
                'visibility'    => 1,
                'status'        => (int)($postData['status'] ?? 1),
            ];

            if ($this->storyModel->insert($data)) {
                setSuccessMessage("msg_added");
                return redirect()->to(adminUrl('web-stories'));
            } else {
                setErrorMessage("msg_error");
                return redirect()->back()->withInput();
            }
        }

        $categoryModel = new CategoryModel();
        $data = [
            'title'      => trans("add_story") ?? 'Add Web Story',
            'categories' => $categoryModel->findAllRoots($this->activeLang->id)
        ];

        return view('admin/web_story/add', $data);
    }

    public function edit($id)
    {
        checkPermission('web_stories');

        $story = $this->storyModel->find($id);
        if (!$story) {
            return redirect()->to(adminUrl('web-stories'));
        }

        if (!hasPermission('manage_all_posts') && $story->user_id != user()->id) {
            setErrorMessage("msg_error");
            return redirect()->to(adminUrl('web-stories'));
        }

        if (isPostMethod()) {
            $postData = $this->request->getPost();
            $uploadService = new UploadService($this->config);
            
            $slug = cleanSlug($postData['slug'] ?? '');
            if (empty($slug)) {
                $slug = strSlug($postData['title']);
            }

            // FIX: Prevent wiping of existing image if no new URL/File is provided
            $coverUrl = $postData['cover_image_url'] ?? '';
            $coverImage = !empty($coverUrl) ? $coverUrl : $story->cover_image;
            
            $coverFile = $this->request->getFile('cover_image_file');
            if ($coverFile && $coverFile->isValid() && !$coverFile->hasMoved()) {
                $uploadedCover = $uploadService->uploadRawFile($coverFile, [
                    'folderName' => 'web_stories',
                    'prefix' => 'cover_',
                    'allowedExtensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif']
                ]);
                if (!empty($uploadedCover['path'])) {
                    $coverImage = $uploadedCover['path'];
                }
            }

            $storyContent = [];
            $slideUrls = $postData['slide_image_url'] ?? [];
            $slideFiles = $this->request->getFileMultiple('slide_image_file') ?? [];

            for ($i = 0; $i < count($slideUrls); $i++) {
                $slideImage = $slideUrls[$i] ?? '';
                
                if (isset($slideFiles[$i]) && $slideFiles[$i]->isValid() && !$slideFiles[$i]->hasMoved()) {
                    $uploadedSlide = $uploadService->uploadRawFile($slideFiles[$i], [
                        'folderName' => 'web_stories',
                        'prefix' => 'slide_',
                        'allowedExtensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'mp4', 'webm']
                    ]);
                    if (!empty($uploadedSlide['path'])) {
                        $slideImage = $uploadedSlide['path'];
                    }
                }

                if (!empty($slideImage)) {
                    $storyContent[] = [
                        'image'       => $slideImage,
                        'heading'     => cleanStr($postData['slide_heading'][$i] ?? ''),
                        'description' => cleanStr($postData['slide_description'][$i] ?? ''),
                        'link'        => trim($postData['slide_link'][$i] ?? '')
                    ];
                }
            }

            $data = [
                'title'         => cleanStr($postData['title']),
                'slug'          => $slug,
                'summary'       => cleanStr($postData['summary'] ?? ''),
                'cover_image'   => $coverImage,
                'story_content' => json_encode($storyContent, JSON_UNESCAPED_UNICODE),
                'category_id'   => (int)($postData['category_id'] ?? 0),
                'status'        => (int)($postData['status'] ?? 1),
            ];

            if ($this->storyModel->update($id, $data)) {
                setSuccessMessage("msg_updated");
                return redirect()->to(adminUrl('web-stories'));
            } else {
                setErrorMessage("msg_error");
                return redirect()->back()->withInput();
            }
        }

        $categoryModel = new CategoryModel();
        $data = [
            'title'      => trans("update_story") ?? 'Update Web Story',
            'story'      => $story,
            'categories' => $categoryModel->findAllRoots($this->activeLang->id)
        ];

        return view('admin/web_story/edit', $data);
    }

    public function delete()
    {
        if (!hasPermission('web_stories')) {
            return jsonResponse(false);
        }

        $id = (int)inputPost('id');
        $story = $this->storyModel->find($id);

        if (!$story) {
            setErrorMessage('msg_error');
            return jsonResponse(false);
        }

        if (!hasPermission('manage_all_posts') && $story->user_id != user()->id) {
            setErrorMessage("msg_error");
            return jsonResponse(false);
        }

        if ($this->storyModel->delete($id)) {
            setSuccessMessage("msg_deleted");
            return jsonResponse(true);
        }

        setErrorMessage("msg_error");
        return jsonResponse(false);
    }
}