<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

require APPPATH . '/libraries/BaseController.php';

class Gifts extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('gifts_model');
        $this->load->helper('url');
        $this->load->library('form_validation');
     //   $this->isLoggedIn();
    }

    /**
     * List all gifts
     */
    public function index()
    {

        if (!$this->canAccessGifts() && !$this->isAdmin()) {
            $this->loadThis();
        } else {
            $searchText = '';
            if (!empty($this->input->post('searchText'))) {
                $searchText = $this->security->xss_clean($this->input->post('searchText'));
            }
            $data['searchText'] = $searchText;

            // Get all gifts
            $allGifts = $this->gifts_model->get_all_gifts();
            
            // Apply search filter
            if (!empty($searchText)) {
                $filtered = array();
                foreach ($allGifts as $giftId => $gift) {
                    if (stripos($gift['name'], $searchText) !== false || 
                        (isset($gift['giftType']) && stripos($gift['giftType'], $searchText) !== false)) {
                        $filtered[$giftId] = $gift;
                    }
                }
                $data['gifts'] = $filtered;
            } else {
                $data['gifts'] = $allGifts;
            }

            $this->global['pageTitle'] = 'StreamAdmin : Gifts Management';
            $this->loadViews("gifts/gifts", $this->global, $data, NULL);
        }
    }

    /**
     * Add new gift page
     */
    public function addGift()
    {
        if (!$this->canAccessGifts() && !$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->global['pageTitle'] = 'StreamAdmin : Add Gift';
            $this->loadViews("gifts/addGift", $this->global, NULL, NULL);
        }
    }

    /**
     * Add new gift submission
     */
    public function addNewGift()
    {
        if (!$this->canAccessGifts() && !$this->isAdmin()) {
            echo json_encode(array('status' => 'access'));
        } else {
            $this->form_validation->set_rules('name', 'Gift Name', 'trim|required|max_length[100]');
            $this->form_validation->set_rules('giftType', 'Gift Type', 'trim|required|max_length[100]');
            $this->form_validation->set_rules('value', 'Coin Value', 'trim|required|numeric|greater_than[0]');

            if ($this->form_validation->run() == FALSE) {
                $this->session->set_flashdata('error', validation_errors());
                redirect('gifts/addGift');
            } else {
                $name = $this->security->xss_clean($this->input->post('name'));
                $giftType = $this->security->xss_clean($this->input->post('giftType'));
                $value = $this->input->post('value');

                // Handle image upload to Firebase Storage
                $imageUrl = '';
                if (!empty($_FILES['image']['name']) && !empty($_FILES['image']['tmp_name'])) {
                    // Validate file type
                    $allowed_types = array('gif', 'jpg', 'jpeg', 'png', 'webp');
                    $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                    
                    if (!in_array($file_ext, $allowed_types)) {
                        $this->session->set_flashdata('error', 'Invalid file type. Only GIF, JPG, JPEG, PNG, and WEBP are allowed.');
                        redirect('gifts/addGift');
                        return;
                    }

                    // Validate file size (5MB max)
                    if ($_FILES['image']['size'] > 5242880) {
                        $this->session->set_flashdata('error', 'File size exceeds 5MB limit.');
                        redirect('gifts/addGift');
                        return;
                    }

                    try {
                        $firebase = $this->firebase->init();
                        $storage = $firebase->createStorage();
                        $defaultBucket = $storage->getBucket();

                        $uploadedFile = $defaultBucket->upload(
                            file_get_contents($_FILES['image']['tmp_name']),
                            [
                                'name' => "gifts/" . time() . "_" . $_FILES['image']['name']
                            ]
                        );

                        $imageUrl = $uploadedFile->info()['mediaLink'];
                    } catch (Exception $e) {
                        $this->session->set_flashdata('error', 'Failed to upload image: ' . $e->getMessage());
                        redirect('gifts/addGift');
                        return;
                    }
                }

                $giftData = array(
                    'name' => $name,
                    'giftType' => $giftType,
                    'value' => (int)$value,
                    'image' => $imageUrl,
                    'timestamp' => time() * 1000
                );

                $result = $this->gifts_model->add_gift($giftData);

                if ($result) {
                    $this->session->set_flashdata('success', 'Gift added successfully');
                } else {
                    $this->session->set_flashdata('error', 'Failed to add gift');
                }

                redirect('gifts');
            }
        }
    }

    /**
     * Edit gift page
     */
    public function editGift($giftId = NULL)
    {
        if (!$this->canAccessGifts() && !$this->isAdmin()) {
            $this->loadThis();
        } else {
            if (empty($giftId)) {
                redirect('gifts');
            }

            $giftInfo = $this->gifts_model->get_gift_by_id($giftId);

            if (empty($giftInfo)) {
                $this->session->set_flashdata('error', 'Gift not found');
                redirect('gifts');
            }

            $data['giftInfo'] = $giftInfo;
            $data['giftId'] = $giftId;

            $this->global['pageTitle'] = 'StreamAdmin : Edit Gift';
            $this->loadViews("gifts/editGift", $this->global, $data, NULL);
        }
    }

    /**
     * Update gift
     */
    public function updateGift()
    {
        if (!$this->canAccessGifts() && !$this->isAdmin()) {
            echo json_encode(array('status' => 'access'));
        } else {
            $giftId = $this->input->post('giftId');
            
            $this->form_validation->set_rules('name', 'Gift Name', 'trim|required|max_length[100]');
            $this->form_validation->set_rules('giftType', 'Gift Type', 'trim|required|max_length[100]');
            $this->form_validation->set_rules('value', 'Coin Value', 'trim|required|numeric|greater_than[0]');

            if ($this->form_validation->run() == FALSE) {
                $this->session->set_flashdata('error', validation_errors());
                redirect('gifts/editGift/' . $giftId);
            } else {
                $name = $this->security->xss_clean($this->input->post('name'));
                $giftType = $this->security->xss_clean($this->input->post('giftType'));
                $value = $this->input->post('value');

                $giftData = array(
                    'name' => $name,
                    'giftType' => $giftType,
                    'value' => (int)$value
                );

                // Handle image upload to Firebase Storage
                if (!empty($_FILES['image']['name']) && !empty($_FILES['image']['tmp_name'])) {
                    // Validate file type
                    $allowed_types = array('gif', 'jpg', 'jpeg', 'png', 'webp');
                    $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                    
                    if (!in_array($file_ext, $allowed_types)) {
                        $this->session->set_flashdata('error', 'Invalid file type. Only GIF, JPG, JPEG, PNG, and WEBP are allowed.');
                        redirect('gifts/editGift/' . $giftId);
                        return;
                    }

                    // Validate file size (5MB max)
                    if ($_FILES['image']['size'] > 5242880) {
                        $this->session->set_flashdata('error', 'File size exceeds 5MB limit.');
                        redirect('gifts/editGift/' . $giftId);
                        return;
                    }

                    try {
                        $firebase = $this->firebase->init();
                        $storage = $firebase->createStorage();
                        $defaultBucket = $storage->getBucket();

                        $uploadedFile = $defaultBucket->upload(
                            file_get_contents($_FILES['image']['tmp_name']),
                            [
                                'name' => "gifts/" . time() . "_" . $_FILES['image']['name']
                            ]
                        );

                        $giftData['image'] = $uploadedFile->info()['mediaLink'];
                    } catch (Exception $e) {
                        $this->session->set_flashdata('error', 'Failed to upload image: ' . $e->getMessage());
                        redirect('gifts/editGift/' . $giftId);
                        return;
                    }
                }

                $result = $this->gifts_model->update_gift($giftId, $giftData);

                if ($result) {
                    $this->session->set_flashdata('success', 'Gift updated successfully');
                } else {
                    $this->session->set_flashdata('error', 'Failed to update gift');
                }

                redirect('gifts');
            }
        }
    }

    /**
     * Delete gift (AJAX)
     */
    public function deleteGift()
    {
        if (!$this->canAccessGifts() && !$this->isAdmin()) {
            echo json_encode(array('status' => 'access'));
        } else {
            $giftId = $this->input->post('giftId');

            if (empty($giftId)) {
                echo json_encode(array('status' => FALSE, 'message' => 'Invalid gift ID'));
                return;
            }

            $result = $this->gifts_model->delete_gift($giftId);

            if ($result) {
                echo json_encode(array('status' => TRUE, 'message' => 'Gift deleted successfully'));
            } else {
                echo json_encode(array('status' => FALSE, 'message' => 'Failed to delete gift'));
            }
        }
    }
}

