<?php

namespace App\Controllers;

use App\Services\UserService;
use App\Core\View;
use App\Interfaces\UserRequest;
use App\Models\StatusAkun;
use App\Models\UserRole;
use App\Services\DivisiService;

final class UserController
{

  private View $view;
  private UserService $userService;
  private DivisiService $divisiService;

  public function __construct()
  {
    $this->view = new View();
    $this->userService = new UserService();
    $this->divisiService = new DivisiService();
  }

  public function index(): void
  {

    $keyword = trim($_GET['keyword'] ?? '');
    $role = trim($_GET['role'] ?? '');
    $divisi = trim($_GET['divisi'] ?? '');
    $statusAkun = trim($_GET['status'] ?? '');

    $hasFilter =
      $keyword !== '' ||
      $role !== '' ||
      $divisi !== '' ||
      $statusAkun !== '';

    if ($hasFilter) {
      $data = $this->userService->findBy(
        $keyword,
        $role,
        $divisi,
        $statusAkun
      );
    } else {
      $data = $this->userService->findAll();
    }

    $divisions = $this->divisiService->findAll();
    $this->view->renderAdminPage('manajemen-user/list', [
      'title' => 'Manajemen User',
      'data' => $data,
      'divisions' => $divisions,
      'totalUser' => count($data)
    ]);
  }

  public function createForm(): void
  {
    $divisions = $this->divisiService->findAll();
    $this->view->renderAdminPage('manajemen-user/tambah', [
      'divisions' => $divisions,
      'title' => 'Tambah User'
    ]);
  }

  public function updateForm(int $id): void
  {
    try {
      $divisions = $this->divisiService->findAll();
      $user = $this->userService->findById($id);
      $this->view->renderAdminPage('manajemen-user/detail', [
        'user' => $user,
        'divisions' => $divisions,
        'title' => 'Ubah User'
      ]);
      exit;
    } catch (\Exception $e) {
      $_SESSION['error'] = 'User tidak ditemukan: ' . $e->getMessage();
      redirect('MANAJEMEN_USER');
      exit;
    }
  }

  public function create(): void
  {
    $divisiId = !empty($_POST['divisiId'])
      ? (int) $_POST['divisiId']
      : null;
    $userRequest = UserRequest::create(
      $_POST['nama'],
      $_POST['username'],
      $_POST['password'],
      $_POST['email'],
      $_POST['noTelepon'],
      UserRole::from($_POST['role']),
      $divisiId,
      StatusAkun::from($_POST['statusAkun']),
      $_POST['spesialisasi']
    );

    try {
      $this->userService->save($userRequest);
      $_SESSION['success'] = 'User berhasil ditambahkan';
      redirect('TAMBAH_USER');
      exit;
    } catch (\Exception $e) {
      $_SESSION['error'] = 'User gagal ditambahkan: ' . $e->getMessage();
      redirect('TAMBAH_USER');
      exit;
    }
  }

  public function update(int $id): void
  {
    $divisiId = !empty($_POST['divisiId'])
      ? (int) $_POST['divisiId']
      : null;

    $userRequest = UserRequest::update(
      $id,
      $_POST['nama'],
      $_POST['username'],
      $_POST['email'],
      $_POST['noTelepon'],
      UserRole::from($_POST['role']),
      $divisiId,
      StatusAkun::from($_POST['statusAkun']),
      $_POST['spesialisasi']
    );

    try {
      $this->userService->update($userRequest);
      $_SESSION['success'] = 'User berhasil diubah';
      redirect('DETAIL_USER', ['id' => $id]);
      exit;
    } catch (\Exception $e) {
      $_SESSION['error'] = 'User gagal diubah: ' . $e->getMessage();
      redirect('DETAIL_USER', ['id' => $id]);
      exit;
    }
  }

  public function changePasswordForm(int $id): void
  {
    $this->view->renderAdminPage('manajemen-user/ubah-password', [
      'user' => $this->userService->findById($id)
    ]);
  }
  public function changePassword(int $id): void
  {
    try {
      $this->userService->changePassword($id, $_POST['password'], $_POST['confirmPassword']);
      $_SESSION['success'] = 'Password berhasil diubah';
      redirect('UBAH_PASSWORD', ['id' => $id]);
      exit;
    } catch (\Exception $e) {
      $_SESSION['error'] = 'Password gagal diubah: ' . $e->getMessage();
      redirect('UBAH_PASSWORD', ['id' => $id]);
      exit;
    }
  }
}
