<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\Migrant;
use App\Models\ApplicationStatus;
use App\Models\UploadedDocument;
use App\Services\UploadService;
use Security;

class MigrantController extends Controller {
    
    protected $migrantModel;
    protected $statusModel;
    protected $uploadService;
    protected $documentModel;
    
    public function __construct() {
        try {
            parent::__construct();
            
            error_log("MigrantController constructor started");
            
            // Initialize models with error handling
            $this->migrantModel = new Migrant();
            $this->statusModel = new ApplicationStatus();
            $this->documentModel = new UploadedDocument();
            
            // Try to initialize UploadService, but don't fail if it doesn't exist
            try {
                if (class_exists('App\Services\UploadService')) {
                    $this->uploadService = new UploadService();
                    error_log("UploadService initialized successfully");
                } else {
                    error_log("UploadService class not found - file uploads will be disabled");
                    $this->uploadService = null;
                }
            } catch (\Exception $e) {
                error_log("Failed to initialize UploadService: " . $e->getMessage());
                $this->uploadService = null;
            }
            
            error_log("MigrantController constructor completed");
            
        } catch (\Exception $e) {
            error_log("MigrantController constructor error: " . $e->getMessage());
            error_log("Stack trace: " . $e->getTraceAsString());
            throw $e;
        }
    }
    
    /**
     * Show registration form
     */
    public function create() {
        try {
            error_log("MigrantController::create() called");
            
            $this->requireAuth();
            
            $person_id = $this->migrantModel->generatePersonId();
            
            $this->render('migrants/create', [
                'title' => 'New Registration',
                'csrf_token' => $this->csrf_token(),
                'person_id' => $person_id
            ]);
            
        } catch (\Exception $e) {
            error_log("ERROR in create(): " . $e->getMessage());
            $_SESSION['error'] = 'Unable to load registration form. Please try again.';
            $this->redirect('/dashboard');
        }
    }
    
