<?php

namespace App\Controllers\Api;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class ApiController extends BaseController
{
    protected $currentUser = null;
    protected $db;
    protected $jwtKey;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        
        // Set CORS headers FIRST before anything else
        $this->setCorsHeaders();
        
        // Handle OPTIONS requests (preflight)
        if ($this->request->getMethod() === 'OPTIONS') {
            return;
        }
        
        try {
            $this->db = \Config\Database::connect();
            $this->jwtKey = getenv('JWT_SECRET', true) ?: 'your-secret-key';
            $this->authenticate();
        } catch (\Exception $e) {
            // Log but don't fail - let the controller handle it
            log_message('error', 'ApiController init error: ' . $e->getMessage());
        }
        
        header('Content-Type: application/json');
    }

    protected function setCorsHeaders()
    {
        $origin = $this->request->getHeaderLine('Origin');
        $allowed_origins = ['http://localhost:5173', 'http://127.0.0.1:5173'];
        
        if (in_array($origin, $allowed_origins)) {
            header("Access-Control-Allow-Origin: {$origin}");
        }
        
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 7200');
    }

    protected function authenticate()
    {
        $token = $this->getBearerToken();
        
        if (!$token) {
            return;
        }

        try {
            $decoded = JWT::decode($token, new Key($this->jwtKey, 'HS256'));
            $this->currentUser = (array) $decoded;
        } catch (\Exception $e) {
            // Token validation failed
            return;
        }
    }

    protected function getBearerToken()
    {
        $header = $this->request->getHeaderLine('Authorization');
        if (preg_match('/Bearer\s+(.*)$/i', $header, $matches)) {
            return $matches[1];
        }
        return null;
    }

    protected function generateToken($userId, $email, $role)
    {
        $issuedAt = time();
        $expire = $issuedAt + 86400; // 24 hours

        $payload = [
            'iat' => $issuedAt,
            'exp' => $expire,
            'userId' => $userId,
            'email' => $email,
            'role' => $role,
        ];

        return JWT::encode($payload, $this->jwtKey, 'HS256');
    }

    protected function isAuthenticated()
    {
        return $this->currentUser !== null;
    }

    protected function hasRole($role)
    {
        return $this->isAuthenticated() && isset($this->currentUser['role']) && $this->currentUser['role'] === $role;
    }

    protected function hasAnyRole($roles)
    {
        return $this->isAuthenticated() && in_array($this->currentUser['role'], $roles);
    }

    protected function requireAuth()
    {
        if (!$this->isAuthenticated()) {
            return $this->respond(['error' => 'Unauthorized'], ResponseInterface::HTTP_UNAUTHORIZED);
        }
    }

    protected function requireRole($role)
    {
        if (!$this->hasRole($role)) {
            return $this->respond(['error' => 'Forbidden'], ResponseInterface::HTTP_FORBIDDEN);
        }
    }

    protected function respond($data = null, $statusCode = 200)
    {
        return $this->response
            ->setStatusCode($statusCode)
            ->setJSON($data);
    }

    protected function respondCreated($data)
    {
        return $this->respond($data, ResponseInterface::HTTP_CREATED);
    }

    protected function respondUpdated($data)
    {
        return $this->respond($data, ResponseInterface::HTTP_OK);
    }

    protected function respondDeleted()
    {
        return $this->respond(['success' => true], ResponseInterface::HTTP_NO_CONTENT);
    }

    protected function respondNotFound()
    {
        return $this->respond(['error' => 'Not found'], ResponseInterface::HTTP_NOT_FOUND);
    }

    protected function respondValidationError($errors)
    {
        return $this->respond(['errors' => $errors], ResponseInterface::HTTP_UNPROCESSABLE_ENTITY);
    }

    protected function respondBadRequest($message)
    {
        return $this->respond(['error' => $message], ResponseInterface::HTTP_BAD_REQUEST);
    }

    protected function logAudit($action, $entityType, $entityId, $oldValues = null, $newValues = null)
    {
        $auditData = [
            'user_id' => $this->currentUser['userId'] ?? null,
            'action' => $action,
            'entity_type' => $entityType,
            'entity_id' => $entityId,
            'old_values' => $oldValues ? json_encode($oldValues) : null,
            'new_values' => $newValues ? json_encode($newValues) : null,
            'ip_address' => $this->request->getIPAddress(),
            'created_at' => date('Y-m-d H:i:s'),
        ];

        $this->db->table('audit_logs')->insert($auditData);
    }
}
