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

class RequestController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->library('firebase');
        $this->load->helper('url');
        $this->load->model('admin/Request_model');
        $this->load->model('admin/Content_model');
    }


    public function index()
    {
        $scratch = $this->Request_model->getAllScratch();

        $eventNames = [];

        // Separate scratch items by type
        $addScratch = [];
        $scratchItems = [];

        foreach ($scratch as $id => $s) {
            $eventId = $s['eventId'] ?? null;
            $event = $this->firebase->getDocument('events', $eventId);
            $scratch[$id]['event_name'] = $event['event_name'] ?? 'N/A';

            // Separate by scratchType
            $scratchType = $scratch[$id]['scratchType'] ?? 'Add';

            if ($scratchType === 'Add') {
                $addScratch[$id] = $scratch[$id];
            } else {
                $scratchItems[$id] = $scratch[$id];
            }

            if ($scratch[$id]['event_name'] !== 'N/A' && !in_array($scratch[$id]['event_name'], $eventNames)) {
                $eventNames[] = $scratch[$id]['event_name'];
            }
        }

        // Sort both arrays by date (newest first)
        uasort($addScratch, fn($a, $b) => ($b['createdDate'] ?? 0) <=> ($a['createdDate'] ?? 0));
        uasort($scratchItems, fn($a, $b) => ($b['createdDate'] ?? 0) <=> ($a['createdDate'] ?? 0));

        // Sort event names A-Z
        sort($eventNames);

        $data['add_scratch'] = $addScratch;
        $data['scratch_items'] = $scratchItems;
        $data['event_names'] = $eventNames;
        $data['page_title'] = 'Requests';
        $data['active_menu'] = 'requests';
        $data['content_view'] = 'admin/pages/requests';

        $this->load->view('admin/layouts/main', $data);
    }
}
