<?php

namespace App\Controllers\Admin;

use CodeIgniter\RESTful\ResourceController;
use App\Models\ProfileModel;

class ProfileController extends ResourceController
{
    protected $modelName = 'App\Models\ProfileModel';
    protected $format    = 'json';

    public function index()
    {
        helper('text');
        $search = $this->request->getGet('search');
        $filter = $this->request->getGet('filter');
        $sort = $this->request->getGet('sort') ?? 'id';
        $order = $this->request->getGet('order') ?? 'DESC';

        $model = new ProfileModel();

        if ($search) {
            if (strlen($search) >= 3) {
                $model->groupStart()
                    ->like('full_name', $search)
                    ->orLike('bio', $search)
                ->groupEnd();
            } else {
                session()->setFlashdata('warning', 'Kata kunci pencarian minimal 3 karakter.');
            }
        }

        // Apply Filter
        if ($filter == 'has_photo') {
            $model->where('photo IS NOT NULL')->where('photo !=', '');
        } elseif ($filter == 'no_photo') {
            $model->groupStart()
                ->where('photo', null)
                ->orWhere('photo', '')
            ->groupEnd();
        }

        $data = [
            'profiles' => $model->orderBy($sort, $order)->paginate(10),
            'pager' => $model->pager,
            'search' => $search,
            'filter' => $filter,
            'sort' => $sort,
            'order' => $order,
            'title' => 'Daftar Profil'
        ];

        return view('admin/profile/index', $data);
    }

    public function new()
    {
        return view('admin/profile/form', ['title' => 'Add Profile']);
    }

    public function create()
    {
        $rules = [
            'full_name' => 'required',
            'email' => 'required|valid_email',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $data = $this->request->getPost();
        
        // Handle Photo Upload
        $photo = $this->request->getFile('photo');
        if ($photo && $photo->isValid() && !$photo->hasMoved()) {
            $newName = $photo->getRandomName();
            $photo->move(FCPATH . 'uploads/photos', $newName);
            $data['photo'] = 'uploads/photos/' . $newName;
        }

        $this->model->insert($data);
        return redirect()->to('/admin/profile')->with('message', 'Profile created successfully');
    }

    public function edit($id = null)
    {
        $data = [
            'profile' => $this->model->find($id),
            'title' => 'Edit Profile'
        ];
        return view('admin/profile/form', $data);
    }

    public function update($id = null)
    {
        $rules = [
            'full_name' => 'required',
            'email' => 'required|valid_email',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $data = $this->request->getPost();

        // Handle Photo Upload
        $photo = $this->request->getFile('photo');
        if ($photo && $photo->isValid() && !$photo->hasMoved()) {
            $newName = $photo->getRandomName();
            $photo->move(FCPATH . 'uploads/photos', $newName);
            $data['photo'] = 'uploads/photos/' . $newName;
        }

        $this->model->update($id, $data);
        return redirect()->to('/admin/profile')->with('message', 'Profile updated successfully');
    }

    public function delete($id = null)
    {
        $this->model->delete($id);
        return redirect()->to('/admin/profile')->with('message', 'Profile deleted successfully');
    }
}
