564 lines
20 KiB
PHP
564 lines
20 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers\View;
|
|
|
|
use App\Models\EventModel;
|
|
use App\Models\EventChargesModel;
|
|
use App\Models\UserModel;
|
|
use App\Models\StudentModel;
|
|
use App\Models\StudentClassModel;
|
|
use App\Models\ConfigurationModel;
|
|
use App\Models\EnrollmentModel;
|
|
use App\Models\InvoiceModel;
|
|
use App\Models\InvoiceEventModel;
|
|
use App\Models\ClassSectionModel;
|
|
use App\Models\PaymentModel;
|
|
#use ???
|
|
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 $invoiceModel;
|
|
protected $invoiceEventModel;
|
|
protected $studentClassModel;
|
|
protected $classSectionModel;
|
|
protected $paymentModel;
|
|
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->invoiceModel = new InvoiceModel();
|
|
$this->invoiceEventModel = new InvoiceEventModel();
|
|
$this->studentClassModel = new StudentClassModel();
|
|
$this->classSectionModel = new ClassSectionModel();
|
|
$this->paymentModel = new PaymentModel();
|
|
$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'),
|
|
]);
|
|
|
|
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'];
|
|
}
|
|
|
|
// Also remove any invoice_event rows tied to this event
|
|
$eventName = $event['event_name'] ?? null;
|
|
if ($eventName) {
|
|
$builder = $this->invoiceEventModel->where('event_name', $eventName);
|
|
if (!empty($event['school_year'])) {
|
|
$builder->where('school_year', $event['school_year']);
|
|
}
|
|
if (!empty($event['semester'])) {
|
|
$builder->where('semester', $event['semester']);
|
|
}
|
|
$builder->delete();
|
|
}
|
|
|
|
// 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);
|
|
$filterEventId = (int) ($this->request->getGet('event_id') ?? 0);
|
|
$filterParentId = (int) ($this->request->getGet('parent_id') ?? 0);
|
|
|
|
$chargesBuilder = $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, events.description AS event_description, events.amount AS event_amount')
|
|
->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);
|
|
|
|
if ($filterEventId > 0) {
|
|
$chargesBuilder->where('event_charges.event_id', $filterEventId);
|
|
}
|
|
|
|
$charges = $chargesBuilder
|
|
->orderBy('event_charges.created_at', 'DESC')
|
|
->findAll();
|
|
|
|
foreach ($charges as &$charge) {
|
|
if (empty($charge['class_section_id']) && !empty($charge['student_id'])) {
|
|
$sections = $this->studentClassModel->getClassSectionIdsByStudentId(
|
|
(int)$charge['student_id'],
|
|
$schoolYear
|
|
);
|
|
if (!empty($sections)) {
|
|
$charge['class_section_id'] = $sections[0];
|
|
}
|
|
}
|
|
}
|
|
unset($charge);
|
|
|
|
$parentBalances = [];
|
|
try {
|
|
$balanceRows = $this->invoiceModel
|
|
->select('parent_id, COALESCE(SUM(balance),0) AS total_balance')
|
|
->where('school_year', $schoolYear)
|
|
->where('semester', $semester)
|
|
->groupBy('parent_id')
|
|
->findAll();
|
|
|
|
foreach ($balanceRows as $row) {
|
|
$parentBalances[(int)($row['parent_id'] ?? 0)] = (float)($row['total_balance'] ?? 0.0);
|
|
}
|
|
} catch (\Throwable $e) {
|
|
log_message('error', 'Failed to load parent balances: ' . $e->getMessage());
|
|
}
|
|
|
|
$sectionIds = array_unique(array_filter(array_column($charges, 'class_section_id')));
|
|
$classSectionNames = [];
|
|
if (!empty($sectionIds)) {
|
|
$sections = $this->classSectionModel
|
|
->select('class_section_id, class_section_name')
|
|
->whereIn('class_section_id', $sectionIds)
|
|
->findAll();
|
|
foreach ($sections as $section) {
|
|
$classSectionNames[(int)($section['class_section_id'] ?? 0)] = $section['class_section_name'] ?? '';
|
|
}
|
|
}
|
|
|
|
$semesterOptions = (new EventChargesModel())
|
|
->select('semester')
|
|
->distinct()
|
|
->orderBy('semester', 'ASC')
|
|
->findColumn('semester');
|
|
$semesterOptions = array_values(array_filter(array_unique($semesterOptions ?? [])));
|
|
if (empty($semesterOptions)) {
|
|
$semesterOptions = [$this->semester];
|
|
}
|
|
|
|
$schoolYearOptions = (new EventChargesModel())
|
|
->select('school_year')
|
|
->distinct()
|
|
->orderBy('school_year', 'ASC')
|
|
->findColumn('school_year');
|
|
$schoolYearOptions = array_values(array_filter(array_unique($schoolYearOptions ?? [])));
|
|
if (empty($schoolYearOptions)) {
|
|
$schoolYearOptions = [$this->schoolYear];
|
|
}
|
|
|
|
return view('administrator/events/event_charges', [
|
|
'charges' => $charges,
|
|
'parents' => $parents,
|
|
'events' => $events,
|
|
'school_year' => $schoolYear,
|
|
'semester' => $semester,
|
|
'filterEventId' => $filterEventId,
|
|
'filterParentId' => $filterParentId,
|
|
'parentBalances' => $parentBalances,
|
|
'classSectionNames' => $classSectionNames,
|
|
'semesterOptions' => $semesterOptions,
|
|
'schoolYearOptions' => $schoolYearOptions,
|
|
]);
|
|
}
|
|
|
|
|
|
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;
|
|
}
|
|
|
|
$sectionIds = $this->studentClassModel->getClassSectionIdsByStudentId($studentId, $schoolYear);
|
|
$classSectionId = !empty($sectionIds) ? $sectionIds[0] : null;
|
|
|
|
if ($existing) {
|
|
$updateData = [
|
|
'participation' => 'yes',
|
|
'updated_by' => $userId,
|
|
'class_section_id'=> $classSectionId,
|
|
];
|
|
if (isset($event['amount']) && ((float)$event['amount'] !== (float)($existing['charged'] ?? 0))) {
|
|
$updateData['charged'] = $event['amount'];
|
|
}
|
|
$this->eventChargesModel->update($existing['id'], $updateData);
|
|
continue;
|
|
} else {
|
|
$this->eventChargesModel->insert([
|
|
'parent_id' => $parentId,
|
|
'student_id' => $studentId,
|
|
'event_id' => $eventId,
|
|
'participation' => 'yes',
|
|
'charged' => $event['amount'],
|
|
'event_paid' => 0,
|
|
'class_section_id' => $classSectionId,
|
|
'school_year' => $schoolYear,
|
|
'semester' => $semester,
|
|
'created_by' => $userId,
|
|
'updated_by' => $userId
|
|
]);
|
|
}
|
|
}
|
|
|
|
$this->invoiceController->generateInvoice($parentId);
|
|
|
|
$this->fixInvoiceStatusAfterCharge($parentId, $schoolYear);
|
|
|
|
return redirect()->back()->with('success', 'Event charges updated successfully.');
|
|
}
|
|
|
|
public function removeCharge($chargeId = null)
|
|
{
|
|
if (!$chargeId) {
|
|
return redirect()->back()->with('error', 'Invalid charge.');
|
|
}
|
|
|
|
$charge = $this->eventChargesModel->find($chargeId);
|
|
if (!$charge) {
|
|
return redirect()->back()->with('error', 'Charge not found.');
|
|
}
|
|
|
|
$paymentId = (int)($charge['event_payment_id'] ?? 0);
|
|
if ($paymentId > 0) {
|
|
$this->paymentModel->delete($paymentId);
|
|
}
|
|
|
|
$this->eventChargesModel->delete($chargeId);
|
|
$this->invoiceController->generateInvoice($charge['parent_id']);
|
|
|
|
return redirect()->back()->with('success', 'Participation removed, invoices updated.');
|
|
}
|
|
|
|
public function toggleEventPayment($chargeId = null)
|
|
{
|
|
if (!$chargeId) {
|
|
return redirect()->back()->with('error', 'Invalid charge.');
|
|
}
|
|
|
|
$charge = $this->eventChargesModel->find($chargeId);
|
|
if (!$charge) {
|
|
return redirect()->back()->with('error', 'Charge not found.');
|
|
}
|
|
|
|
$isPaid = $this->request->getPost('paid') === '1';
|
|
$event = $this->eventModel->find($charge['event_id']);
|
|
$eventAmount = max(0.0, (float)($event['amount'] ?? 0));
|
|
$paymentId = (int)($charge['event_payment_id'] ?? 0);
|
|
|
|
$parentId = $charge['parent_id'];
|
|
$schoolYear = $charge['school_year'] ?? $this->schoolYear;
|
|
|
|
if (!empty($eventAmount)) {
|
|
$invoice = $this->invoiceModel
|
|
->where('parent_id', $parentId)
|
|
->where('school_year', $schoolYear)
|
|
->orderBy('id', 'DESC')
|
|
->first();
|
|
|
|
if (!$invoice) {
|
|
$this->invoiceController->generateInvoice($parentId);
|
|
$invoice = $this->invoiceModel
|
|
->where('parent_id', $parentId)
|
|
->where('school_year', $schoolYear)
|
|
->orderBy('id', 'DESC')
|
|
->first();
|
|
}
|
|
|
|
if ($invoice) {
|
|
if ($isPaid && !$paymentId) {
|
|
$paymentId = $this->createEventPayment($parentId, (int)$invoice['id'], $eventAmount, $schoolYear, $charge['semester'] ?? $this->semester);
|
|
} elseif (!$isPaid && $paymentId > 0) {
|
|
$this->paymentModel->delete($paymentId);
|
|
$paymentId = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
$this->eventChargesModel->update($chargeId, [
|
|
'event_paid' => $isPaid ? 1 : 0,
|
|
'charged' => $eventAmount,
|
|
'event_payment_id' => $paymentId > 0 ? $paymentId : null,
|
|
]);
|
|
|
|
$this->invoiceController->generateInvoice($parentId);
|
|
$this->fixInvoiceStatusAfterCharge($parentId, $schoolYear);
|
|
|
|
return redirect()->back()->with('success', 'Event payment status updated.');
|
|
}
|
|
|
|
|
|
|
|
|
|
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
|
|
$eventId = $this->request->getGet('event_id');
|
|
|
|
$chargesBuilder = $this->eventChargesModel
|
|
->where('parent_id', $parentId)
|
|
->where('semester', $semester)
|
|
->where('school_year', $schoolYear);
|
|
|
|
if (!empty($eventId)) {
|
|
$chargesBuilder->where('event_id', $eventId);
|
|
}
|
|
|
|
$chargedStudentIds = $chargesBuilder
|
|
->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);
|
|
}
|
|
|
|
private function createEventPayment(int $parentId, int $invoiceId, float $amount, string $schoolYear, ?string $semester): ?int
|
|
{
|
|
if ($amount <= 0 || $invoiceId <= 0 || $parentId <= 0) {
|
|
return null;
|
|
}
|
|
|
|
$monthSemester = $semester ?: $this->semester;
|
|
$data = [
|
|
'parent_id' => $parentId,
|
|
'invoice_id' => $invoiceId,
|
|
'total_amount' => $amount,
|
|
'paid_amount' => $amount,
|
|
'balance' => 0.0,
|
|
'number_of_installments' => 1,
|
|
'payment_method' => 'Event charge',
|
|
'payment_date' => utc_now(),
|
|
'school_year' => $schoolYear,
|
|
'semester' => $monthSemester,
|
|
'status' => 'Paid',
|
|
'transaction_id' => $this->paymentModel->generateNewTransactionId(),
|
|
'updated_by' => session()->get('user_id'),
|
|
];
|
|
|
|
if (!$this->paymentModel->insert($data)) {
|
|
log_message('error', 'Failed to insert event payment: ' . json_encode($this->paymentModel->errors()));
|
|
return null;
|
|
}
|
|
|
|
return (int)$this->paymentModel->getInsertID();
|
|
}
|
|
|
|
private function fixInvoiceStatusAfterCharge($parentId, $schoolYear)
|
|
{
|
|
if (!$parentId || !$schoolYear) {
|
|
return;
|
|
}
|
|
|
|
$invoices = $this->invoiceModel
|
|
->where('parent_id', $parentId)
|
|
->where('school_year', $schoolYear)
|
|
->findAll();
|
|
|
|
foreach ($invoices as $invoice) {
|
|
$status = strtolower(trim($invoice['status'] ?? ''));
|
|
$balance = (float)($invoice['balance'] ?? 0.0);
|
|
|
|
if ($balance <= 0.00001 && $status !== 'paid') {
|
|
$this->invoiceModel->update($invoice['id'], ['status' => 'Paid']);
|
|
} elseif ($status === 'paid' && $balance > 0) {
|
|
$this->invoiceModel->update($invoice['id'], ['status' => 'Unpaid']);
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|