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

<?php
session_start();

// Check if student is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit();
}

// Include database connection
require_once('../../includes/db_connection.php');

$userId = $_SESSION['user_id'];

// Check if file and document type are provided
if (!isset($_POST['document_type']) || empty($_POST['document_type']) || !isset($_FILES['document_file'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Document type and file are required'
    ]);
    exit();
}

$documentType = $_POST['document_type'];
$file = $_FILES['document_file'];

// Validate document type
$allowedTypes = ['id_proof', 'address_proof', 'qualification_certificate', 'passport_photo'];
if (!in_array($documentType, $allowedTypes)) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid document type'
    ]);
    exit();
}

// Validate file type
$allowedExtensions = ['pdf', 'jpg', 'jpeg', 'png'];
$fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($fileExtension, $allowedExtensions)) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid file type. Only PDF, JPG, JPEG, and PNG files are allowed.'
    ]);
    exit();
}

// Validate file size (5MB max)
$maxSize = 5 * 1024 * 1024; // 5MB
if ($file['size'] > $maxSize) {
    echo json_encode([
        'success' => false,
        'message' => 'File size exceeds the maximum limit of 5MB'
    ]);
    exit();
}

// Create upload directory if it doesn't exist
$uploadDir = '../../uploads/documents/' . $userId . '/';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// Generate a unique filename
$fileName = uniqid() . '_' . $documentType . '.' . $fileExtension;
$uploadPath = $uploadDir . $fileName;
$dbFilePath = 'uploads/documents/' . $userId . '/' . $fileName;

try {
    // Move the uploaded file
    if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to upload file'
        ]);
        exit();
    }
    
    // Check if student_documents table exists
    $tableExists = $conn->query("SHOW TABLES LIKE 'student_documents'");
    if ($tableExists->num_rows == 0) {
        // Create the table
        $createTable = "CREATE TABLE student_documents (
            id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            user_id INT(11) NOT NULL,
            document_type VARCHAR(50) NOT NULL,
            file_path VARCHAR(255) NOT NULL,
            upload_date DATETIME NOT NULL,
            status ENUM('pending', 'verified', 'rejected') DEFAULT 'pending',
            admin_notes TEXT NULL,
            INDEX (user_id)
        )";
        $conn->query($createTable);
    }
    
    // Check if a document of this type already exists
    $stmt = $conn->prepare("
        SELECT id FROM student_documents
        WHERE user_id = ? AND document_type = ?
    ");
    $stmt->bind_param('is', $userId, $documentType);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        // Update existing document
        $row = $result->fetch_assoc();
        $docId = $row['id'];
        
        $stmt = $conn->prepare("
            UPDATE student_documents
            SET file_path = ?, upload_date = NOW(), status = 'pending', admin_notes = NULL
            WHERE id = ?
        ");
        $stmt->bind_param('si', $dbFilePath, $docId);
    } else {
        // Insert new document
        $stmt = $conn->prepare("
            INSERT INTO student_documents (user_id, document_type, file_path, upload_date, status)
            VALUES (?, ?, ?, NOW(), 'pending')
        ");
        $stmt->bind_param('iss', $userId, $documentType, $dbFilePath);
    }
    
    if (!$stmt->execute()) {
        throw new Exception($conn->error);
    }
    
    // Check if enrollment_applications table exists and user has any pending applications
    $tableExists = $conn->query("SHOW TABLES LIKE 'enrollment_applications'");
    if ($tableExists->num_rows > 0) {
        // Update application status if applicable
        $stmt = $conn->prepare("
            UPDATE enrollment_applications 
            SET status = 'documents_pending'
            WHERE user_id = ? AND status = 'pending'
        ");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
    }
    
    // Check if activities table exists
    $tableExists = $conn->query("SHOW TABLES LIKE 'activities'");
    if ($tableExists->num_rows > 0) {
        // Log the activity
        $activity = "Uploaded " . ucfirst(str_replace('_', ' ', $documentType));
        $stmt = $conn->prepare("
            INSERT INTO activities (user_id, activity_type, description, activity_date)
            VALUES (?, 'document_upload', ?, NOW())
        ");
        $stmt->bind_param('is', $userId, $activity);
        $stmt->execute();
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Document uploaded successfully',
        'file_path' => $dbFilePath
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error uploading document: ' . $e->getMessage()
    ]);
}

$conn->close();