<?php

namespace App\Controllers\API;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Libraries\ResponseFormatter;

class UserController extends BaseController
{
    protected $userModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
    }

    // 📌 GET ALL USERS
    public function index()
    {
        $users = $this->userModel->findAll();

        // 🔥 hapus password sebelum dikirim
        foreach ($users as &$user) {
            unset($user['password']);
        }

        return $this->response->setJSON(
            ResponseFormatter::success($users)
        );
    }

    // ➕ CREATE USER
    public function create()
    {
        $input = $this->request->getJSON(true);

        $this->userModel->insert([
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => password_hash($input['password'], PASSWORD_DEFAULT),
            'role' => $input['role'] ?? 'kasir',
            'phone' => $input['phone'] ?? null,
        ]);

        return $this->response->setJSON(
            ResponseFormatter::success(null, 'User berhasil ditambahkan')
        );
    }

    // ✏️ UPDATE USER (TANPA PASSWORD)
    public function update($id)
    {
        $input = $this->request->getJSON(true);

        $this->userModel->update($id, [
            'name' => $input['name'],
            'email' => $input['email'],
            'role' => $input['role'],
            'phone' => $input['phone'] ?? null,
        ]);

        return $this->response->setJSON(
            ResponseFormatter::success(null, 'User berhasil diupdate')
        );
    }

    // ❌ DELETE USER
    public function delete($id)
    {
        $this->userModel->delete($id);

        return $this->response->setJSON(
            ResponseFormatter::success(null, 'User berhasil dihapus')
        );
    }

    // 🔐 CHANGE PASSWORD
    public function changePassword($id)
    {
        $input = $this->request->getJSON(true);

        if (empty($input['password'])) {
            return $this->response->setJSON(
                ResponseFormatter::error('Password wajib diisi', 400)
            );
        }

        $this->userModel->update($id, [
            'password' => password_hash($input['password'], PASSWORD_DEFAULT),
        ]);

        return $this->response->setJSON(
            ResponseFormatter::success(null, 'Password berhasil diubah')
        );
    }
}