<?php
namespace App\Controllers\Api\V1;

use App\Core\Controller;
use App\Models\Migrant;
use App\Models\ApplicationStatus;

class ApiController extends Controller {
    
    protected $migrantModel;
    protected $apiKey;
    
    public function __construct() {
        parent::__construct();
        $this->migrantModel = new Migrant();
        
        // API Authentication
        $this->authenticateApi();
    }
    
    /**
     * Authenticate API request
     */
    protected function authenticateApi() {
        $headers = getallheaders();
        $this->apiKey = $headers['X-API-Key'] ?? null;
        
        if (!$this->apiKey || !$this->validateApiKey($this->apiKey)) {
            $this->response->unauthorized('Invalid API key');
        }
    }
    
    /**
     * Validate API key
     */
    protected function validateApiKey($key) {
        // In production, validate against database
        $validKeys = [
            'live_key_2024_abc123',
            'test_key_2024_xyz789'
        ];
        
        return in_array($key, $validKeys);
    }
    
    /**
     * GET /api/v1/migrants
     */
    public function index() {
        $page = (int)($this->request->get('page', 1));
        $limit = (int)($this->request->get('limit', 20));
        $offset = ($page - 1) * $limit;
        
        $db = $this->migrantModel->getConnection();
        
        // Get migrants with pagination
        $stmt = $db->prepare("
            SELECT 
                b.person_id,
                b.document_type,
                b.document_no,
                b.surname,
                b.given_name,
                b.nationality,
                b.date_of_birth,
                b.sex,
                b.email_address,
                a.status as current_status,
                b.created_at,
                b.updated_at
            FROM biographical_information b
            LEFT JOIN (
                SELECT person_id, status
                FROM application_status a1
                WHERE created_at = (
                    SELECT MAX(created_at)
                    FROM application_status a2
                    WHERE a2.person_id = a1.person_id
                )
            ) a ON b.person_id = a.person_id
            WHERE b.deleted_at IS NULL
            ORDER BY b.created_at DESC
            LIMIT ? OFFSET ?
        ");
        
        $stmt->execute([$limit, $offset]);
        $migrants = $stmt->fetchAll();
        
        // Get total count
        $countStmt = $db->query("SELECT COUNT(*) as total FROM biographical_information WHERE deleted_at IS NULL");
        $total = $countStmt->fetch()['total'];
        
        $this->json([
            'success' => true,
            'data' => $migrants,
            'meta' => [
                'page' => $page,
                'limit' => $limit,
                'total' => (int)$total,
                'pages' => ceil($total / $limit)
            ]
        ]);
    }
    
    /**
     * GET /api/v1/migrants/{id}
     */
    public function show($params) {
        $person_id = $params['id'];
        $migrant = $this->migrantModel->getFullProfile($person_id);
        
        if (!$migrant) {
            $this->response->notFound('Migrant not found');
        }
        
        // Remove sensitive data
        unset($migrant['biometrics']);
        
        $this->json([
            'success' => true,
            'data' => $migrant
        ]);
    }
    
    /**
     * POST /api/v1/migrants
     */
    public function store() {
        $data = $this->request->all();
        $data['person_id'] = $this->migrantModel->generatePersonId();
        $data['created_by'] = 1; // API user ID
        $data['surname'] = strtoupper($data['surname'] ?? '');
        $data['given_name'] = strtoupper($data['given_name'] ?? '');
        
        // Validate required fields
        $required = ['document_type', 'document_no', 'surname', 'given_name', 'nationality', 'date_of_birth', 'sex'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                $this->response->error("$field is required", 400);
            }
        }
        
        try {
            $this->migrantModel->beginTransaction();
            
            $migrant = $this->migrantModel->create($data);
            
            if (!$migrant) {
                throw new \Exception("Failed to create migrant");
            }
            
            // Create initial status
            $statusModel = new ApplicationStatus();
            $statusModel->create([
                'person_id' => $data['person_id'],
                'status' => ApplicationStatus::STATUS_DRAFT,
                'created_by' => 1
            ]);
            
            $this->migrantModel->commit();
            
            $this->response->json([
                'success' => true,
                'message' => 'Migrant created successfully',
                'data' => ['person_id' => $data['person_id']]
            ], 201);
            
        } catch (\Exception $e) {
            $this->migrantModel->rollback();
            $this->response->error($e->getMessage(), 400);
        }
    }
    
    /**
     * PUT /api/v1/migrants/{id}
     */
    public function update($params) {
        $person_id = $params['id'];
        $data = $this->request->all();
        
        $migrant = $this->migrantModel->find($person_id);
        if (!$migrant) {
            $this->response->notFound('Migrant not found');
        }
        
        $data['updated_by'] = 1;
        $data['surname'] = strtoupper($data['surname'] ?? $migrant['surname']);
        $data['given_name'] = strtoupper($data['given_name'] ?? $migrant['given_name']);
        
        $updated = $this->migrantModel->update($person_id, $data);
        
        if ($updated) {
            $this->json([
                'success' => true,
                'message' => 'Migrant updated successfully'
            ]);
        } else {
            $this->response->error('Update failed', 400);
        }
    }
    
    /**
     * DELETE /api/v1/migrants/{id}
     */
    public function delete($params) {
        $person_id = $params['id'];
        
        $migrant = $this->migrantModel->find($person_id);
        if (!$migrant) {
            $this->response->notFound('Migrant not found');
        }
        
        $deleted = $this->migrantModel->delete($person_id);
        
        if ($deleted) {
            $this->json([
                'success' => true,
                'message' => 'Migrant deleted successfully'
            ]);
        } else {
            $this->response->error('Delete failed', 400);
        }
    }
    
    /**
     * GET /api/v1/migrants/search
     */
    public function search() {
        $params = $this->request->all();
        $results = $this->migrantModel->search($params);
        
        $this->json([
            'success' => true,
            'data' => $results,
            'count' => count($results)
        ]);
    }
    
    /**
     * GET /api/v1/stats
     */
    public function statistics() {
        $statusModel = new ApplicationStatus();
        $stats = $statusModel->getStatusStats();
        
        $this->json([
            'success' => true,
            'data' => [
                'applications' => $stats,
                'total' => array_sum($stats)
            ]
        ]);
    }
}