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

class SponsorController extends CI_Controller
{
    private $table = 'sponsors';

    public function __construct()
    {
        parent::__construct();
        $this->load->library(['session', 'firebase']);
        $this->load->model('admin/Setting_model');
        $this->load->helper(['url', 'auth']);
        check_admin();
    }
    public function index()
    {
        $data['sponsors'] = $this->Setting_model->getSponsors();



        $data['page_title'] = 'sponsors';
        $data['active_menu'] = 'sponsors';
        $data['content_view'] = 'admin/pages/sponsors';
        $this->load->view('admin/layouts/main', $data);
    }
    public function deleteSponsor($id)
    {
        if (!$id) {
            echo json_encode([
                'success' => false,
                'message' => 'Invalid sponsor ID'
            ]);
            return;
        }

        $deleted = $this->Setting_model->deleteSponsor($id);

        if ($deleted) {
            echo json_encode([
                'success' => true,
                'message' => 'Sponsor deleted successfully'
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Failed to delete sponsor'
            ]);
        }
    }


    public function addSponsor()
    {
        if ($this->input->method() !== 'post') {
            echo json_encode(['success' => false, 'message' => 'Invalid request method']);
            return;
        }

        $name = $this->input->post('name', true);
        $url  = $this->input->post('url', true);

        // Upload image to Firebase Storage
        $imageUrl = '';
        if (!empty($_FILES['image']['name'])) {
            $fileTmp = $_FILES['image']['tmp_name'];
            $fileName = 'sponsors/' . time() . '_' . $_FILES['image']['name'];

            $uploadedUrl = $this->firebase->uploadFile($fileTmp, $fileName);
            if (!$uploadedUrl) {
                echo json_encode(['success' => false, 'message' => 'Failed to upload image to Firebase']);
                return;
            }
            $imageUrl = $uploadedUrl;
        }

        $timestamp = round(microtime(true) * 1000); // milliseconds

        $data = [
            'name'        => $name,
            'url'         => $url,
            'imageurl'    => $imageUrl,
            'createdDate' => $timestamp,
            'updated_at'  => $timestamp
        ];

        $saved = $this->Setting_model->addSponsor($data);

        if ($saved) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to save sponsor']);
        }
    }
}
