<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\TipsterStatsModel;

class TipsterAuth extends Controller
{
    public function index()
    {
        // If already logged in, redirect to portal
        if (session()->get('tipsterLoggedIn')) {
            return redirect()->to('/tipster');
        }
        
        return view('tipster/login');
    }

    public function login()
    {
        $pin = $this->request->getPost('pin');
        
        if (empty($pin)) {
            return redirect()->back()->with('error', 'Please enter your PIN');
        }

        // Get the tipster by PIN
        $tipsterModel = new TipsterStatsModel();
        $tipster = $tipsterModel->where('pin', $pin)->first();

        if (!$tipster) {
            return redirect()->back()->with('error', 'Invalid PIN');
        }

        // Verify PIN matches
        if ($tipster['pin'] !== $pin) {
            return redirect()->back()->with('error', 'Invalid PIN');
        }

        // Set session
        $session = session();
        $session->set('tipsterLoggedIn', true);
        $session->set('tipsterAuthor', $tipster['author']);
        $session->set('tipsterLastActivity', time());
        
        return redirect()->to('/tipster');
    }

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

