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

$page_title = 'Document Verification';

if (!$auth->hasPermission('can_verify_documents') && !$auth->hasRole('super_admin')) {
    $_SESSION['error'] = "You don't have permission to access this page";
    header('Location: dashboard.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!Security::validateCSRFToken($_POST['csrf_token'])) {
        die('Invalid CSRF token');
    }
    
    $action = $_POST['action'];
    $doc_id = (int)$_POST['doc_id'];
    
    if ($action === 'verify') {
        $notes = $_POST['verification_notes'] ?? '';
        $sql = "UPDATE document_verifications SET 
                verification_status = 'verified',
                verification_notes = ?,
                verified_by = ?,
                verified_at = NOW()
                WHERE id = ?";
        
        if ($db->execute($sql, [$notes, $current_user['id'], $doc_id])) {
            $_SESSION['success'] = "Document verified successfully";
        }
    }
    
    if ($action === 'reject') {
        $notes = $_POST['verification_notes'] ?? '';
        $sql = "UPDATE document_verifications SET 
                verification_status = 'failed',
                verification_notes = ?,
                verified_by = ?,
                verified_at = NOW()
                WHERE id = ?";
        
        if ($db->execute($sql, [$notes, $current_user['id'], $doc_id])) {
            $_SESSION['success'] = "Document rejected";
        }
    }
    
    header('Location: document-verification.php');
    exit;
}

// Get documents
$status_filter = $_GET['status'] ?? 'pending';
$search = $_GET['search'] ?? '';

$where = ["verification_status = ?"];
$params = [$status_filter];

if ($search) {
    $where[] = "verification_code LIKE ?";
    $params[] = "%$search%";
}

$sql = "SELECT dv.*, p.title as property_title, l.title as land_title,
        CONCAT(u.first_name, ' ', u.last_name) as verified_by_name
        FROM document_verifications dv
        LEFT JOIN properties p ON dv.property_id = p.id
        LEFT JOIN lands l ON dv.land_id = l.id
        LEFT JOIN users u ON dv.verified_by = u.id
        WHERE " . implode(' AND ', $where) . "
        ORDER BY dv.created_at DESC";

$documents = $db->fetchAll($sql, $params);

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Document Verification</h1>
</div>

<div class="card">
    <div class="card-header">
        <ul class="nav nav-tabs card-header-tabs">
            <li class="nav-item">
                <a class="nav-link <?php echo $status_filter === 'pending' ? 'active' : ''; ?>" 
                   href="?status=pending">
                    Pending <span class="badge bg-warning">
                        <?php echo $db->fetchOne("SELECT COUNT(*) as c FROM document_verifications WHERE verification_status = 'pending'")['c']; ?>
                    </span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $status_filter === 'verified' ? 'active' : ''; ?>" 
                   href="?status=verified">
                    Verified
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $status_filter === 'failed' ? 'active' : ''; ?>" 
                   href="?status=failed">
                    Failed
                </a>
            </li>
        </ul>
    </div>
    
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Code</th>
                        <th>Type</th>
                        <th>Property/Land</th>
                        <th>Document</th>
                        <th>Payment</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($documents as $doc): ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($doc['verification_code']); ?></strong></td>
                        <td><?php echo ucfirst($doc['document_type']); ?></td>
                        <td><?php echo htmlspecialchars($doc['property_title'] ?? $doc['land_title'] ?? 'N/A'); ?></td>
                        <td>
                            <a href="../<?php echo htmlspecialchars($doc['document_path']); ?>" 
                               target="_blank" class="btn btn-sm btn-outline-primary">
                                <i class="fas fa-file-pdf"></i> View
                            </a>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo $doc['payment_status'] === 'paid' ? 'success' : 'warning'; ?>">
                                <?php echo ucfirst($doc['payment_status']); ?>
                            </span>
                        </td>
                        <td><?php echo date('M d, Y', strtotime($doc['created_at'])); ?></td>
                        <td>
                            <?php if ($doc['verification_status'] === 'pending'): ?>
                            <button class="btn btn-sm btn-success verify-doc" 
                                    data-id="<?php echo $doc['id']; ?>">
                                <i class="fas fa-check"></i> Verify
                            </button>
                            <button class="btn btn-sm btn-danger reject-doc" 
                                    data-id="<?php echo $doc['id']; ?>">
                                <i class="fas fa-times"></i> Reject
                            </button>
                            <?php else: ?>
                            <small class="text-muted">
                                By: <?php echo htmlspecialchars($doc['verified_by_name'] ?? 'N/A'); ?>
                            </small>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Verification Modal -->
<div class="modal fade" id="verificationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">Verify Document</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action" id="modalAction">
                    <input type="hidden" name="doc_id" id="modalDocId">
                    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                    
                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea name="verification_notes" class="form-control" rows="3" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="modalSubmit">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    $('.verify-doc').click(function() {
        $('#modalTitle').text('Verify Document');
        $('#modalAction').val('verify');
        $('#modalDocId').val($(this).data('id'));
        $('#modalSubmit').removeClass('btn-danger').addClass('btn-success').text('Verify');
        $('#verificationModal').modal('show');
    });
    
    $('.reject-doc').click(function() {
        $('#modalTitle').text('Reject Document');
        $('#modalAction').val('reject');
        $('#modalDocId').val($(this).data('id'));
        $('#modalSubmit').removeClass('btn-success').addClass('btn-danger').text('Reject');
        $('#verificationModal').modal('show');
    });
</script>

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