<?php

namespace App\Controllers\View;

use App\Models\EventModel;
use App\Models\EventChargesModel;
use App\Models\UserModel;
use App\Models\StudentModel;
use App\Models\ConfigurationModel;
use App\Models\EnrollmentModel;
use App\Controllers\View\InvoiceController;
use CodeIgniter\RESTful\ResourceController;

class EventController extends ResourceController
{
    protected $eventChargesModel;
    protected $studentModel;
    protected $userModel;
    protected $configModel;
    protected $eventModel;
    protected $invoiceController;
    protected $schoolYear;
    protected $semester;
    protected $categories;
    protected $enrollmentModel;

    public function __construct()
    {
        $this->eventChargesModel = new EventChargesModel(); //eventChargesModel
        $this->studentModel = new StudentModel();
        $this->configModel = new ConfigurationModel();
        $this->userModel = new UserModel(); // Add this
        $this->eventModel = new EventModel();
        $this->invoiceController = new InvoiceController();
        $this->enrollmentModel = new EnrollmentModel();

        $this->schoolYear = $this->configModel->getConfig('school_year');
        $this->semester = $this->configModel->getConfig('semester');
        $this->categories = [
            'workshops',
            'orientations',
            'field trips',
            'Ramadan programs',
        ];
    }

    public function index()
    {
        $eventModel = new EventModel();

        $today = local_date(utc_now(), 'Y-m-d');

        // Fetch all events
        $events = $eventModel
            ->orderBy('created_at', 'DESC')
            ->findAll();

        // Fetch active events (not expired)
        $activeEventCount = $eventModel
            ->where('expiration_date >=', $today)
            ->countAllResults();

        return view('administrator/events/event_list', [
            'events' => $events,
            'activeEventCount' => $activeEventCount
        ]);
    }


    public function create()
    {
        helper(['form']);
        if (strtolower($this->request->getMethod()) === 'post') {
            $file = $this->request->getFile('flyer');
            $flyerPath = null;

            if ($file && $file->isValid() && !$file->hasMoved()) {
                // Move to public/uploads/event_flyers
                $newName = $file->getRandomName();
                $file->move(FCPATH . 'uploads/event_flyers', $newName);
                $flyerPath = 'event_flyers/' . $newName; // store relative path
            }

            $eventId = $this->eventModel->insert([
                'event_name' => $this->request->getPost('event_name'),
                'event_category' => $this->request->getPost('event_category'),
                'description' => $this->request->getPost('description'),
                'amount' => $this->request->getPost('amount'),
                'flyer' => $flyerPath,
                'expiration_date' => $this->request->getPost('expiration_date'),
                'semester' => $this->request->getPost('semester'),
                'school_year' => $this->request->getPost('school_year'),
                'created_by' => session()->get('user_id'),
            ]);

            if ($eventId) {
                $amount = (float) $this->request->getPost('amount');
                $semester = (string) $this->request->getPost('semester');
                $schoolYear = (string) $this->request->getPost('school_year');
                $userId = (int) (session()->get('user_id') ?? 0);

                $enrollments = $this->enrollmentModel
                    ->select('enrollments.student_id, students.parent_id')
                    ->join('students', 'students.id = enrollments.student_id', 'left')
                    ->where('enrollments.school_year', $schoolYear)
                    ->whereIn('enrollments.enrollment_status', ['enrolled', 'payment pending'])
                    ->findAll();

                $parentIds = [];
                foreach ($enrollments as $row) {
                    $studentId = (int) ($row['student_id'] ?? 0);
                    $parentId = (int) ($row['parent_id'] ?? 0);
                    if ($studentId <= 0 || $parentId <= 0) {
                        continue;
                    }

                    $exists = $this->eventChargesModel
                        ->where('event_id', $eventId)
                        ->where('student_id', $studentId)
                        ->where('school_year', $schoolYear)
                        ->where('semester', $semester)
                        ->first();

                    if ($exists) {
                        continue;
                    }

                    $this->eventChargesModel->insert([
                        'event_id' => $eventId,
                        'parent_id' => $parentId,
                        'student_id' => $studentId,
                        'participation' => 'yes',
                        'charged' => $amount,
                        'school_year' => $schoolYear,
                        'semester' => $semester,
                        'updated_by' => $userId ?: null,
                    ]);

                    $parentIds[] = $parentId;
                }

                $parentIds = array_unique($parentIds);
                foreach ($parentIds as $pid) {
                    $this->invoiceController->generateInvoice((string) $pid);
                }
            }

            return redirect()->to('/administrator/events')->with('success', 'Event created successfully');
        }

        return view('administrator/events/create_event', [
            'categories' => $this->categories,
        ]);
    }


