<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Users extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        // Session & Role Check
        if (!isset($_SESSION['qurbani_user_id']) || $_SESSION['qurbani_role'] !== 'sa') {
            redirect('/admin', 'refresh');
        }

        // Load required models
        $this->load->model('User_model', 'user');
        $this->load->model('Payment_model', 'payment');
        $this->load->model('Settings_model', 'setup');
        $this->load->model('Role_model', 'roles');

    }

    public function index()
    {




        $data['avg_session_time'] = $this->user->get_avg_session_duration();
        $data['most_active_user'] = $this->user->get_most_active_user();
        $data['failed_today'] = $this->user->get_failed_logins_today();
        $data['last_logout_time'] = $this->user->get_last_logout_time();

$all_users = $this->user->get_all();

$active_users_last_30 = 0;

$data['users'] = [];
foreach ($all_users as $user) {
    $user->login_count = $this->user->get_user_login_count($user->id);
    $user->last_login = $this->user->get_user_last_login($user->id);
    $user->active_last_30 = $this->user->is_user_active_last_30_days($user->id);

    if ($user->active_last_30) {
        $active_users_last_30++;
    }

    $data['users'][] = $user;
}

$data['active_users_last_30'] = $active_users_last_30;


$raw_data = $this->user->get_daily_login_counts();
$login_labels = [];
$login_counts = [];

for ($i = 29; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $label = date('D d M', strtotime($date));
    $login_labels[] = $label;

    $login_counts[] = isset($raw_data[$date]) ? (int)$raw_data[$date] : 0;
}

$data['login_labels'] = $login_labels;
$data['login_counts'] = $login_counts;



// Last 7 days login stats
$stats = $this->user->get_daily_stats(7);

$labels = [];
$success_data = [];
$fail_data = [];

foreach ($stats as $s) {
    $labels[] = date('D d M', strtotime($s->date));
    $success_data[] = (int) $s->success_count;
    $fail_data[] = (int) $s->failure_count;
}

$data['login_labels'] = $labels;
$data['login_success'] = $success_data;
$data['login_fail'] = $fail_data;


 $data['logs'] = $this->user->get_all_logs();




$data['logged_in_users'] = $this->user->get_logged_in_users_count();
$data['last_month_logins'] = $this->user->get_last_month_login_count();
$data['total_users'] = $this->user->get_total_users_count();

$data['settings'] = $this->setup->get_by_id(1);
 $data['roles'] = $this->roles->get_all();
        $data['title'] = 'Users';
        $data['mainContent'] = 'admin/users/index';
        $this->load->view('admin/layout/master', $data);
    }

    public function add()
    {
        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            $post = $this->input->post();

            $password = isset($post['password']) ? $post['password'] : '';
            if ($password === '') {
                $this->session->set_flashdata('error', 'Password is required');
                redirect('admin/users');
            }

            $data = [
                'name'      => isset($post['name'])      ? $post['name']      : '',
                'username'  => isset($post['username'])  ? $post['username']  : '',
                'email'     => isset($post['email'])     ? $post['email']     : '',
                'role'      => isset($post['role'])      ? $post['role']      : '',
                'password'  => User_model::hash_password($password),
                'user_id'   => $_SESSION['qurbani_user_id']
            ];

            if ($this->user->checkUsername($data['username'])) {
                $this->session->set_flashdata('error', 'Username Already Exist');
            } elseif ($this->user->checkEmail($data['email'])) {
                $this->session->set_flashdata('error', 'Email Already Exist');
            } else {
                $this->user->create($data);
                $this->session->set_flashdata('message', 'User added successfully.');
            }
            redirect('admin/users');
        }

        // No standalone add page exists — users are added via the index modal
        redirect('admin/users');
    }

    public function edit($id)
    {
        // No standalone edit page exists — editing is done via the index modal (admin/users/update)
        redirect('admin/users');
    }

/**
 * Actually used by edit-user-modal (POST /admin/users/update)
 * Fields are whitelisted to prevent mass-assignment.
 */
public function update()
{
    $post = $this->input->post();
    $id = isset($post['id']) ? (int)$post['id'] : 0;
    if ($id <= 0) {
        redirect('admin/users');
    }

    $data = [
        'name'      => isset($post['name'])     ? $post['name']     : '',
        'username'  => isset($post['username']) ? $post['username'] : '',
        'email'     => isset($post['email'])    ? $post['email']    : '',
        'role'      => isset($post['role'])     ? $post['role']     : ''
    ];
    if (!empty($post['password'])) {
        $data['password'] = User_model::hash_password($post['password']);
    }

    if ($this->user->checkUsername($data['username'], $id)) {
        $this->session->set_flashdata('error', 'Username already exists');
    } elseif ($this->user->checkEmail($data['email'], $id)) {
        $this->session->set_flashdata('error', 'Email already exists');
    } else {
        $updated = $this->user->update($id, $data);
        $this->session->set_flashdata('success', $updated ? 'User updated successfully' : 'Failed to update user');
    }

    redirect('admin/users');
}











    public function delete($id)
    {
        if ($this->user->destroy($id)) {
            $this->session->set_flashdata('message', 'Deleted Successfully');
        }
        redirect('admin/users');
    }

    public function checkUsername()
    {
        $username = $this->input->get('username');
        $id = $this->input->get('id');
        echo $this->user->checkUsername($username, $id);
    }

    public function checkEmail()
    {
        $email = $this->input->get('email');
        $id = $this->input->get('id');
        echo $this->user->checkEmail($email, $id);
    }

}
