<?php

namespace App\Controllers\API;

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

class CustomerController extends BaseController
{
    protected $customerModel;

    public function __construct()
    {
        $this->customerModel = new CustomerModel();
    }

    // 📌 GET ALL CUSTOMERS
public function index()
{
    $keyword = $this->request->getGet('search');

    $builder = $this->customerModel;

    if ($keyword) {
        $builder = $builder->like('name', $keyword);
    }

    $customers = $builder->orderBy('id', 'DESC')->findAll();

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

    // 📌 CREATE CUSTOMER (optional, tapi bagus ada)
    public function create()
{
    try {
        $input = $this->request->getJSON(true);

        if (!$input) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'Input kosong'
            ]);
        }

        $this->customerModel->insert($input);

        return $this->response->setJSON([
            'status' => true,
            'data' => $input
        ]);

    } catch (\Throwable $e) {
        return $this->response->setJSON([
            'status' => false,
            'error' => $e->getMessage()
        ]);
    }
}

public function update($id)
{
    $input = $this->request->getJSON(true);

    $this->customerModel->update($id, $input);

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

public function delete($id)
{
    $this->customerModel->delete($id);

    return $this->response->setJSON(
        ResponseFormatter::success(null, 'Customer berhasil dihapus')
    );
}
public function deleted()
{
    $keyword = $this->request->getGet('search');

    $builder = $this->customerModel->onlyDeleted();

    if ($keyword) {
        $builder = $builder->like('name', $keyword);
    }

    $customers = $builder->findAll();

    return $this->response->setJSON(
        ResponseFormatter::success($customers)
    );
}
public function restore($id)
{
   $this->customerModel->protect(false)
    ->withDeleted()
    ->set(['deleted_at' => null])
    ->where('id', $id)
    ->update();

    return $this->response->setJSON([
        'status' => true,
        'message' => 'Customer berhasil dikembalikan'
    ]);
}
}