Path : /home/vishqocm/pcib.in/enroll/ajax/
File Upload :
Current File : /home/vishqocm/pcib.in/enroll/ajax/upload_document.php

<?php
// 🔒 Force JSON response & prevent PHP warnings from breaking it
header('Content-Type: application/json');

// ✅ Display PHP errors only during development
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start(); // Buffer output to catch accidental echoes

// Add error logging to a file
ini_set('log_errors', 1);
ini_set('error_log', '../../uploads/php_errors.log');

session_start();
include_once('../../admin/database/db_config.php');

// Ensure we have a valid database connection before proceeding
if (!isset($conn) || !($conn instanceof mysqli) || $conn->connect_error) {
    // Try to connect manually if the include didn't set up $conn correctly
    $db_host = $db_host ?? 'localhost';
    $db_user = $db_user ?? 'root';
    $db_pass = $db_pass ?? '';
    $db_name = $db_name ?? 'popularcomputer';
    
    $conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
    
    if ($conn->connect_error) {
        echo json_encode([
            'success' => false,
            'message' => 'Database connection failed: ' . $conn->connect_error
        ]);
        exit();
    }
}

// Debug: Check student_documents table structure
try {
    $debug_query = "DESCRIBE student_documents";
    $debug_result = $conn->query($debug_query);
    if ($debug_result) {
        $columns = [];
        while ($row = $debug_result->fetch_assoc()) {
            $columns[] = $row['Field'];
        }
        error_log("student_documents columns: " . implode(", ", $columns));
    } else {
        error_log("Failed to get student_documents table structure");
    }
} catch (Exception $e) {
    error_log("Error checking table structure: " . $e->getMessage());
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Authentication required'
    ]);
    exit;
}

$user_id = $_SESSION['user_id'];
$response = [
    'success' => false,
    'message' => '',
    'document' => null
];

// Process document upload
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $document_type = isset($_POST['document_type']) ? trim($_POST['document_type']) : '';
    $application_id = isset($_POST['application_id']) ? intval($_POST['application_id']) : 0;
    
    // Validate document type and application ID
    if (empty($document_type)) {
        $response['message'] = 'Document type is required';
        echo json_encode($response);
        exit;
    }
    
    // Check if file was uploaded
    if (!isset($_FILES['document_file']) || $_FILES['document_file']['error'] === UPLOAD_ERR_NO_FILE) {
        $response['message'] = 'Please select a file to upload';
        echo json_encode($response);
        exit;
    }
    
    // Check for upload errors
    if ($_FILES['document_file']['error'] !== UPLOAD_ERR_OK) {
        $response['message'] = 'Upload failed with error code: ' . $_FILES['document_file']['error'];
        echo json_encode($response);
        exit;
    }
    
    // Validate file size (max 5MB)
    if ($_FILES['document_file']['size'] > 5 * 1024 * 1024) {
        $response['message'] = 'File size exceeds 5MB limit';
        echo json_encode($response);
        exit;
    }
    
    // Validate file type (PDF, JPG, PNG)
    $allowed_types = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'];
    $file_info = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($file_info, $_FILES['document_file']['tmp_name']);
    finfo_close($file_info);
    
    if (!in_array($mime_type, $allowed_types)) {
        $response['message'] = 'Invalid file type. Only PDF, JPG, and PNG files are allowed';
        echo json_encode($response);
        exit;
    }
    
    // Create directory if it doesn't exist
    $upload_dir = '../../uploads/student_documents/' . $user_id . '/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    // Generate unique filename
    $file_extension = pathinfo($_FILES['document_file']['name'], PATHINFO_EXTENSION);
    $new_filename = $document_type . '_' . time() . '.' . $file_extension;
    $target_file = $upload_dir . $new_filename;
    $db_file_path = '../uploads/student_documents/' . $user_id . '/' . $new_filename;
    
    // Move uploaded file
    if (move_uploaded_file($_FILES['document_file']['tmp_name'], $target_file)) {
        // Insert into database
        $document_query = "INSERT INTO student_documents (user_id, document_type, document_path, upload_date, status) 
                          VALUES (?, ?, ?, NOW(), 'pending')";
        $stmt = $conn->prepare($document_query);
        
        if (!$stmt) {
            $response['message'] = 'Database error: ' . $conn->error;
            echo json_encode($response);
            exit;
        }
        
        $stmt->bind_param("iss", $user_id, $document_type, $db_file_path);
        
        if ($stmt->execute()) {
            $document_id = $conn->insert_id;
            
            // Build document details for response
            $doc_query = "SELECT * FROM student_documents WHERE id = ?";
            $doc_stmt = $conn->prepare($doc_query);
            $doc_stmt->bind_param("i", $document_id);
            $doc_stmt->execute();
            $document = $doc_stmt->get_result()->fetch_assoc();
            
            $response['success'] = true;
            $response['message'] = 'Document uploaded successfully';
            $response['document'] = [
                'id' => $document_id,
                'type' => $document_type,
                'path' => $db_file_path,
                'upload_date' => date('M d, Y h:i A'),
                'status' => 'pending'
            ];
            
            // Check if all required documents are uploaded
            if ($application_id > 0) {
                $required_docs = ['id_proof', 'educational_certificate', 'photograph'];
                $all_required_uploaded = true;
                
                foreach ($required_docs as $req_doc) {
                    $check_query = "SELECT COUNT(*) as count FROM student_documents WHERE user_id = ? AND document_type = ?";
                    $check_stmt = $conn->prepare($check_query);
                    $check_stmt->bind_param("is", $user_id, $req_doc);
                    $check_stmt->execute();
                    $check_result = $check_stmt->get_result()->fetch_assoc();
                    
                    if ($check_result['count'] == 0) {
                        $all_required_uploaded = false;
                        break;
                    }
                }
                
                $response['all_documents_uploaded'] = $all_required_uploaded;
                
                // If all required documents are uploaded, update application status
                if ($all_required_uploaded) {
                    $update_query = "UPDATE enrollment_applications SET status = 'payment_pending' WHERE id = ? AND user_id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("ii", $application_id, $user_id);
                    $update_stmt->execute();
                    
                    $response['redirect_to_payment'] = true;
                    $response['payment_url'] = "../payment.php?application_id=$application_id";
                }
            }
        } else {
            $response['message'] = 'Failed to save document information: ' . $stmt->error;
        }
    } else {
        $response['message'] = 'Failed to upload document. Please try again';
    }
} else {
    $response['message'] = 'Invalid request method';
}

echo json_encode($response);

/**
 * Get human-readable error message for file upload errors
 */
function getFileUploadErrorMessage($errorCode) {
    switch ($errorCode) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'A PHP extension stopped the file upload';
        default:
            return 'Unknown upload error';
    }
}

/**
 * Get display name for document type
 */
function getDocumentTypeDisplay($documentType) {
    $types = [
        'id_proof' => 'ID Proof (Aadhaar/PAN/Passport)',
        'educational_certificate' => 'Educational Certificate',
        'photograph' => 'Recent Passport Size Photograph',
        'other' => 'Other Supporting Documents (Optional)'
    ];
    
    return isset($types[$documentType]) ? $types[$documentType] : ucfirst(str_replace('_', ' ', $documentType));
}
?>