<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'My Documents';

if (!$auth->isLoggedIn() || $auth->isAdmin()) {
    header('Location: ../login.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Get user's profile data
$sql = "SELECT * FROM user_profile_data WHERE user_id = ?";
$profile_data = $db->fetchOne($sql, [$current_user['id']]);

// Collect all documents
$documents = [];

if ($profile_data) {
    $doc_fields = [
        'id_front_image' => ['name' => 'ID Card (Front)', 'icon' => 'fa-id-card', 'type' => 'Identity'],
        'id_back_image' => ['name' => 'ID Card (Back)', 'icon' => 'fa-id-card', 'type' => 'Identity'],
        'passport_photo' => ['name' => 'Passport Photo', 'icon' => 'fa-portrait', 'type' => 'Identity'],
        'employment_letter' => ['name' => 'Employment Letter', 'icon' => 'fa-file-alt', 'type' => 'Employment'],
        'bank_statement' => ['name' => 'Bank Statement', 'icon' => 'fa-file-invoice-dollar', 'type' => 'Financial'],
        'business_registration' => ['name' => 'Business Registration', 'icon' => 'fa-certificate', 'type' => 'Business'],
        'guarantor_form' => ['name' => 'Guarantor Form', 'icon' => 'fa-file-signature', 'type' => 'Guarantor']
    ];
    
    foreach ($doc_fields as $field => $info) {
        if (!empty($profile_data[$field])) {
            $documents[] = array_merge($info, [
                'path' => $profile_data[$field],
                'uploaded' => $profile_data['created_at']
            ]);
        }
    }
}

include 'includes/header.php';
?>

<style>
    .document-card {
        transition: all 0.3s;
        cursor: pointer;
    }
    
    .document-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 20px rgba(0,0,0,0.15);
    }
    
    .doc-icon {
        width: 80px;
        height: 80px;
        border-radius: 15px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2.5rem;
        margin-bottom: 15px;
    }
    
    .upload-zone {
        border: 3px dashed #ddd;
        border-radius: 15px;
        padding: 40px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
    }
    
    .upload-zone:hover {
        border-color: var(--primary);
        background: rgba(212, 160, 23, 0.05);
    }
    
    .upload-zone.dragover {
        border-color: var(--primary);
        background: rgba(212, 160, 23, 0.1);
    }
    
    .category-badge {
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 600;
    }
</style>

<div class="page-header">
    <h1>Document Center</h1>
    <p class="text-muted mb-0">Manage all your documents in one place</p>
</div>

<!-- Document Statistics -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card text-center p-3" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
            <i class="fas fa-folder fa-3x text-white mb-2"></i>
            <h3 class="text-white mb-1"><?php echo count($documents); ?></h3>
            <small class="text-white opacity-75">Total Documents</small>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card text-center p-3" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">
            <i class="fas fa-check-circle fa-3x text-white mb-2"></i>
            <h3 class="text-white mb-1">
                <?php echo $current_user['status'] === 'active' ? 'Verified' : 'Pending'; ?>
            </h3>
            <small class="text-white opacity-75">Verification Status</small>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card text-center p-3" style="background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%);">
            <i class="fas fa-shield-alt fa-3x text-white mb-2"></i>
            <h3 class="text-white mb-1">Secure</h3>
            <small class="text-white opacity-75">256-bit Encryption</small>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card text-center p-3" style="background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);">
            <i class="fas fa-cloud fa-3x text-white mb-2"></i>
            <h3 class="text-white mb-1">Cloud</h3>
            <small class="text-white opacity-75">Stored Safely</small>
        </div>
    </div>
</div>

<!-- Document Categories -->
<div class="row mb-4">
    <div class="col-12">
        <div class="btn-group" role="group">
            <button type="button" class="btn btn-outline-primary active" data-filter="all">
                All Documents
            </button>
            <button type="button" class="btn btn-outline-primary" data-filter="Identity">
                Identity
            </button>
            <button type="button" class="btn btn-outline-primary" data-filter="Employment">
                Employment
            </button>
            <button type="button" class="btn btn-outline-primary" data-filter="Financial">
                Financial
            </button>
            <button type="button" class="btn btn-outline-primary" data-filter="Business">
                Business
            </button>
            <button type="button" class="btn btn-outline-primary" data-filter="Guarantor">
                Guarantor
            </button>
        </div>
    </div>
</div>

<!-- Documents Grid -->
<?php if (empty($documents)): ?>
<div class="card">
    <div class="card-body text-center py-5">
        <i class="fas fa-folder-open fa-5x text-muted mb-4"></i>
        <h4 class="text-muted">No Documents Yet</h4>
        <p class="text-muted mb-4">Complete your profile to upload documents</p>
        <a href="complete-profile.php" class="btn btn-primary btn-lg">
            <i class="fas fa-user-edit"></i> Complete Profile
        </a>
    </div>
