<?php
/**
 * Document Processing Page
 * Upload and process documents using OCR
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';
require_once 'classes/DocumentProcessor.php';

requireLogin();

$documentProcessor = new DocumentProcessor($conn);
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['document'])) {
    $documentType = $_POST['document_type'] ?? '';
    $member_id = $_POST['member_id'] ?? null;
    
    if (empty($documentType)) {
        $message = 'Document type is required';
        $messageType = 'danger';
    } elseif ($_FILES['document']['error'] !== UPLOAD_ERR_OK) {
        $message = 'File upload error';
        $messageType = 'danger';
    } else {
        // Upload file
        $uploadDir = 'uploads/documents/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $fileName = time() . '_' . basename($_FILES['document']['name']);
        $filePath = $uploadDir . $fileName;
        
        if (move_uploaded_file($_FILES['document']['tmp_name'], $filePath)) {
            // Process document
            $result = $documentProcessor->processDocument($filePath, $documentType);
            
            if ($result['success']) {
                // Save processed document
                if ($member_id) {
                    $saveResult = $documentProcessor->saveProcessedDocument(
                        $member_id,
                        $documentType,
                        $filePath,
                        $result['extracted_data'] ?? []
                    );
                }
                
                $message = 'Document processed successfully';
                $messageType = 'success';
                $extractedData = $result['extracted_data'] ?? [];
            } else {
                $message = $result['message'] ?? 'Failed to process document';
                $messageType = 'danger';
            }
        } else {
            $message = 'Failed to upload file';
            $messageType = 'danger';
        }
    }
}

$pageTitle = 'Process Document';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Process Document')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="welcome-header" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Document Processing</h2>
                                <p>Upload and extract data from documents using OCR</p>
                            </div>
                        </div>
                    </div>

                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Upload Document</h4>
                                </div>
                                <div class="page-card-body">
                                    <form method="POST" enctype="multipart/form-data">
                                        <div class="mb-3">
                                            <label class="form-label">Document Type <span class="text-danger">*</span></label>
                                            <select name="document_type" class="form-select" required>
                                                <option value="">Select Type</option>
                                                <option value="NATIONAL_ID">National ID</option>
                                                <option value="BIRTH_CERTIFICATE">Birth Certificate</option>
                                                <option value="CLAIM_DOCUMENT">Claim Document</option>
                                                <option value="BANK_STATEMENT">Bank Statement</option>
                                                <option value="OTHER">Other</option>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Member (Optional)</label>
                                            <select name="member_id" class="form-select">
                                                <option value="">Select Member</option>
                                                <?php
                                                $members = $conn->query("SELECT member_id, member_number, first_name, last_name FROM members WHERE is_active = 1 ORDER BY member_number");
                                                while ($member = $members->fetch_assoc()):
                                                ?>
                                                    <option value="<?php echo $member['member_id']; ?>">
                                                        <?php echo htmlspecialchars($member['member_number'] . ' - ' . $member['first_name'] . ' ' . $member['last_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Document File <span class="text-danger">*</span></label>
                                            <input type="file" name="document" class="form-control" accept="image/*,.pdf" required>
                                            <small class="text-muted">Supported formats: JPG, PNG, PDF</small>
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-upload-line me-2"></i>Process Document
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <?php if (isset($extractedData) && !empty($extractedData)): ?>
                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Extracted Data</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Field</th>
                                                    <th>Value</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($extractedData as $key => $value): ?>
                                                    <tr>
                                                        <td><strong><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $key))); ?></strong></td>
                                                        <td><?php echo htmlspecialchars($value ?? 'N/A'); ?></td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <div class="alert alert-info mt-3">
                                        <i class="ri-information-line me-2"></i>
                                        <strong>Note:</strong> Please verify extracted data for accuracy. OCR may not be 100% accurate.
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
