<?php namespace App\Controllers\Api;
use App\Controllers\BaseApiController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Models\pageMediaModel;
use CodeIgniter\RESTful\ResourceController;

class PageMediaController extends BaseApiController
{
    public function getMediaList()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $jwtSecret = getenv('JWT_SECRET');
            if (!$jwtSecret || !is_string($jwtSecret)) {
                return $this->failServerError('JWT secret key is not configured properly.');
            }

            $decoded = JWT::decode($token, new Key($jwtSecret, 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token payload.');
            }

            $db = \Config\Database::connect();

            $builder = $db->table('page_media pm');
            $builder->select('pm.*, 
                            m1.name AS menu_name, 
                            m2.name AS submenu_name');
            $builder->join('menus m1', 'pm.menu_id = m1.id', 'left');
            $builder->join('menus m2', 'pm.submenu_id = m2.id', 'left');
            $builder->where('pm.row_status', 1);
            $builder->orderBy('pm.created_at', 'DESC');

            $query = $builder->get();
            $mediaList = $query->getResult();

            return $this->respond([
                'status' => 200,
                'message' => 'Media list fetched successfully.',
                'data' => $mediaList
            ]);

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }



   public function addMedia()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));

            $menuId = $this->request->getPost('menu_id');
            $submenuId = $this->request->getPost('submenu_id');

            $files = $this->request->getFiles()['media_files'];
            if (empty($files)) {
                return $this->fail('No files uploaded.');
            }

            helper('filesystem');
            $savedFiles = [];
            $mediaModel = new \App\Models\PageMediaModel();
            foreach ($files as $file) {
                if ($file->isValid() && !$file->hasMoved()) {
                    $newName = time() . '_' . $file->getClientName();

                    $uploadPath = WRITEPATH . 'uploads/page_media/';
                    if (!is_dir($uploadPath)) {
                        mkdir($uploadPath, 0755, true);
                    }

                    if ($file->move($uploadPath, $newName)) {
                        // Optional: copy to public folder for preview
                        copy($uploadPath . $newName, FCPATH . 'uploads/page_media/' . $newName);

                        $savedFiles[] = $newName;

                        $mediaModel->insert([
                            'menu_id'    => $menuId,
                            'submenu_id' => $submenuId,
                            'image'      => base_url('uploads/page_media/' . $newName),
                            'created_at' => date('Y-m-d H:i:s'),
                        ]);
                    } else {
                        log_message('error', 'Move failed for file: ' . $file->getClientName());
                    }
                } else {
                    log_message('error', 'Invalid file: ' . $file->getErrorString());
                }
            }


            return $this->respond([
                'status' => 200,
                'message' => 'Media uploaded successfully.',
                'files' => $savedFiles
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }

   public function deleteMedia()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $id = $this->request->getPost('id');

            if (!$id || !is_numeric($id)) {
                return $this->fail('Invalid media ID.');
            }

            $mediaModel = new PageMediaModel();
            $existing = $mediaModel->find($id);

            if (!$existing) {
                return $this->failNotFound('Media not found.');
            }

            // Option 1: Soft delete
            // $mediaModel->update($id, ['row_status' => 0]);

            // Option 2: Hard delete from DB and optionally delete the file
            $mediaModel->delete($id);

            // Optionally delete the actual file
            $filePath = WRITEPATH . 'uploads/page_media/' . basename($existing['image']);
            if (file_exists($filePath)) {
                unlink($filePath);
            }

            return $this->respond([
                'status' => true,
                'message' => 'Media deleted successfully.'
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Delete Media Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getMediaById()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        try {
            $token = trim(str_replace('Bearer', '', $authHeader));
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));

            $id = $this->request->getGet('id');
            if (!$id || !is_numeric($id)) {
                return $this->fail('Invalid media ID.');
            }
             $mediaModel = new PageMediaModel();
            $media = $mediaModel->find($id);
            if (!$media) {
                return $this->failNotFound('Media not found.');
            }

            return $this->respond([
                'status' => true,
                'data'   => $media
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }


    public function updateMedia()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));

            $mediaModel = new \App\Models\PageMediaModel();

            $mediaId = $this->request->getPost('id');
            $menuId = $this->request->getPost('menu_id');
            $submenuId = $this->request->getPost('submenu_id');

            $mediaItem = $mediaModel->find($mediaId);
            if (!$mediaItem) {
                return $this->failNotFound('Media item not found.');
            }

            // Update fields even if no file uploaded
            $updateData = [
                'menu_id'    => $menuId,
                'submenu_id' => $submenuId,
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            $files = $this->request->getFiles()['media_files'] ?? null;

            if ($files) {
                helper('filesystem');
                $uploadPath = WRITEPATH . 'uploads/page_media/';
                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath, 0755, true);
                }

                // Handle multiple files (replace only the first one, or extend logic for multiple if needed)
                foreach ($files as $file) {
                    if ($file->isValid() && !$file->hasMoved()) {
                        // Delete old image
                        $oldImage = basename($mediaItem['image']);
                        @unlink($uploadPath . $oldImage);
                        @unlink(FCPATH . 'uploads/page_media/' . $oldImage);

                        // Save new image
                        $newName = time() . '_' . $file->getClientName();
                        if ($file->move($uploadPath, $newName)) {
                            copy($uploadPath . $newName, FCPATH . 'uploads/page_media/' . $newName);

                            $updateData['image'] = base_url('uploads/page_media/' . $newName);
                        }
                        break; // Only replace with the first valid uploaded file
                    }
                }
            }

            $mediaModel->update($mediaId, $updateData);

            return $this->respond([
                'status' => 200,
                'message' => 'Media updated successfully.',
            ]);
        } catch (\Exception $e) {
            log_message('error', 'JWT Decode Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }




}