<?php

namespace Modules\Posts\Controllers;

use App\Controllers\Auth\AuthController;

class BlockPosts extends AuthController
{
    public function initController($request, $response, $logger)
    {
        parent::initController($request, $response, $logger);
        $this->data['categoryTree']         = $this->postscategoryModel->getCategoryList();
    }

    public function saveBlock()
    {
        if ($this->request->getMethod() === 'POST')
        {
            $blockType = $this->request->getPost('block_type'); // e.g. text, heading, image
            $postId    = $this->request->getPost('post_id');
            $getPost    = $this->postsModel->where('id', $postId)->first($postId);
            
            // Basic validation based on block type
            $rules = [];
            switch ($blockType) {
                case 'text':
                    $rules = ['description' => ['label'=>'Text', 'rules'=>'required']];
                    break;
                case 'list':
                    $rules = ['list_content' => ['label'=>'List', 'rules'=>'required']];
                    break;
                case 'heading':
                    $rules = ['heading' => ['label'=>'Heading', 'rules'=>'required']];
                    break;
                case 'image':
                    $rules = ['photo' => ['label' => 'Image', 'rules' => 'uploaded[photo]']];
                    break;
                case 'cards':
                    $rules = ['card_name' => ['label'=>'Name', 'rules'=>'required']];
                    break;
                case 'stats':
                    $rules = ['stats_title' => ['label'=>'Title', 'rules'=>'required']];
                    break;
                case 'gallery':
                    $rules = ['gallery_title' => ['label'=>'Title', 'rules'=>'required']];
                    break;
                case 'code':
                    $rules = ['code' => ['label'=>'Code', 'rules'=>'required']];
                    break;
                case 'advert':
                    $rules = ['advert_code' => ['label'=>'Advert', 'rules'=>'required']];
                    break;
                
            }

            if(!$this->validate($rules)){
                $validation = \Config\Services::validation();
                $errors = $validation->getErrors();;
                $errorMessage = implode('<br>', $errors);
                //session()->setFlashdata('error', $errorMessage, 5);

                if($this->request->isAJAX()){
                    $response = [
                        'success' => false,
                        'msg' => $errorMessage, 	   
                    ];
                    return $this->response->setJSON($response);
                }else{
                    session()->setFlashdata('error', $errorMessage, 5);
                    return redirect()->to('administrator/posts/block-post/edit/'.$postId.'-'.$getPost['alias']);
                }
            }

            switch ($blockType) {
                case 'text':
                    $content = $this->request->getVar('description');
                    break;
                case 'list':
                    $content = $this->request->getVar('list_content');
                    break;
                case 'heading':
                    $heading = $this->request->getVar('heading');
                    break;
                case 'cards':
                    $heading = $this->request->getVar('card_name');
                    break;
                case 'stats':
                    $heading = $this->request->getVar('stats_title');
                    break;
                case 'gallery':
                    $heading = $this->request->getVar('gallery_title');
                    $content = $this->request->getVar('gallery_description');
                    break;
                
                    
            }

            // Save in Post Block
            $data = [
                'post_id'      => $postId,
                'block_type'   => $blockType,
                'block_cat'    => $this->request->getVar('block_cat'),
                'content'      => $content ?? null,
                'heading'      => $heading ?? null,
                'heading_type' => $this->request->getVar('heading_type'),
                'color'        => $this->request->getVar('color'),
                'caption'      => $this->request->getVar('caption'),
                'list_type'    => $this->request->getVar('list_type'),
                'code'         => $this->request->getVar('code'),
                'advert_code'  => $this->request->getVar('advert_code'),
                'ordering'     => $this->request->getVar('ordering') ?? 0,
                'status'       => 'active'
            ];

            // Handle image upload if block_type is image
            if ($blockType === 'image') {
                $file = $this->request->getFile('photo');
                if ($file && $file->isValid() && !$file->hasMoved()) {
                    $newName = $file->getRandomName();
                    $file->move(ROOTPATH . 'media/posts', $newName);
                    $data['photo'] = base_url('media/posts/' . $newName);
                }
            }

            // Save or update block
            $blockId = $this->request->getVar('id');
            $result = $blockId 
                ? $this->postblocksModel->updateWithOrdering($blockId, $data) 
                : $this->postblocksModel->insertWithOrdering($data);

            if ($result) {
                if(!$blockId){
                    if($this->request->isAJAX()){
                        $response = [
                            'success' => true,
                            'msg' => 'Block saved successfully', 	   
                        ];
                        return $this->response->setJSON($response);
                    }else{
                        session()->setFlashdata('success', 'Block saved successfully', 3);
                    }
                    
                }
                session()->setFlashdata('info', 'Block updated successfully', 3);
            } else {
                
                if($this->request->isAJAX()){
                        $response = [
                            'success' => false,
                            'msg' => 'Failed to save block', 	   
                        ];
                        return $this->response->setJSON($response);
                    }else{
                        session()->setFlashdata('error', 'Failed to save block', 3);
                    }
            }
            return redirect()->to('administrator/posts/block-post/edit/'.$postId.'-'.$getPost['alias']);
        }
    }