    /**
     * Store migrant data with biometrics
     */
    public function store() {
        try {
            $this->requireAuth();
            
            // Verify CSRF token
            if (!isset($_POST['csrf_token']) || !Security::validateCSRFToken($_POST['csrf_token'])) {
                $_SESSION['error'] = 'Invalid CSRF token';
                $this->redirect('/migrants/create');
                return;
            }
            
            $data = $_POST;
            
            try {
                $this->migrantModel->beginTransaction();
                
                // Generate person_id
                $person_id = $this->migrantModel->generatePersonId();
                
                // Validate required fields
                $required_fields = ['document_type', 'country_of_issue', 'document_no', 'surname', 'given_name', 'nationality', 'date_of_birth', 'sex'];
                $missing_fields = [];
                
                foreach ($required_fields as $field) {
                    if (empty($data[$field])) {
                        $missing_fields[] = $field;
                    }
                }
                
                if (!empty($missing_fields)) {
                    throw new \Exception("Missing required fields: " . implode(', ', $missing_fields));
                }
                
                // Get database connection
                $db = $this->migrantModel->getConnection();
                
                // Check for duplicate document number
                $checkStmt = $db->prepare("SELECT COUNT(*) as count FROM biographical_information WHERE document_no = ?");
                $checkStmt->execute([$data['document_no']]);
                $result = $checkStmt->fetch();
                
                if ($result['count'] > 0) {
                    // Auto-generate unique document number
                    $original_document_no = $data['document_no'];
                    $counter = 1;
                    $document_no = $original_document_no;
                    
                    while (true) {
                        $checkStmt->execute([$document_no]);
                        $result = $checkStmt->fetch();
                        
                        if ($result['count'] == 0) {
                            break;
                        }
                        
                        $document_no = $original_document_no . '-' . $counter;
                        $counter++;
                        
                        if ($counter > 100) {
                            $document_no = $original_document_no . '-' . uniqid();
                            break;
                        }
                    }
                    
                    $data['document_no'] = $document_no;
                    $_SESSION['warning'] = "Document number '{$original_document_no}' is already in use. It has been changed to '{$document_no}' for this registration.";
                }
                
                // Prepare data for insertion
                $migrantData = [
                    'person_id' => $person_id,
                    'document_type' => $data['document_type'],
                    'country_of_issue' => $data['country_of_issue'],
                    'document_no' => $data['document_no'],
                    'surname' => strtoupper($data['surname']),
                    'given_name' => strtoupper($data['given_name']),
                    'nationality' => $data['nationality'],
                    'date_of_birth' => $data['date_of_birth'],
                    'sex' => $data['sex'],
                    'created_by' => $_SESSION['user_id']
                ];
                
                // Add optional fields
                $optionalFields = [
                    'expiry_date', 'national_id_no', 'date_of_issue', 'issuing_authority',
                    'occupation', 'profession', 'highest_qualification', 'email_address',
                    'blood_type', 'marital_status', 'place_of_birth', 'country_of_birth',
                    'state_province', 'town'
                ];
                
                foreach ($optionalFields as $field) {
                    if (!empty($data[$field])) {
                        $migrantData[$field] = $data[$field];
                    }
                }
                
                // Insert biographical information
                $columns = implode(', ', array_keys($migrantData));
                $placeholders = ':' . implode(', :', array_keys($migrantData));
                
                $sql = "INSERT INTO biographical_information ({$columns}) VALUES ({$placeholders})";
                $stmt = $db->prepare($sql);
                $result = $stmt->execute($migrantData);
                
                if (!$result) {
                    $errorInfo = $stmt->errorInfo();
                    throw new \Exception("Database error: " . ($errorInfo[2] ?? 'Unknown error'));
                }
                
                // Handle biometrics data
                if (!empty($data['biometrics_json'])) {
                    $biometrics = json_decode($data['biometrics_json'], true);
                    
                    // Save photo data
                    if (!empty($biometrics['photo'])) {
                        $photoData = preg_replace('#^data:image/\w+;base64,#i', '', $biometrics['photo']);
                        $photoData = base64_decode($photoData);
                        
                        if ($photoData) {
                            $photoStmt = $db->prepare("
                                UPDATE biographical_information 
                                SET photo_data = ?, photo_format = 'jpeg' 
                                WHERE person_id = ?
                            ");
                            $photoStmt->execute([$photoData, $person_id]);
                        }
                    }
                    
                    // Save fingerprint data
                    if (!empty($biometrics['fingerprints'])) {
                        $biometricsStmt = $db->prepare("
                            INSERT INTO biometrics (person_id, capture_date, capture_device_id, created_by)
                            VALUES (?, NOW(), ?, ?)
                        ");
                        $biometricsStmt->execute([
                            $person_id,
                            $biometrics['device'] ?? 'unknown',
                            $_SESSION['user_id']
                        ]);
                        
                        $biometricsId = $db->lastInsertId();
                        
                        $fingerStmt = $db->prepare("
                            INSERT INTO fingerprints 
                            (biometrics_id, finger_position, fingerprint_template, template_format, quality_score, capture_timestamp)
                            VALUES (?, ?, ?, ?, ?, NOW())
                        ");
                        
                        foreach ($biometrics['fingerprints'] as $finger => $fpData) {
                            $encryptedTemplate = Security::encrypt($fpData['template']);
                            
                            $fingerStmt->execute([
                                $biometricsId,
                                $finger,
                                $encryptedTemplate,
                                $fpData['format'] ?? 'ANSI-378',
                                $fpData['quality'] ?? 85
                            ]);
                        }
                    }
                }
                
                // Determine initial status
                $initialStatus = ApplicationStatus::STATUS_DRAFT;
                if (!empty($data['submit_for_review'])) {
                    $initialStatus = ApplicationStatus::STATUS_SUBMITTED;
                }
                
                // Create application status
                $statusData = [
                    'person_id' => $person_id,
                    'status' => $initialStatus,
                    'remarks' => $initialStatus === ApplicationStatus::STATUS_SUBMITTED ? 'Submitted for review' : 'Draft created',
                    'created_by' => $_SESSION['user_id']
                ];
                
                $statusColumns = implode(', ', array_keys($statusData));
                $statusPlaceholders = ':' . implode(', :', array_keys($statusData));
                
                $statusSql = "INSERT INTO application_status ({$statusColumns}) VALUES ({$statusPlaceholders})";
                $statusStmt = $db->prepare($statusSql);
                $statusResult = $statusStmt->execute($statusData);
                
                if (!$statusResult) {
                    $errorInfo = $statusStmt->errorInfo();
                    throw new \Exception("Failed to create status record: " . ($errorInfo[2] ?? 'Unknown error'));
                }
                
                // Handle file uploads if any and if uploadService exists
                if (!empty($_FILES['documents']) && $_FILES['documents']['name'][0] != '' && $this->uploadService) {
                    $this->handleDocumentUploads($person_id, $_FILES['documents']);
                } else if (!empty($_FILES['documents']) && $_FILES['documents']['name'][0] != '') {
                    error_log("UploadService not available - skipping file uploads");
                }
                
                $this->migrantModel->commit();
                
                if ($initialStatus === ApplicationStatus::STATUS_SUBMITTED) {
                    $_SESSION['success'] = 'Migrant registered and submitted for review successfully!';
                } else {
                    $_SESSION['success'] = 'Migrant registered successfully as draft.';
                }
                
                $this->redirect('/migrants/' . $person_id);
                
            } catch (\Exception $e) {
                $this->migrantModel->rollback();
                throw $e;
            }
            
        } catch (\Exception $e) {
            error_log("Migrant registration error: " . $e->getMessage());
            error_log("Stack trace: " . $e->getTraceAsString());
            
            if (strpos($e->getMessage(), '1062 Duplicate entry') !== false) {
                $_SESSION['error'] = 'This document number is already registered in the system. Please use a different document number.';
            } else {
                $_SESSION['error'] = 'Registration failed: ' . $e->getMessage();
            }
            
            $this->redirect('/migrants/create');
        }
    }
    
    /**
     * Show migrant profile with biometrics
     */
    public function show($params) {
        try {
            $this->requireAuth();
            
            $person_id = $params['id'] ?? '';
            if (empty($person_id)) {
                $this->redirect('/migrants/search');
                return;
            }
            
            $migrant = $this->migrantModel->getFullProfile($person_id);
            
            if (!$migrant) {
                $_SESSION['error'] = 'Migrant not found';
                $this->redirect('/migrants/search');
                return;
            }
            
            $this->render('migrants/show', [
                'title' => 'Migrant Profile',
                'migrant' => $migrant,
                'csrf_token' => $this->csrf_token()
            ]);
            
        } catch (\Exception $e) {
            error_log("ERROR in show(): " . $e->getMessage());
            $_SESSION['error'] = 'Unable to load profile';
            $this->redirect('/migrants/search');
        }
    }
    
    /**
     * Show edit form for migrant
     */
    public function edit($params) {
        try {
            $this->requireAuth();
            
            $person_id = $params['id'] ?? '';
            if (empty($person_id)) {
                $_SESSION['error'] = 'Invalid migrant ID';
                $this->redirect('/migrants/search');
                return;
            }
            
            $migrant = $this->migrantModel->getFullProfile($person_id);
            
            if (!$migrant) {
                $_SESSION['error'] = 'Migrant not found';
                $this->redirect('/migrants/search');
                return;
            }
            
            // Check if can be edited (only Draft or Rejected)
            $currentStatus = $migrant['current_status']['status'] ?? 'Draft';
            if (!in_array($currentStatus, ['Draft', 'Rejected'])) {
                $_SESSION['error'] = 'This application cannot be edited in its current status';
                $this->redirect('/migrants/' . $person_id);
                return;
            }
            
            $this->render('migrants/edit', [
                'title' => 'Edit Migrant',
                'migrant' => $migrant,
                'csrf_token' => $this->csrf_token()
            ]);
            
        } catch (\Exception $e) {
            error_log("ERROR in edit(): " . $e->getMessage());
            $_SESSION['error'] = 'Unable to load edit form';
            $this->redirect('/migrants/search');
        }
    }
    
    /**
     * Update migrant - Process edit form with duplicate checking
     */
    public function update($params) {
        try {
            $this->requireAuth();
            
            // Verify CSRF
            if (!isset($_POST['csrf_token']) || !Security::validateCSRFToken($_POST['csrf_token'])) {
                $_SESSION['error'] = 'Invalid CSRF token';
                $this->redirect('/migrants/' . $params['id'] . '/edit');
                return;
            }
            
            $person_id = $params['id'] ?? '';
            if (empty($person_id)) {
                $_SESSION['error'] = 'Invalid migrant ID';
                $this->redirect('/migrants/search');
                return;
            }
            
            $data = $_POST;
            
            try {
                $this->migrantModel->beginTransaction();
                
                $db = $this->migrantModel->getConnection();
                
                // Check for duplicate document number (excluding current record)
                if (!empty($data['document_no'])) {
                    $checkStmt = $db->prepare("SELECT COUNT(*) as count FROM biographical_information WHERE document_no = ? AND person_id != ?");
                    $checkStmt->execute([$data['document_no'], $person_id]);
                    $result = $checkStmt->fetch();
                    
                    if ($result['count'] > 0) {
                        throw new \Exception("Document number '{$data['document_no']}' already exists in the system. Please use a unique document number.");
                    }
                }
                
                // Update biographical information
                $updateData = [
                    'document_type' => $data['document_type'] ?? '',
                    'country_of_issue' => $data['country_of_issue'] ?? '',
                    'document_no' => $data['document_no'] ?? '',
                    'surname' => strtoupper($data['surname'] ?? ''),
                    'given_name' => strtoupper($data['given_name'] ?? ''),
                    'nationality' => $data['nationality'] ?? '',
                    'date_of_birth' => $data['date_of_birth'] ?? null,
                    'sex' => $data['sex'] ?? '',
                    'expiry_date' => !empty($data['expiry_date']) ? $data['expiry_date'] : null,
                    'national_id_no' => $data['national_id_no'] ?? null,
                    'date_of_issue' => !empty($data['date_of_issue']) ? $data['date_of_issue'] : null,
                    'issuing_authority' => $data['issuing_authority'] ?? null,
                    'occupation' => $data['occupation'] ?? null,
                    'profession' => $data['profession'] ?? null,
                    'highest_qualification' => $data['highest_qualification'] ?? null,
                    'email_address' => $data['email_address'] ?? null,
                    'blood_type' => $data['blood_type'] ?? null,
                    'marital_status' => $data['marital_status'] ?? null,
                    'place_of_birth' => $data['place_of_birth'] ?? null,
                    'country_of_birth' => $data['country_of_birth'] ?? null,
                    'state_province' => $data['state_province'] ?? null,
                    'town' => $data['town'] ?? null,
                    'updated_by' => $_SESSION['user_id']
                ];
                
                // Build dynamic update query
                $setParts = [];
                $updateParams = [];
                
                foreach ($updateData as $field => $value) {
                    if ($value !== null && $value !== '') {
                        $setParts[] = "$field = :$field";
                        $updateParams[$field] = $value;
                    }
                }
                
                if (empty($setParts)) {
                    throw new \Exception("No data to update");
                }
                
                $sql = "UPDATE biographical_information SET " . implode(', ', $setParts);
                $sql .= " WHERE person_id = :person_id";
                $updateParams['person_id'] = $person_id;
                
                $stmt = $db->prepare($sql);
                $result = $stmt->execute($updateParams);
                
                if (!$result) {
                    $errorInfo = $stmt->errorInfo();
                    throw new \Exception("Database error: " . ($errorInfo[2] ?? 'Unknown error'));
                }
                
                // Update biometrics if new data provided
                if (!empty($data['biometrics_json'])) {
                    $biometrics = json_decode($data['biometrics_json'], true);
                    
                    // Update photo if new one captured
                    if (!empty($biometrics['photo'])) {
                        $photoData = preg_replace('#^data:image/\w+;base64,#i', '', $biometrics['photo']);
                        $photoData = base64_decode($photoData);
                        
                        if ($photoData) {
                            $photoStmt = $db->prepare("
                                UPDATE biographical_information 
                                SET photo_data = ?, photo_format = 'jpeg' 
                                WHERE person_id = ?
                            ");
                            $photoStmt->execute([$photoData, $person_id]);
                        }
                    }
                    
                    // Add new fingerprints if any
                    if (!empty($biometrics['fingerprints'])) {
                        // Check if biometrics record exists
                        $checkStmt = $db->prepare("SELECT id FROM biometrics WHERE person_id = ? ORDER BY capture_date DESC LIMIT 1");
                        $checkStmt->execute([$person_id]);
                        $existingBiometrics = $checkStmt->fetch();
                        
                        if ($existingBiometrics) {
                            $biometricsId = $existingBiometrics['id'];
                        } else {
                            // Create new biometrics record
                            $bioStmt = $db->prepare("
                                INSERT INTO biometrics (person_id, capture_date, capture_device_id, created_by)
                                VALUES (?, NOW(), ?, ?)
                            ");
                            $bioStmt->execute([
                                $person_id,
                                $biometrics['device'] ?? 'unknown',
                                $_SESSION['user_id']
                            ]);
                            $biometricsId = $db->lastInsertId();
                        }
                        
                        // Insert new fingerprints
                        $fingerStmt = $db->prepare("
                            INSERT INTO fingerprints 
                            (biometrics_id, finger_position, fingerprint_template, template_format, quality_score, capture_timestamp)
                            VALUES (?, ?, ?, ?, ?, NOW())
                        ");
                        
                        foreach ($biometrics['fingerprints'] as $finger => $fpData) {
                            // Check if fingerprint already exists
                            $checkFpStmt = $db->prepare("
                                SELECT id FROM fingerprints f
                                JOIN biometrics b ON f.biometrics_id = b.id
                                WHERE b.person_id = ? AND f.finger_position = ?
                            ");
                            $checkFpStmt->execute([$person_id, $finger]);
                            $existingFp = $checkFpStmt->fetch();
                            
                            if (!$existingFp) {
                                $encryptedTemplate = Security::encrypt($fpData['template']);
                                
                                $fingerStmt->execute([
                                    $biometricsId,
                                    $finger,
                                    $encryptedTemplate,
                                    $fpData['format'] ?? 'ANSI-378',
                                    $fpData['quality'] ?? 85
                                ]);
                            }
                        }
                    }
                }
                
                $this->migrantModel->commit();
                
                $_SESSION['success'] = 'Migrant updated successfully';
                $this->redirect('/migrants/' . $person_id);
                
            } catch (\Exception $e) {
                $this->migrantModel->rollback();
                throw $e;
            }
            
        } catch (\Exception $e) {
            error_log("Update error: " . $e->getMessage());
            $_SESSION['error'] = 'Update failed: ' . $e->getMessage();
            $this->redirect('/migrants/' . $params['id'] . '/edit');
        }
    }
    
    /**
     * Search migrants
     */
    public function search() {
        try {
            $this->requireAuth();
            
            $params = $_GET;
            $results = $this->migrantModel->search($params);
            
            $this->render('migrants/search', [
                'title' => 'Search Migrants',
                'results' => $results,
                'searchParams' => $params
            ]);
            
        } catch (\Exception $e) {
            error_log("ERROR in search(): " . $e->getMessage());
            $_SESSION['error'] = 'Unable to load search page';
            $this->redirect('/dashboard');
        }
    }
    
    /**
     * Submit for review
     */
    public function submit($params) {
        try {
            $this->requireAuth();
            
            $person_id = $params['id'] ?? '';
            if (empty($person_id)) {
                if ($this->request->isAjax()) {
                    $this->json(['error' => 'Invalid migrant ID'], 400);
                } else {
                    $_SESSION['error'] = 'Invalid migrant ID';
                    $this->redirect('/migrants/search');
                }
                return;
            }
            
            // Verify CSRF for POST requests
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $token = $_POST['csrf_token'] ?? $this->request->input('csrf_token');
                if (!Security::validateCSRFToken($token)) {
                    if ($this->request->isAjax()) {
                        $this->json(['error' => 'Invalid CSRF token'], 400);
                    } else {
                        $_SESSION['error'] = 'Invalid CSRF token';
                        $this->redirect('/migrants/' . $person_id);
                    }
                    return;
                }
            }
            
            // Check current status
            $currentStatus = $this->statusModel->getCurrentStatus($person_id);
            
            // Only allow submission from Draft or Rejected
            if ($currentStatus && !in_array($currentStatus['status'], ['Draft', 'Rejected'])) {
                throw new \Exception("This application cannot be submitted in its current status");
            }
            
            $this->statusModel->updateStatus(
                $person_id,
                ApplicationStatus::STATUS_SUBMITTED,
                'Submitted for review',
                $_SESSION['user_id']
            );
            
            if ($this->request->isAjax()) {
                $this->json(['success' => true, 'message' => 'Application submitted for review successfully']);
            } else {
                $_SESSION['success'] = 'Application submitted for review';
                $this->redirect('/migrants/' . $person_id);
            }
            
        } catch (\Exception $e) {
            error_log("Submit error: " . $e->getMessage());
            
            if ($this->request->isAjax()) {
                $this->json(['error' => $e->getMessage()], 400);
            } else {
                $_SESSION['error'] = $e->getMessage();
                $this->redirect('/migrants/' . $person_id);
            }
        }
    }
    
    /**
     * Review application - Update status (Approve/Reject/Under Review)
     */
    public function review($params) {
        try {
            $this->requireAuth();
            
            // Only Admin and SuperAdmin can review
            if (!in_array($_SESSION['role'], ['Admin', 'SuperAdmin'])) {
                if ($this->request->isAjax()) {
                    $this->json(['error' => 'Unauthorized'], 403);
                } else {
                    $_SESSION['error'] = 'You do not have permission to review applications';
                    $this->redirect('/dashboard');
                }
                return;
            }
            
            // Verify CSRF for POST requests
            if ($_SERVER['REQUEST_METHOD'] === 'POST' && 
                (!isset($_POST['csrf_token']) || !Security::validateCSRFToken($_POST['csrf_token']))) {
                if ($this->request->isAjax()) {
                    $this->json(['error' => 'Invalid CSRF token'], 400);
                } else {
                    $_SESSION['error'] = 'Invalid CSRF token';
                    $this->redirect('/pending');
                }
                return;
            }
            
            $person_id = $params['id'] ?? '';
            $action = $_POST['action'] ?? $this->request->input('action');
            $remarks = $_POST['remarks'] ?? $this->request->input('remarks', '');
            
            if (empty($person_id) || empty($action)) {
                if ($this->request->isAjax()) {
                    $this->json(['error' => 'Invalid request'], 400);
                } else {
                    $_SESSION['error'] = 'Invalid request';
                    $this->redirect('/pending');
                }
                return;
            }
            
            // Map action to status
            $status = '';
            switch ($action) {
                case 'approve':
                    $status = ApplicationStatus::STATUS_APPROVED;
                    break;
                case 'reject':
                    $status = ApplicationStatus::STATUS_REJECTED;
                    break;
                case 'reinstate':
                    $status = ApplicationStatus::STATUS_DRAFT;
                    break;
                case 'review':
                case 'under_review':
                    $status = ApplicationStatus::STATUS_UNDER_REVIEW;
                    break;
                default:
                    if ($this->request->isAjax()) {
                        $this->json(['error' => 'Invalid action'], 400);
                    } else {
                        $_SESSION['error'] = 'Invalid action';
                        $this->redirect('/pending');
                    }
                    return;
            }
            
            $this->statusModel->updateStatus(
                $person_id,
                $status,
                $remarks,
                $_SESSION['user_id']
            );
            
            $message = 'Application ' . $status;
            
            if ($this->request->isAjax()) {
                $this->json(['success' => true, 'message' => $message]);
            } else {
                $_SESSION['success'] = $message;
                $this->redirect('/migrants/' . $person_id);
            }
            
        } catch (\Exception $e) {
            error_log("Review error: " . $e->getMessage());
            
            if ($this->request->isAjax()) {
                $this->json(['error' => $e->getMessage()], 400);
            } else {
                $_SESSION['error'] = $e->getMessage();
                $this->redirect('/pending');
            }
        }
    }
    
    /**
     * Show approved applications
     */
    public function approved() {
        try {
            $this->requireAuth();
            
            // Only Admin and SuperAdmin can view approved list
            if (!in_array($_SESSION['role'], ['Admin', 'SuperAdmin'])) {
                $_SESSION['error'] = 'You do not have permission to view this page';
                $this->redirect('/dashboard');
                return;
            }
            
            $applications = $this->statusModel->getApprovedApplications(100);
            
            $this->render('migrants/approved', [
                'title' => 'Approved Applications',
                'applications' => $applications
            ]);
            
        } catch (\Exception $e) {
            error_log("ERROR in approved(): " . $e->getMessage());
            $_SESSION['error'] = 'Unable to load approved applications';
            $this->redirect('/dashboard');
        }
    }
    
    /**
     * Show rejected applications
     */
    public function rejected() {
        try {
            $this->requireAuth();
            
            // Only Admin and SuperAdmin can view rejected list
            if (!in_array($_SESSION['role'], ['Admin', 'SuperAdmin'])) {
                $_SESSION['error'] = 'You do not have permission to view this page';
                $this->redirect('/dashboard');
                return;
            }
            
            $applications = $this->statusModel->getRejectedApplications(100);
            
            $this->render('migrants/rejected', [
                'title' => 'Rejected Applications',
                'applications' => $applications
            ]);
            
        } catch (\Exception $e) {
            error_log("ERROR in rejected(): " . $e->getMessage());
            $_SESSION['error'] = 'Unable to load rejected applications';
            $this->redirect('/dashboard');
        }
    }
    
    /**
     * Get migrant photo for direct display
     */
    public function photo($params) {
        try {
            $this->requireAuth();
            
            $person_id = $params['id'] ?? '';
            if (empty($person_id)) {
                header("HTTP/1.0 404 Not Found");
                exit;
            }
            
            $db = $this->migrantModel->getConnection();
            $stmt = $db->prepare("SELECT photo_data, photo_format FROM biographical_information WHERE person_id = ?");
            $stmt->execute([$person_id]);
            $photo = $stmt->fetch();
            
            if ($photo && !empty($photo['photo_data'])) {
                header("Content-Type: image/" . ($photo['photo_format'] ?? 'jpeg'));
                echo $photo['photo_data'];
            } else {
                // Return default placeholder
                header("Content-Type: image/svg+xml");
                echo '<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
                    <rect width="200" height="200" fill="#f0f0f0"/>
                    <text x="100" y="115" font-family="Arial" font-size="14" fill="#999" text-anchor="middle">No Photo</text>
                </svg>';
            }
            exit;
            
        } catch (\Exception $e) {
            error_log("ERROR in photo(): " . $e->getMessage());
            header("HTTP/1.0 500 Internal Server Error");
            exit;
        }
    }
    
    /**
     * Handle document uploads
     */
    protected function handleDocumentUploads($person_id, $files) {
        try {
            if (!$this->uploadService) {
                error_log("UploadService not available - skipping file uploads");
                return;
            }
            
            $uploaded = $this->uploadService->uploadMultiple($files, 'documents/' . $person_id);
            
            foreach ($uploaded as $file) {
                $this->documentModel->create([
                    'person_id' => $person_id,
                    'document_type' => $file['original_name'],
                    'file_name' => $file['filename'],
                    'file_path' => $file['filepath'],
                    'file_size' => $file['size'],
                    'mime_type' => $file['mime_type'],
                    'uploaded_by' => $_SESSION['user_id']
                ]);
            }
        } catch (\Exception $e) {
            error_log("Error in handleDocumentUploads: " . $e->getMessage());
        }
    }
    
    /**
     * Index page - redirect to search
     */
    public function index() {
        $this->requireAuth();
        $this->redirect('/migrants/search');
    }
    
    // =============================================
    // DEPENDANT MANAGEMENT METHODS
    // =============================================
    
    /**
     * Add dependant to migrant
     */
    public function addDependant() {
        try {
            $this->requireAuth();
            
            // Set header for JSON response
            header('Content-Type: application/json');
            
            // Log the received data for debugging
            error_log("=== ADD DEPENDANT CALLED ===");
            error_log("POST data: " . print_r($_POST, true));
            
            // Verify CSRF token
            if (!isset($_POST['csrf_token']) || !\Security::validateCSRFToken($_POST['csrf_token'])) {
                error_log("CSRF validation failed");
                echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
                return;
            }
            
            $person_id = $_POST['person_id'] ?? '';
            $surname = strtoupper(trim($_POST['surname'] ?? ''));
            $given_name = strtoupper(trim($_POST['given_name'] ?? ''));
            $date_of_birth = $_POST['date_of_birth'] ?? '';
            $gender = $_POST['gender'] ?? '';
            $document_no = !empty($_POST['document_no']) ? strtoupper(trim($_POST['document_no'])) : null;
            $relationship = $_POST['relationship'] ?? '';
            
            // Validate required fields
            if (empty($person_id) || empty($surname) || empty($given_name) || 
                empty($date_of_birth) || empty($gender) || empty($relationship)) {
                echo json_encode(['success' => false, 'error' => 'All required fields must be filled']);
                return;
            }
            
            // Validate age (must be under 18)
            try {
                $dob = new \DateTime($date_of_birth);
                $now = new \DateTime();
                $age = $now->diff($dob)->y;
                
                if ($age >= 18) {
                    echo json_encode(['success' => false, 'error' => 'Dependant must be under 18 years old']);
                    return;
                }
            } catch (\Exception $e) {
                echo json_encode(['success' => false, 'error' => 'Invalid date format']);
                return;
            }
            
            // Check if person exists
            $migrant = $this->migrantModel->find($person_id);
            if (!$migrant) {
                echo json_encode(['success' => false, 'error' => 'Migrant not found']);
                return;
            }
            
            $db = $this->migrantModel->getConnection();
            
            // Check if table exists
            $tableCheck = $db->query("SHOW TABLES LIKE 'dependants'");
            if ($tableCheck->rowCount() == 0) {
                echo json_encode(['success' => false, 'error' => 'Database table not found']);
                return;
            }
            
            // Insert dependant
            $sql = "INSERT INTO dependants (person_id, surname, given_name, date_of_birth, gender, document_no, relationship, created_by)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $db->prepare($sql);
            $result = $stmt->execute([
                $person_id, 
                $surname, 
                $given_name, 
                $date_of_birth, 
                $gender, 
                $document_no, 
                $relationship,
                $_SESSION['user_id'] ?? 'system'
            ]);
            
            if ($result) {
                $id = $db->lastInsertId();
                echo json_encode(['success' => true, 'message' => 'Dependant added successfully', 'id' => $id]);
            } else {
                echo json_encode(['success' => false, 'error' => 'Failed to add dependant']);
            }
            
        } catch (\Exception $e) {
            error_log("ERROR in addDependant(): " . $e->getMessage());
            echo json_encode(['success' => false, 'error' => 'Server error occurred']);
        }
    }
    
    /**
     * Get dependants for a migrant
     */
    public function getDependants($params) {
        try {
            $this->requireAuth();
            
            header('Content-Type: application/json');
            
            $person_id = $params['id'] ?? '';
            if (empty($person_id)) {
                echo json_encode(['success' => false, 'error' => 'Invalid person ID']);
                return;
            }
            
            $db = $this->migrantModel->getConnection();
            
            // Check if table exists
            $tableCheck = $db->query("SHOW TABLES LIKE 'dependants'");
            if ($tableCheck->rowCount() == 0) {
                echo json_encode(['success' => true, 'data' => []]);
                return;
            }
            
            $stmt = $db->prepare("SELECT * FROM dependants WHERE person_id = ? AND deleted_at IS NULL ORDER BY created_at DESC");
            $stmt->execute([$person_id]);
            $dependants = $stmt->fetchAll();
            
            echo json_encode(['success' => true, 'data' => $dependants]);
            
        } catch (\Exception $e) {
            error_log("Error getting dependants: " . $e->getMessage());
            echo json_encode(['success' => false, 'error' => 'Failed to retrieve dependants']);
        }
    }
    
    /**
     * Delete dependant
     */
    public function deleteDependant() {
        try {
            $this->requireAuth();
            
            header('Content-Type: application/json');
            
            // Verify CSRF token
            if (!isset($_POST['csrf_token']) || !\Security::validateCSRFToken($_POST['csrf_token'])) {
                echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
                return;
            }
            
            $id = $_POST['id'] ?? 0;
            if (empty($id)) {
                echo json_encode(['success' => false, 'error' => 'Invalid dependant ID']);
                return;
            }
            
            $db = $this->migrantModel->getConnection();
            
            $stmt = $db->prepare("UPDATE dependants SET deleted_at = NOW() WHERE id = ?");
            $result = $stmt->execute([$id]);
            
            if ($result) {
                echo json_encode(['success' => true, 'message' => 'Dependant deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'error' => 'Failed to delete dependant']);
            }
            
        } catch (\Exception $e) {
            error_log("Error deleting dependant: " . $e->getMessage());
            echo json_encode(['success' => false, 'error' => 'Database error occurred']);
        }
    }
}