<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\Common_model;

class Users extends BaseController
{
    protected $common;
    protected $table = 'tbl_users';

    public function __construct()
    {
        $this->common = new Common_model();
    }

    /* ================= LIST USERS ================= */
    public function index()
    {
        if (session()->get('role') !== 'Admin') {
            return redirect()->to('/home')->with('error', 'Unauthorized access');
        }

        $data['users'] = $this->common->getData(
            $this->table,
            'id,name,mobile_number,username,added_date_time',
            [],
            [],
            'id DESC'
        );

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

    /* ================= ADD USER ================= */
public function store()
{
    if (session()->get('role') !== 'Admin') {
        return redirect()->back()->with('error', 'Unauthorized');
    }

    $rules = [
        'name'          => 'required',
        'mobile_number' => 'required|numeric|exact_length[10]',
        'username'      => 'required',
        'password'      => 'required|min_length[6]'
    ];

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

    
    $mobileExists = $this->common->getData(
        $this->table,
        'id',
        ['mobile_number' => $this->request->getPost('mobile_number')]
    );

    if (!empty($mobileExists)) {
        return redirect()->back()
            ->withInput()
            ->with('error', 'Mobile number already exists');
    }

   
    $usernameExists = $this->common->getData(
        $this->table,
        'id',
        ['username' => $this->request->getPost('username')]
    );

    if (!empty($usernameExists)) {
        return redirect()->back()
            ->withInput()
            ->with('error', 'Username already exists');
    }

    $insertData = [
        'name'             => $this->request->getPost('name'),
        'mobile_number'    => $this->request->getPost('mobile_number'),
        'username'         => $this->request->getPost('username'),
        'password' => $this->request->getPost('password'),
        'role'             => 'Employee',
        'added_date_time'  => date('Y-m-d H:i:s'),
        'transaction_date' => date('Y-m-d'),
        'added_by'         => session()->get('user_id'),
        'added_by_role'    => session()->get('role')
    ];

    $this->common->insertData($this->table, $insertData);

    return redirect()->to(base_url('users'))
        ->with('success', 'User added successfully');
}



    /* ================= EDIT ================= */
    public function edit($id)
    {
        if (session()->get('role') !== 'Admin') {
            return redirect()->to('/home')->with('error', 'Unauthorized');
        }

        $editUser = $this->common->getData($this->table, '*', ['id' => $id]);

        if (empty($editUser)) {
            return redirect()->back()->with('error', 'User not found');
        }

        $data['editUser'] = $editUser[0];
        $data['users'] = $this->common->getData(
            $this->table,
            'id,name,mobile_number,username,added_date_time',
            [],
            [],
            'id DESC'
        );

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

public function update($id)
{
    if (session()->get('role') !== 'Admin') {
        return redirect()->back()->with('error', 'Unauthorized');
    }

    $rules = [
        'name'          => 'required',
        'mobile_number' => 'required|numeric|exact_length[10]',
        'username'      => 'required'
    ];

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

   
    $mobileExists = $this->common->getData(
        $this->table,
        'id',
        [
            'mobile_number' => $this->request->getPost('mobile_number'),
            'id !='         => $id
        ]
    );

    if (!empty($mobileExists)) {
        return redirect()->back()
            ->withInput()
            ->with('error', 'Mobile number already exists');
    }

    // 🔴 CHECK USERNAME EXISTS (EXCEPT CURRENT USER)
    $usernameExists = $this->common->getData(
        $this->table,
        'id',
        [
            'username' => $this->request->getPost('username'),
            'id !='    => $id
        ]
    );

    if (!empty($usernameExists)) {
        return redirect()->back()
            ->withInput()
            ->with('error', 'Username already exists');
    }

   $updateData = [
    'name'          => $this->request->getPost('name'),
    'mobile_number' => $this->request->getPost('mobile_number'),
    'username'      => $this->request->getPost('username'),
	'last_updated_date_time'  => date('Y-m-d H:i:s'),
	'last_updated_by'         => session()->get('user_id'),
	'last_updated_by_role'    => session()->get('role')
	

];

if ($this->request->getPost('password')) {
    $updateData['password'] = $this->request->getPost('password');
}

    $this->common->updateData($this->table, $updateData, ['id' => $id]);

    return redirect()->to(base_url('users'))
        ->with('success', 'User updated successfully');
}



    /* ================= DELETE ================= */
    public function delete($id)
    {
        if (session()->get('role') !== 'Admin') {
            return redirect()->back()->with('error', 'Unauthorized');
        }

        $this->common->deleteData($this->table, ['id' => $id]);

         return redirect()->to(base_url('users'))
        ->with('success', 'User Deleted successfully');
    }
}
?>