    public function edit($id = null)
    {
        helper(['form']);
        $event = $this->eventModel->find($id);

        if (!$event) {
            return redirect()->to('/administrator/events')->with('error', 'Event not found');
        }

        if (strtolower($this->request->getMethod()) === 'post') {
            log_message('debug', 'POST detected');
            $file = $this->request->getFile('flyer');
            $flyerPath = $event['flyer']; // Default: keep old flyer

            if ($file && $file->isValid() && !$file->hasMoved()) {
                $newName = $file->getRandomName();
                $file->move(FCPATH . 'uploads/event_flyers', $newName);
                $flyerPath = 'event_flyers/' . $newName; // store relative path
            }

            $updated = $this->eventModel->update($id, [
                'event_name' => $this->request->getPost('event_name'),
                'event_category' => $this->request->getPost('event_category'),
                'description' => $this->request->getPost('description'),
                'amount' => $this->request->getPost('amount'),
                'flyer' => $flyerPath,
                'expiration_date' => $this->request->getPost('expiration_date'),
                'semester' => $this->request->getPost('semester'),
                'school_year' => $this->request->getPost('school_year'),
            ]);

            if ($updated) {
                return redirect()->to('/administrator/events')->with('success', 'Event updated successfully');
            } else {
                log_message('debug', 'GET detected');
                return redirect()->back()->with('error', 'Failed to update event');
            }
        }

        return view('administrator/events/edit_event', [
            'event' => $event,
            'categories' => $this->categories,
        ]);
    }


    public function delete($id = null)
    {

        $event = $this->eventModel->find($id);

        if (!$event) {
            return redirect()->to('/administrator/events')->with('error', 'Event not found');
        }

        // Delete related charges and collect parent IDs
        $charges = $this->eventChargesModel->where('event_id', $id)->findAll();
        $parentIds = [];        

        foreach ($charges as $charge) {
            $this->eventChargesModel->delete($charge['id']);
            $parentIds[] = $charge['parent_id'];
        }

        // Delete event
        $this->eventModel->delete($id);
        
        $parentIds = array_unique($parentIds);

        foreach ($parentIds as $parentId) {
            $this->invoiceController->generateInvoice($parentId);
        }

        return redirect()->to('/administrator/events')->with('success', 'Event, charges, and invoices updated.');
    }


    // Optionally keep your eventShow / eventUpdate for legacy administrator event charges
    public function eventShow()
    {

        $schoolYear = $this->request->getGet('school_year') ?? $this->schoolYear;
        $semester = $this->request->getGet('semester') ?? $this->semester;

        $parents = $this->userModel->getParents();
        $events = $this->eventModel->getActiveEvents($this->schoolYear);

        $charges = $this->eventChargesModel
            ->select('event_charges.*, 
                    users.firstname AS parent_firstname, users.lastname AS parent_lastname, 
                    students.firstname AS student_firstname, students.lastname AS student_lastname,
                    events.event_name')
            ->join('users', 'users.id = event_charges.parent_id', 'left')
            ->join('students', 'students.id = event_charges.student_id', 'left')
            ->join('events', 'events.id = event_charges.event_id', 'left')
            ->where('event_charges.school_year', $schoolYear)
            ->where('event_charges.semester', $semester)
            ->orderBy('event_charges.created_at', 'DESC')
            ->findAll();

        return view('administrator/events/event_charges', [
            'charges' => $charges,
            'parents' => $parents,
            'events'  => $events,
            'school_year' => $schoolYear,
            'semester' => $semester,
        ]);
    }


    public function eventUpdate()
    {
        $schoolYear = $this->request->getPost('school_year') ?? $this->schoolYear;
        $semester = $this->request->getPost('semester') ?? $this->semester;

        $parentId = $this->request->getPost('parent_id');
        $eventId = $this->request->getPost('event_id');
        $participations = $this->request->getPost('participation') ?? [];

        if (!$parentId || !$eventId || empty($participations)) {
            return redirect()->back()->with('error', 'Missing required information.');
        }

        $userId = session()->get('user_id');
        $event = $this->eventModel->getEvent($eventId, $schoolYear);

        foreach ($participations as $studentId => $value) {
            $existing = $this->eventChargesModel->where([
                'parent_id' => $parentId,
                'student_id' => $studentId,
                'event_id' => $eventId,
                'school_year' => $schoolYear,
                'semester' => $semester
            ])->first();

            if ($value === 'no') {
                if ($existing) {
                    $this->eventChargesModel->delete($existing['id']);
                }
                continue;
            }

            // value is 'yes'
            if ($existing) {
                $this->eventChargesModel->update($existing['id'], [
                    'participation' => 'yes',
                    'charged'       => $event['amount'],
                    'updated_by'    => $userId
                ]);
            } else {
                $this->eventChargesModel->insert([
                    'parent_id'     => $parentId,
                    'student_id'    => $studentId,
                    'event_id'      => $eventId,
                    'participation' => 'yes',
                    'charged'       => $event['amount'],
                    'school_year'   => $schoolYear,
                    'semester'      => $semester,
                    'created_by'    => $userId,
                    'updated_by'    => $userId
                ]);
            }
        }

        $this->invoiceController->generateInvoice($parentId);

        return redirect()->back()->with('success', 'Event charges updated successfully.');
    }




    public function getStudentsWithCharges()
    {
        $parentId = $this->request->getGet('parent_id');
        $semester = $this->request->getGet('semester');
        $schoolYear = $this->request->getGet('school_year');

        // Get students for parent
        $students = $this->studentModel->where('parent_id', $parentId)->findAll();

        // Get student_ids that already have charges
        $chargedStudentIds = $this->eventChargesModel
            ->where('parent_id', $parentId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->groupBy('student_id')
            ->select('student_id')
            ->findColumn('student_id');

        $data = [];
        foreach ($students as $student) {
            $data[] = [
                'id' => $student['id'],
                'name' => $student['firstname'] . ' ' . $student['lastname'],
                'charged' => in_array($student['id'], $chargedStudentIds ?? []),
            ];
        }

        return $this->response->setJSON($data);
    }


}
