<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\ActivityModel;

class AdminActivities extends BaseController
{
    protected $activityModel;

    public function __construct()
    {
        $this->activityModel = new ActivityModel();
    }

    public function index()
    {
        $data = [
            'title' => 'Manajemen Aktivitas',
            'activities' => $this->activityModel->orderBy('created_at', 'DESC')->findAll()
        ];
        return view('admin/activities/index', $data);
    }

    public function create()
    {
        $data = [
            'title' => 'Tambah Aktivitas Baru',
            'validation' => \Config\Services::validation()
        ];
        return view('admin/activities/create', $data);
    }

    public function store()
    {
        // Validation
        if (
            !$this->validate([
                'title' => 'required',
                'date_activity' => 'required',
                'time_activity' => 'required',
                'image' => [
                    'rules' => 'uploaded[image]|max_size[image,2048]|is_image[image]|mime_in[image,image/jpg,image/jpeg,image/png]',
                    'errors' => [
                        'uploaded' => 'Pilih gambar terlebih dahulu',
                        'max_size' => 'Ukuran gambar terlalu besar',
                        'is_image' => 'File bukan gambar',
                        'mime_in' => 'File bukan gambar'
                    ]
                ]
            ])
        ) {
            return redirect()->to(base_url('admin/activities/create'))->withInput();
        }

        // Image Upload
        $fileImage = $this->request->getFile('image');
        if ($fileImage->isValid() && !$fileImage->hasMoved()) {
            $imageName = $fileImage->getRandomName();
            $fileImage->move('uploads/activities', $imageName);
        }

        $this->activityModel->save([
            'title' => $this->request->getPost('title'),
            'description' => $this->request->getPost('description'),
            'date_activity' => $this->request->getPost('date_activity'),
            'time_activity' => $this->request->getPost('time_activity'),
            'image' => $imageName
        ]);

        return redirect()->to(base_url('admin/activities'))->with('success', 'Aktivitas berhasil ditambahkan');
    }

    public function edit($id)
    {
        $data = [
            'title' => 'Edit Aktivitas',
            'activity' => $this->activityModel->find($id),
            'validation' => \Config\Services::validation()
        ];
        return view('admin/activities/edit', $data);
    }

    public function update($id)
    {
        // Validation (Image optional here)
        $rules = [
            'title' => 'required',
            'date_activity' => 'required',
            'time_activity' => 'required',
        ];

        // Check if image is uploaded
        $fileImage = $this->request->getFile('image');
        if ($fileImage && $fileImage->isValid() && !$fileImage->hasMoved()) {
            $rules['image'] = 'max_size[image,2048]|is_image[image]|mime_in[image,image/jpg,image/jpeg,image/png]';
        }

        if (!$this->validate($rules)) {
            return redirect()->to(base_url('admin/activities/edit/' . $id))->withInput();
        }

        $data = [
            'id' => $id,
            'title' => $this->request->getPost('title'),
            'description' => $this->request->getPost('description'),
            'date_activity' => $this->request->getPost('date_activity'),
            'time_activity' => $this->request->getPost('time_activity'),
        ];

        // Handle Image Update
        if ($fileImage && $fileImage->isValid() && !$fileImage->hasMoved()) {
            $imageName = $fileImage->getRandomName();
            $fileImage->move('uploads/activities', $imageName);
            $data['image'] = $imageName;

            // Optional: delete old image
            // $oldImage = $this->activityModel->find($id)['image'];
            // if(file_exists('uploads/activities/' . $oldImage)) unlink('uploads/activities/' . $oldImage);
        }

        $this->activityModel->save($data);
        return redirect()->to(base_url('admin/activities'))->with('success', 'Aktivitas berhasil diperbarui');
    }

    public function delete($id)
    {
        $this->activityModel->delete($id);
        // Optional: delete image file
        return redirect()->to(base_url('admin/activities'))->with('success', 'Aktivitas berhasil dihapus');
    }
}
