<?php
require_once 'Database.php';
require_once 'Security.php';

class KYC {
    private $db;
    
    public function __construct() {
        $this->db = new Database();
    }
    
    // Submit KYC document
    public function submitDocument($userId, $documentType, $documentNumber, $file) {
        try {
            // Validate file upload
            $validation = Security::validateFileUpload($file);
            if (!$validation['success']) {
                return $validation;
            }
            
            // Generate unique filename
            $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $filename = 'kyc_' . $userId . '_' . $documentType . '_' . time() . '.' . $extension;
            $filePath = UPLOAD_PATH . 'kyc/' . $filename;
            
            // Create directory if it doesn't exist
            if (!file_exists(UPLOAD_PATH . 'kyc/')) {
                mkdir(UPLOAD_PATH . 'kyc/', 0755, true);
            }
            
            // Move uploaded file
            if (!move_uploaded_file($file['tmp_name'], $filePath)) {
                return ['success' => false, 'message' => 'File upload failed'];
            }
            
            // Save document record
            $this->db->query("INSERT INTO kyc_documents (user_id, document_type, document_number, file_path) 
                             VALUES (:user_id, :doc_type, :doc_number, :file_path)");
            $this->db->bind(':user_id', $userId);
            $this->db->bind(':doc_type', $documentType);
            $this->db->bind(':doc_number', $documentNumber);
            $this->db->bind(':file_path', $filePath);
            
            if (!$this->db->execute()) {
                unlink($filePath); // Remove file if database insert fails
                return ['success' => false, 'message' => 'Failed to save document record'];
            }
            
            $documentId = $this->db->lastInsertId();
            
            // Update user KYC status to pending if this is their first document
            $this->updateUserKYCStatus($userId);
            
            Security::logSecurityEvent('KYC_DOCUMENT_SUBMITTED', "Submitted $documentType document", $userId);
            
            return [
                'success' => true, 
                'message' => 'Document submitted successfully',
                'document_id' => $documentId
            ];
            
        } catch (Exception $e) {
            error_log('KYC document submission error: ' . $e->getMessage());
            return ['success' => false, 'message' => 'Document submission failed'];
        }
    }
    
    // Get user's KYC documents
    public function getUserDocuments($userId) {
        $this->db->query("SELECT d.*, u.username as reviewed_by_username 
                         FROM kyc_documents d 
                         LEFT JOIN users u ON d.reviewed_by = u.id 
                         WHERE d.user_id = :user_id 
                         ORDER BY d.submitted_at DESC");
        $this->db->bind(':user_id', $userId);
        return $this->db->resultSet();
    }
    
    // Get pending KYC documents (admin)
    public function getPendingDocuments($limit = 50) {
        $this->db->query("SELECT d.*, u.username, u.email, u.first_name, u.last_name 
                         FROM kyc_documents d 
                         JOIN users u ON d.user_id = u.id 
                         WHERE d.status = 'pending' 
                         ORDER BY d.submitted_at ASC 
                         LIMIT :limit");
        $this->db->bind(':limit', $limit);
        return $this->db->resultSet();
    }
    
    // Review KYC document (admin)
    public function reviewDocument($documentId, $reviewerId, $status, $rejectionReason = null) {
        try {
            $this->db->beginTransaction();
            
            // Get document details
            $this->db->query("SELECT * FROM kyc_documents WHERE id = :doc_id");
            $this->db->bind(':doc_id', $documentId);
            $document = $this->db->single();
            
            if (!$document) {
                throw new Exception('Document not found');
            }
            
            // Update document status
            $this->db->query("UPDATE kyc_documents SET 
                             status = :status, 
                             rejection_reason = :reason, 
                             reviewed_at = NOW(), 
                             reviewed_by = :reviewer_id 
                             WHERE id = :doc_id");
            
            $this->db->bind(':status', $status);
            $this->db->bind(':reason', $rejectionReason);
            $this->db->bind(':reviewer_id', $reviewerId);
            $this->db->bind(':doc_id', $documentId);
            
            if (!$this->db->execute()) {
                throw new Exception('Failed to update document status');
            }
            
            // Update user's overall KYC status
            $this->updateUserKYCStatus($document['user_id']);
            
            $this->db->endTransaction();
            
            Security::logSecurityEvent('KYC_DOCUMENT_REVIEWED', 
                                     "Document #$documentId reviewed as $status", 
                                     $reviewerId);
            
            return ['success' => true, 'message' => 'Document reviewed successfully'];
            
        } catch (Exception $e) {
            $this->db->cancelTransaction();
            error_log('KYC document review error: ' . $e->getMessage());
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
    
    // Update user's overall KYC status
    private function updateUserKYCStatus($userId) {
        // Get user's documents
        $this->db->query("SELECT document_type, status FROM kyc_documents WHERE user_id = :user_id");
        $this->db->bind(':user_id', $userId);
        $documents = $this->db->resultSet();
        
        if (empty($documents)) {
            return; // No documents submitted
        }
        
        // Define required documents for different KYC levels
        $requiredDocs = [
            'level1' => ['passport', 'driver_license', 'national_id'], // Any one of these
            'level2' => ['utility_bill', 'bank_statement'] // Any one of these
        ];
        
        $approvedTypes = [];
        $hasRejected = false;
        $hasPending = false;
        
        foreach ($documents as $doc) {
            if ($doc['status'] === 'approved') {
                $approvedTypes[] = $doc['document_type'];
            } elseif ($doc['status'] === 'rejected') {
                $hasRejected = true;
            } elseif ($doc['status'] === 'pending') {
                $hasPending = true;
            }
        }
        
        // Determine KYC status and level
        $kycStatus = 'pending';
        $kycLevel = 0;
        
        // Check for Level 1 (Identity document)
        $hasLevel1 = !empty(array_intersect($approvedTypes, $requiredDocs['level1']));
        
        // Check for Level 2 (Address document)  
        $hasLevel2 = !empty(array_intersect($approvedTypes, $requiredDocs['level2']));
        
        if ($hasLevel1 && $hasLevel2) {
            $kycStatus = 'verified';
            $kycLevel = 2;
        } elseif ($hasLevel1) {
            $kycStatus = 'verified';
            $kycLevel = 1;
        } elseif ($hasRejected && !$hasPending) {
            $kycStatus = 'rejected';
            $kycLevel = 0;
        }
        
        // Update user record
        $this->db->query("UPDATE users SET kyc_status = :status, kyc_level = :level WHERE id = :user_id");
        $this->db->bind(':status', $kycStatus);
        $this->db->bind(':level', $kycLevel);
        $this->db->bind(':user_id', $userId);
        $this->db->execute();
    }
    
    // Get KYC statistics (admin)
    public function getKYCStats() {
        $stats = [];
        
        // Total users by KYC status
        $this->db->query("SELECT kyc_status, COUNT(*) as count FROM users GROUP BY kyc_status");
        $statusStats = $this->db->resultSet();
        
        foreach ($statusStats as $stat) {
            $stats['users_by_status'][$stat['kyc_status']] = $stat['count'];
        }
        
        // Pending documents count
        $this->db->query("SELECT COUNT(*) as count FROM kyc_documents WHERE status = 'pending'");
        $pendingDocs = $this->db->single();
        $stats['pending_documents'] = $pendingDocs['count'];
        
        // Documents by type
        $this->db->query("SELECT document_type, COUNT(*) as count FROM kyc_documents GROUP BY document_type");
        $typeStats = $this->db->resultSet();
        
        foreach ($typeStats as $stat) {
            $stats['documents_by_type'][$stat['document_type']] = $stat['count'];
        }
        
        return $stats;
    }
    
    // Check if user can trade based on KYC level
    public function canUserTrade($userId, $amount = 0) {
        $this->db->query("SELECT kyc_status, kyc_level FROM users WHERE id = :user_id");
        $this->db->bind(':user_id', $userId);
        $user = $this->db->single();
        
        if (!$user || $user['kyc_status'] !== 'verified') {
            return [
                'can_trade' => false, 
                'message' => 'KYC verification required',
                'required_level' => 1
            ];
        }
        
        // Define trading limits based on KYC level
        $limits = [
            1 => 1000,    // Level 1: Up to $1,000 per day
            2 => 10000    // Level 2: Up to $10,000 per day
        ];
        
        $userLimit = $limits[$user['kyc_level']] ?? 0;
        
        if ($amount > $userLimit) {
            return [
                'can_trade' => false,
                'message' => "Trade amount exceeds your KYC limit of $userLimit",
                'current_limit' => $userLimit,
                'required_level' => 2
            ];
        }
        
        return [
            'can_trade' => true,
            'current_limit' => $userLimit,
            'kyc_level' => $user['kyc_level']
        ];
    }
}
?>