    public function getBlock($id)
    {
        $block = $this->postblocksModel->find($id);
        if (!$block) {
            return $this->response->setJSON(['error' => true, 'msg' => 'Block not found']);
        }
        return $this->response->setJSON(['success' => true, 'data' => $block]);
    }

    public function deleteBlock($id)
    {
        $block = $this->postblocksModel->find($id);
        if ($block) {
            $this->postblocksModel->deleteAndReorder($id);
            session()->setFlashdata('success', 'Block deleted successfully', 3);
        }
        session()->setFlashdata('error', 'Block not found', 3);
        return redirect()->to(previous_url());
    }

/** ======================================================
 *  POST BLOCK ITEMS
 *==========================================================*/
    public function saveChildItem()
    {
        if ($this->request->getMethod() === 'POST') {
            $blockId  = $this->request->getPost('block_id');
            $itemType = $this->request->getPost('item_type');

            $data = [
                'block_id'    => $blockId,
                'item_type'   => $itemType,
                'title'       => $this->request->getVar('title'),
                'icon'        => $this->request->getVar('icon'),
                'value'       => $this->request->getVar('value'),
                'description' => $this->request->getVar('description'),
                'caption'     => $this->request->getVar('caption'),
                'link'        => $this->request->getVar('link'),
                'ordering'    => $this->request->getVar('ordering') ?? 0,
                'status'      => 'active'
            ];

            // Handle photo upload if gallery or cards
            if (in_array($itemType, ['gallery', 'cards']) && $file = $this->request->getFile('photo')) {
                if ($file->isValid() && !$file->hasMoved()) {
                    $newName = $file->getRandomName();
                    $file->move(ROOTPATH . 'media/posts', $newName);
                    $data['photo'] = base_url('/media/posts/') . $newName;
                }
            }

            $itemId = $this->request->getPost('id');
            $result = $itemId 
                ? $this->postblockitemsModel->update($itemId, $data)
                : $this->postblockitemsModel->save($data);

            return $this->response->setJSON([
                'success' => (bool)$result,
                'msg'     => $itemId ? 'Item updated successfully' : 'Item added successfully'
            ]);
        }
    }

    public function getChildItem($id)
    {
        $item = $this->postblockitemsModel->find($id);
        return $this->response->setJSON($item ? ['success' => true, 'data' => $item] : ['error' => true, 'msg' => 'Item not found']);
    }

    public function deleteChildItem($id)
    {
        $post = $this->postblockitemsModel->singleBlockItem($id);
        $result = $this->postblockitemsModel->delete($id);
        if($result){
            session()->setFlashdata('error', 'Item deleted successfully', 3);
            return redirect()->to('administrator/posts/block-post/edit/'.$post->post_id.'-'.$post->post_alias);
        }
    }

}