<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Auth extends Controller
{
    public function index()
    {
        // If already logged in, redirect to dashboard
        if (session()->get('isLoggedIn')) {
            return redirect()->to('/admin');
        }
        
        return view('auth/login');
    }

    public function login()
    {
        $pin = $this->request->getPost('pin');
        
        // Get the stored PIN from database
        $db = \Config\Database::connect();
        $builder = $db->table('admin_pin');
        $storedPin = $builder->get()->getRow();

        if (!$storedPin) {
            return redirect()->back()->with('error', 'System not properly configured');
        }

        // Verify PIN
        if (password_verify($pin, $storedPin->pin)) {
            // Set session
            $session = session();
            $session->set('isLoggedIn', true);
            $session->set('lastActivity', time());
            
            return redirect()->to('/admin');
        }

        return redirect()->back()->with('error', 'Invalid PIN');
    }

    public function logout()
    {
        $session = session();
        $session->destroy();
        
        return redirect()->to('/login');
    }

    public function setupPin()
    {
        // Only allow this in development environment
        if (ENVIRONMENT !== 'development') {
            return redirect()->to('/login');
        }

        $pin = '890090'; // Your desired PIN
        $hashedPin = password_hash($pin, PASSWORD_DEFAULT);

        $db = \Config\Database::connect();
        $builder = $db->table('admin_pin');

        // Check if PIN already exists
        $existingPin = $builder->get()->getRow();
        
        if ($existingPin) {
            // Update existing PIN
            $builder->update(['pin' => $hashedPin]);
        } else {
            // Insert new PIN
            $builder->insert(['pin' => $hashedPin]);
        }

        return "PIN has been set up successfully!";
    }
} 