<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\TransactionModel;
use App\Models\EmailChangeRequestModel;
use App\Libraries\EmailService;

class UsersController extends BaseController
{
    public function index()
    {
        $userModel = new UserModel();
        $filters = [
            'name' => $this->request->getGet('name'),
            'email' => $this->request->getGet('email'),
            'phone_number' => $this->request->getGet('phone_number'),
            'kta_number' => $this->request->getGet('kta_number'),
            'birth_date' => $this->request->getGet('birth_date'),
        ];
        
        $data = [
            'users' => $userModel->search($filters),
            'pager' => $userModel->pager,
            'filters' => $filters,
            'pageTitle' => lang('Admin/Users.pageTitle'),
        ];
        return view('backend/users/index', $data);
    }

    public function edit($id = null)
    {
        $user = (new UserModel())->find($id);
        if (!$user) {
            return redirect()->back()->with('error', lang('Admin/Users.errorNotFound'));
        }
        $data = [
            'user' => $user,
            'pageTitle' => lang('Admin/Users.editUser', [$user->name]),
        ];
        return view('backend/users/edit', $data);
    }

    public function update($id = null)
    {
        $userModel = new UserModel();
        $user = $userModel->find($id);
        if (!$user) {
            return redirect()->back()->with('error', lang('Admin/Users.errorNotFound'));
        }

        // --- Aturan Validasi ---
        $rules = [
            'name'         => 'required|alpha_space|min_length[3]',
            'email'        => "required|valid_email|is_unique[users.email,id,{$id}]",
            'phone_number' => "required|regex_match[/^\+[1-9]\d{1,14}$/]|is_unique[users.phone_number,id,{$id}]",
            'kta_number'   => "permit_empty|is_unique_user_kta_except[{$id}]", // Aturan dasar
            'birth_date'   => 'permit_empty|valid_date',
        ];

        // Terapkan aturan KTA yang kompleks HANYA jika field KTA diisi
        if (!empty($this->request->getPost('kta_number'))) {
            $rules['kta_number'] .= '|validate_kta_and_birthdate[birth_date]';
            $rules['birth_date']  = 'required|valid_date';
        }
        
        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        // Mulai transaksi database untuk memastikan konsistensi
        $db = \Config\Database::connect();
        $db->transStart();

        $newEmail = $this->request->getPost('email');
        $emailChanged = ($newEmail !== $user->email);
        
        // Siapkan data untuk diupdate
        helper('general'); // Muat helper untuk strip_leading_zeros
        $userData = [
            'name'           => $this->request->getPost('name'),
            'phone_number'   => $this->request->getPost('phone_number'),
            'kta_number'     => strip_leading_zeros($this->request->getPost('kta_number')),
            'birth_date'     => $this->request->getPost('birth_date'),
        ];
        
        // Logika untuk menangani perubahan email
        if (!$emailChanged) {
            $userData['email'] = $newEmail; // Jika tidak berubah, sertakan email
        } else {
            // Jika email berubah, reset status verifikasi. Email baru akan diupdate setelah diverifikasi.
            $userData['email_verified_at'] = null;
        }

        // --- PERBAIKAN UTAMA: Gunakan Query Builder untuk UPDATE yang andal ---
        $db->table('users')->where('id', $id)->update($userData);

        // Kirim link verifikasi jika email berubah
        if ($emailChanged) {
            $tokenModel = new \App\Models\EmailChangeRequestModel();
            $tokenModel->where('user_id', $id)->delete();

            $token = bin2hex(random_bytes(32));
            $tokenModel->insert([
                'user_id'    => $id,
                'new_email'  => $newEmail,
                'token'      => $token,
                'expires_at' => date('Y-m-d H:i:s', time() + 3600)
            ]);

            $emailService = new \App\Libraries\EmailService();
            $verificationLink = site_url(route_to('profile.email.verify', $token));
            $emailService->sendEmailChangeVerification($newEmail, $verificationLink);
        }
        
        $db->transComplete();

        if ($db->transStatus() === false) {
            return redirect()->back()->with('error', 'Failed to update user data.');
        }

        // Tentukan pesan sukses yang tepat
        $successMessage = $emailChanged 
            ? lang('Admin/Users.updateSuccessEmail') 
            : lang('Admin/Users.updateSuccess');
        
        return redirect()->to(route_to('admin.users.index'))->with('success', $successMessage);
    }

    public function delete($id = null)
    {
        $db = \Config\Database::connect();
        $db->transStart();

        $userModel = new UserModel();
        $transactionModel = new TransactionModel();
        
        // Hapus (soft delete) user
        $userModel->delete($id);
        
        // Batalkan semua transaksi milik user tersebut
        $transactionModel->where('user_id', $id)->set('payment_status', 'canceled')->update();
        
        $db->transComplete();

        if ($db->transStatus() === false) {
            return redirect()->back()->with('error', 'Failed to delete user and their transactions.');
        }

        return redirect()->to(route_to('admin.users.index'))->with('success', lang('Admin/Users.deleteSuccess'));
    }
}