<?php
require_once 'header.php'; 
$page_title = 'Submit Documents';

// --- Handle File Upload Logic ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['document_type'])) {
    $doc_type = $_POST['document_type'];
    
    if (isset($_FILES['document_file']) && $_FILES['document_file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['document_file'];
        $upload_dir = '../uploads/documents/';
        if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }

        $filename = 'partner-' . $partner_id . '-' . $doc_type . '-' . time() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
        $target_path = $upload_dir . $filename;

        if (move_uploaded_file($file['tmp_name'], $target_path)) {
            $db_path = 'uploads/documents/' . $filename;
            
            // Use INSERT ... ON DUPLICATE KEY UPDATE to handle both new and re-uploads
            $stmt = $conn->prepare("
                INSERT INTO partner_documents (partner_id, document_type, file_url, status) 
                VALUES (?, ?, ?, 'Pending') 
                ON DUPLICATE KEY UPDATE file_url = VALUES(file_url), status = 'Pending'
            ");
            $stmt->bind_param("iss", $partner_id, $doc_type, $db_path);
            $stmt->execute();
            $stmt->close();

            // Update the user's main verification status
            $conn->query("UPDATE users SET verification_status = 'pending_review' WHERE id = $partner_id");

            $_SESSION['success_message'] = ucfirst(str_replace('_', ' ', $doc_type)) . " uploaded successfully. It is now pending review.";
        } else {
            $_SESSION['error_message'] = "There was an error moving the uploaded file.";
        }
    } else {
        $_SESSION['error_message'] = "No file was uploaded or an error occurred.";
    }
    header("Location: submit-documents.php");
    exit();
}

// --- Fetch existing documents for status display ---
$docs_result = $conn->query("SELECT document_type, status, admin_notes FROM partner_documents WHERE partner_id = $partner_id");
$documents = [];
while ($row = $docs_result->fetch_assoc()) {
    $documents[$row['document_type']] = $row;
}

// Helper for status badges
function get_doc_status_badge($status) {
    switch (strtolower($status)) {
        case 'approved': return 'bg-success';
        case 'pending': return 'bg-warning text-dark';
        case 'rejected': return 'bg-danger';
        default: return 'bg-secondary';
    }
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="bi bi-file-earmark-check-fill me-2"></i>Verification Documents</h1>
</div>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php elseif (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="alert alert-info">
    <h4 class="alert-heading">Welcome, Partner!</h4>
    <p>To activate your account and start adding your listings, please submit the required verification documents below. Our team will review them within 24-48 hours.</p>
</div>

<div class="row">
    <?php 
    $required_docs = [
        'business_permit' => 'Business Permit / Mayor\'s Permit',
        'valid_id' => 'Valid Government ID of Owner'
    ];
    foreach($required_docs as $key => $title): 
        $doc = $documents[$key] ?? null;
    ?>
    <div class="col-lg-6 mb-4">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <h5 class="card-title"><?php echo $title; ?></h5>
                <p>Status: 
                    <span class="badge <?php echo get_doc_status_badge($doc['status'] ?? 'Not Submitted'); ?>">
                        <?php echo ucfirst($doc['status'] ?? 'Not Submitted'); ?>
                    </span>
                </p>

                <?php if (isset($doc['status']) && $doc['status'] === 'Rejected' && !empty($doc['admin_notes'])): ?>
                    <div class="alert alert-danger small">
                        <strong>Reason for Rejection:</strong> <?php echo htmlspecialchars($doc['admin_notes']); ?>
                    </div>
                <?php endif; ?>

                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="document_type" value="<?php echo $key; ?>">
                    <div class="input-group">
                        <input type="file" class="form-control" name="document_file" accept=".pdf,.jpg,.jpeg,.png" required <?php if(isset($doc['status']) && $doc['status'] === 'Approved') echo 'disabled'; ?>>
                        <button class="btn btn-primary" type="submit" <?php if(isset($doc['status']) && $doc['status'] === 'Approved') echo 'disabled'; ?>>Upload</button>
                    </div>
                    <div class="form-text">Accepted formats: PDF, JPG, PNG. Max size: 5MB.</div>
                </form>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php require_once 'footer.php'; ?>
