<?php

namespace App\Controllers\View;
use App\Controllers\BaseController;
use Config\SessionTimeout;
use CodeIgniter\Controller;
use CodeIgniter\API\ResponseTrait;

class SessionTimeoutController extends BaseController
{
    use ResponseTrait;

    public function getTimeoutConfig()
    {
        return $this->response->setJSON([
            'success' => true,
            'timeout' => SessionTimeout::TIMEOUT_DURATION,
            'warning_time' => SessionTimeout::WARNING_THRESHOLD,
            'check_interval' => SessionTimeout::CHECK_INTERVAL,
            'logout_url' => site_url('auth/logout'),
            'keep_alive_url' => site_url('session/pingActivity'),
            'check_url' => site_url('session/checkTimeout')
        ]);
    }

    public function checkTimeout()
    {
        $session = session();

        // Verify session exists and has last_activity
        if (!$session->has('last_activity')) {
            return $this->expireSession();
        }

        $lastActivity = $session->get('last_activity');
        $elapsed = time() - $lastActivity;

        if ($elapsed > SessionTimeout::TIMEOUT_DURATION) {
            return $this->expireSession();
        } elseif ($elapsed > SessionTimeout::WARNING_THRESHOLD) {
            return $this->response->setJSON([
                'status' => 'warning',
                'time_remaining' => SessionTimeout::TIMEOUT_DURATION - $elapsed
            ]);
        }
        
        return $this->response->setJSON([
            'status' => 'active',
            'time_remaining' => SessionTimeout::TIMEOUT_DURATION - $elapsed
        ]);
    }

    public function pingActivity()
    {
        $session = session();
        
        // Only update if session is still valid
        if (!$session->has('last_activity') || 
            (time() - $session->get('last_activity') > SessionTimeout::TIMEOUT_DURATION)) {
            return $this->expireSession();
        }
        
        $session->set('last_activity', time());
        return $this->response->setJSON([
            'status' => 'active',
            'time_remaining' => SessionTimeout::TIMEOUT_DURATION
        ]);
    }

    private function expireSession()
    {
        $this->destroySession();
        return $this->response->setJSON([
            'status'   => 'expired',
            'redirect' => site_url('login'),
            'message'  => 'Your session has expired due to inactivity.'
        ]);
    }

    private function destroySession()
    {
        $session = session();
        $session->setFlashdata('error', 'Your session has expired due to inactivity.');
        
        // Clear session data
        $session->remove('last_activity');
        $session->destroy();
        
        // Regenerate session ID for security
        session_regenerate_id(true);
    }
}