</div>
<?php else: ?>
<div class="row" id="documentsGrid">
    <?php foreach ($documents as $doc): ?>
    <div class="col-md-6 col-lg-4 mb-4 document-item" data-category="<?php echo $doc['type']; ?>">
        <div class="card document-card h-100">
            <div class="card-body text-center">
                <div class="doc-icon mx-auto" style="background: rgba(212, 160, 23, 0.1); color: var(--primary);">
                    <i class="fas <?php echo $doc['icon']; ?>"></i>
                </div>
                
                <h6 class="mb-2"><?php echo htmlspecialchars($doc['name']); ?></h6>
                
                <span class="category-badge mb-3" style="background: rgba(212, 160, 23, 0.1); color: var(--primary);">
                    <?php echo $doc['type']; ?>
                </span>
                
                <p class="text-muted small mb-3">
                    <i class="far fa-calendar"></i>
                    Uploaded: <?php echo date('M d, Y', strtotime($doc['uploaded'])); ?>
                </p>
                
                <div class="d-grid gap-2">
                    <a href="../<?php echo htmlspecialchars($doc['path']); ?>" 
                       target="_blank" 
                       class="btn btn-outline-primary">
                        <i class="fas fa-eye"></i> View
                    </a>
                    <a href="../<?php echo htmlspecialchars($doc['path']); ?>" 
                       download 
                       class="btn btn-outline-success">
                        <i class="fas fa-download"></i> Download
                    </a>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Add More Documents -->
<div class="card mt-4">
    <div class="card-header">
        <h5 class="mb-0"><i class="fas fa-plus-circle"></i> Upload Additional Documents</h5>
    </div>
    <div class="card-body">
        <div class="upload-zone" id="uploadZone">
            <i class="fas fa-cloud-upload-alt fa-4x text-primary mb-3"></i>
            <h5>Drag & Drop Files Here</h5>
            <p class="text-muted">or click to browse</p>
            <input type="file" id="fileInput" multiple accept=".pdf,.jpg,.jpeg,.png" style="display: none;">
            <small class="text-muted">Supported formats: PDF, JPG, PNG (Max 5MB per file)</small>
        </div>
        
        <div id="uploadProgress" class="mt-3" style="display: none;">
            <div class="progress">
                <div class="progress-bar progress-bar-striped progress-bar-animated" 
                     role="progressbar" style="width: 0%"></div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Document Security Info -->
<div class="card mt-4">
    <div class="card-header">
        <h5 class="mb-0"><i class="fas fa-shield-alt"></i> Document Security</h5>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-3 text-center mb-3">
                <i class="fas fa-lock fa-3x text-success mb-2"></i>
                <h6>256-bit Encryption</h6>
                <small class="text-muted">Bank-level security</small>
            </div>
            <div class="col-md-3 text-center mb-3">
                <i class="fas fa-server fa-3x text-primary mb-2"></i>
                <h6>Secure Storage</h6>
                <small class="text-muted">Encrypted at rest</small>
            </div>
            <div class="col-md-3 text-center mb-3">
                <i class="fas fa-user-shield fa-3x text-info mb-2"></i>
                <h6>NDPR Compliant</h6>
                <small class="text-muted">Privacy protected</small>
            </div>
            <div class="col-md-3 text-center mb-3">
                <i class="fas fa-trash-alt fa-3x text-warning mb-2"></i>
                <h6>Your Control</h6>
                <small class="text-muted">Delete anytime</small>
            </div>
        </div>
        
        <div class="alert alert-info mb-0 mt-3">
            <i class="fas fa-info-circle"></i>
            <strong>Privacy Notice:</strong> Your documents are encrypted and only accessible by you and authorized administrators. 
            We never share your documents with third parties without your explicit consent.
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Category filter
    $('[data-filter]').click(function() {
        $('[data-filter]').removeClass('active');
        $(this).addClass('active');
        
        const filter = $(this).data('filter');
        
        if (filter === 'all') {
            $('.document-item').fadeIn();
        } else {
            $('.document-item').hide();
            $('.document-item[data-category="' + filter + '"]').fadeIn();
        }
    });
    
    // Upload zone
    const uploadZone = $('#uploadZone');
    const fileInput = $('#fileInput');
    
    uploadZone.click(function() {
        fileInput.click();
    });
    
    // Drag and drop
    uploadZone.on('dragover', function(e) {
        e.preventDefault();
        $(this).addClass('dragover');
    });
    
    uploadZone.on('dragleave', function(e) {
        e.preventDefault();
        $(this).removeClass('dragover');
    });
    
    uploadZone.on('drop', function(e) {
        e.preventDefault();
        $(this).removeClass('dragover');
        
        const files = e.originalEvent.dataTransfer.files;
        handleFiles(files);
    });
    
    fileInput.change(function() {
        handleFiles(this.files);
    });
    
    function handleFiles(files) {
        if (files.length === 0) return;
        
        // Validate files
        let valid = true;
        for (let file of files) {
            if (file.size > 5242880) {
                Swal.fire({
                    icon: 'error',
                    title: 'File Too Large',
                    text: file.name + ' exceeds 5MB limit'
                });
                valid = false;
                break;
            }
        }
        
        if (!valid) return;
        
        // Show upload progress
        $('#uploadProgress').show();
        $('.progress-bar').css('width', '0%');
        
        // Simulate upload (replace with actual upload logic)
        let progress = 0;
        const interval = setInterval(function() {
            progress += 10;
            $('.progress-bar').css('width', progress + '%');
            
            if (progress >= 100) {
                clearInterval(interval);
                setTimeout(function() {
                    $('#uploadProgress').hide();
                    Swal.fire({
                        icon: 'success',
                        title: 'Upload Successful',
                        text: files.length + ' document(s) uploaded successfully',
                        timer: 2000
                    }).then(() => {
                        location.reload();
                    });
                }, 500);
            }
        }, 200);
    }
});
</script>

<?php include 'includes/footer.php'; ?>