<?php
/**
 * JV Overseas Education - Document Upload
 * Single-file PHP with integrated HTML and backend logic
 * Matches design of original index.html
 */

session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';  
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'student') {
    header('Location: student-login.php');
    exit;
}

// Get student data
$stmt = $pdo->prepare("SELECT s.*, u.email, 
                      CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
                      c.id as counselor_id
                      FROM students s 
                      LEFT JOIN counselors c ON s.assigned_counselor_id = c.id
                      JOIN users u ON s.id = u.id 
                      WHERE s.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    die("Student profile not found.");
}

// Document types from database schema
$document_types = [
    'passport' => 'Passport Copy',
    'transcript' => 'Academic Transcript',
    'diploma' => 'Diploma/Certificate',
    'recommendation_letter' => 'Recommendation Letter',
    'sop' => 'Statement of Purpose',
    'cv' => 'Curriculum Vitae',
    'language_test' => 'Language Test Results',
    'financial_statement' => 'Financial Statement',
    'other' => 'Other Document'
];

$error = '';
$success = '';
$upload_dir = 'uploads/documents/';

// Ensure upload directory exists
if (!file_exists($upload_dir)) {
    if (!mkdir($upload_dir, 0777, true)) {
        $error = "Failed to create upload directory. Please contact support.";
    }
}

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_document'])) {
    $document_type = $_POST['document_type'] ?? '';
    $recipient_type = $_POST['recipient_type'] ?? 'counselor'; // Default to counselor
    $specific_admin_id = $_POST['specific_admin_id'] ?? null;
    $notes = trim($_POST['notes'] ?? '');
    
    if (empty($document_type)) {
        $error = "Please select a document type.";
    } elseif (empty($_FILES['document_file']['name'])) {
        $error = "Please select a file to upload.";
    } elseif (!in_array($document_type, array_keys($document_types))) {
        $error = "Invalid document type selected.";
    } else {
        // Validate file
        $file_name = $_FILES['document_file']['name'];
        $file_tmp = $_FILES['document_file']['tmp_name'];
        $file_size = $_FILES['document_file']['size'];
        $file_error = $_FILES['document_file']['error'];
        
        // Get file extension
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $allowed_exts = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx'];
        
        if ($file_error !== UPLOAD_ERR_OK) {
            $error = "File upload error occurred. Error code: $file_error";
        } elseif ($file_size > 10 * 1024 * 1024) { // 10MB limit
            $error = "File size must be less than 10MB.";
        } elseif (!in_array($file_ext, $allowed_exts)) {
            $error = "Only PDF, JPG, PNG, DOC, and DOCX files are allowed.";
        } else {
            // Generate unique filename
            $unique_name = $_SESSION['user_id'] . '_' . time() . '_' . bin2hex(random_bytes(8)) . '.' . $file_ext;
            $file_path = $upload_dir . $unique_name;
            
            // Move uploaded file
            if (move_uploaded_file($file_tmp, $file_path)) {
                try {
                    // Start transaction
                    $pdo->beginTransaction();
                    
                    // Insert into database
                    $stmt = $pdo->prepare("INSERT INTO student_documents (
                        student_id, document_type, file_path, status, notes, created_at, updated_at
                    ) VALUES (?, ?, ?, 'pending', ?, NOW(), NOW())");
                    
                    $insert_result = $stmt->execute([
                        $_SESSION['user_id'], 
                        $document_type, 
                        $file_path,
                        $notes
                    ]);
                    
                    if (!$insert_result) {
                        throw new Exception("Failed to insert document record");
                    }
                    
                    $doc_id = $pdo->lastInsertId();
                    
                    $success = "Document uploaded successfully! ";
                    
                    // Determine recipient for notification
                    $recipient_id = null;
                    
                    if ($recipient_type === 'counselor') {
                        if ($student['counselor_id']) {
                            $recipient_id = $student['counselor_id'];
                            $success .= "Your counselor will review it shortly.";
                        } else {
                            $success .= "You don't have an assigned counselor. Please contact admin for assistance.";
                        }
                    } else if ($recipient_type === 'admin' && $specific_admin_id) {
                        // Validate that the admin exists
                        $admin_stmt = $pdo->prepare("SELECT id FROM admins WHERE id = ? AND id IN (SELECT id FROM users WHERE is_active = 1)");
                        $admin_stmt->execute([$specific_admin_id]);
                        if ($admin_stmt->fetch()) {
                            $recipient_id = $specific_admin_id;
                            $success .= "The selected admin will review it shortly.";
                        } else {
                            $success .= "Selected admin not found or inactive.";
                        }
                    }
                    
                    // Create notification for recipient if valid
                    if ($recipient_id) {
                        $notification_stmt = $pdo->prepare("INSERT INTO notifications (
                            user_id, title, message, is_read, notification_type, created_at
                        ) VALUES (?, ?, ?, 0, 'document', NOW())");
                        $notification_result = $notification_stmt->execute([
                            $recipient_id,
                            "New Document Uploaded",
                            "Student {$student['first_name']} {$student['last_name']} has uploaded a new {$document_types[$document_type]}"
                        ]);
                        
                        if (!$notification_result) {
                            throw new Exception("Failed to create notification");
                        }
                    }
                    
                    // Commit transaction
                    $pdo->commit();
                    
                } catch (Exception $e) {
                    // Rollback transaction
                    $pdo->rollback();
                    
                    // Remove file if database insert fails
                    if (file_exists($file_path)) {
                        unlink($file_path);
                    }
                    
                    // Log the error for debugging
                    error_log("Document upload failed: " . $e->getMessage());
                    $error = "Failed to save document information. Database error: " . $e->getMessage();
                }
            } else {
                $error = "Failed to save uploaded file. Please try again.";
            }
        }
    }
}

// Get uploaded documents
try {
    $documents = $pdo->prepare("SELECT * FROM student_documents 
                               WHERE student_id = ? 
                               ORDER BY created_at DESC");
    $documents->execute([$_SESSION['user_id']]);
    $documents = $documents->fetchAll();
} catch (PDOException $e) {
    error_log("Failed to retrieve documents: " . $e->getMessage());
    $documents = [];
    $error = "Could not retrieve your documents. Please try again later.";
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: student-dashboard.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Upload Documents - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .upload-container {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 30px;
            margin-bottom: 30px;
        }
        .document-item {
            border-bottom: 1px solid #eee;
            padding: 15px 0;
        }
        .document-item:last-child {
            border-bottom: none;
        }
        .status-badge {
            font-size: 0.8em;
            padding: 5px 10px;
            border-radius: 20px;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .status-approved {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        .file-icon {
            font-size: 2em;
            color: #3fb7fe;
        }
        .upload-instructions {
            background: #e7f5ff;
            border-left: 4px solid #3fb7fe;
            padding: 15px;
            margin: 20px 0;
            border-radius: 5px;
        }
        .recipient-section {
            background: #f8f9fa;
            border-left: 4px solid #17a2b8;
            padding: 15px;
            margin: 15px 0;
            border-radius: 5px;
        }
        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 5px;
            margin: 10px 0;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>

<?php include 'student-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Document Management</h6>
        <h1 class="display-5">Upload Your Documents</h1>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <div class="row">
        <div class="col-lg-8">
            <!-- Upload Form -->
            <div class="upload-container">
                <h5>Upload New Document</h5>
                
                <div class="upload-instructions">
                    <h6><i class="fas fa-info-circle"></i> Upload Guidelines</h6>
                    <ul class="small">
                        <li>Accepted formats: PDF, JPG, PNG, DOC, DOCX</li>
                        <li>Maximum file size: 10MB</li>
                        <li>Ensure documents are clear and readable</li>
                        <li>Name documents clearly (e.g., "Transcript_John.pdf")</li>
                    </ul>
                </div>
                
                <form method="POST" enctype="multipart/form-data">
                    <div class="form-group">
                        <label>Document Type *</label>
                        <select name="document_type" class="form-control" required>
                            <option value="">Select Document Type</option>
                            <?php foreach ($document_types as $value => $label): ?>
                                <option value="<?= $value ?>" <?= ($value === ($_POST['document_type'] ?? '')) ? 'selected' : '' ?>>
                                    <?= $label ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Recipient Selection -->
                    <div class="recipient-section">
                        <h6><i class="fas fa-user-check"></i> Select Recipient</h6>
                        <div class="form-group">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="recipient_type" id="recipient_counselor" value="counselor" 
                                       <?= (!isset($_POST['recipient_type']) || $_POST['recipient_type'] === 'counselor') ? 'checked' : '' ?>>
                                <label class="form-check-label" for="recipient_counselor">
                                    My Assigned Counselor
                                    <?php if ($student['counselor_name']): ?>
                                        <strong><?= htmlspecialchars($student['counselor_name']) ?></strong>
                                    <?php else: ?>
                                        <span class="text-danger">Not assigned</span>
                                    <?php endif; ?>
                                </label>
                            </div>
                            
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="radio" name="recipient_type" id="recipient_admin" value="admin" 
                                       <?= (isset($_POST['recipient_type']) && $_POST['recipient_type'] === 'admin') ? 'checked' : '' ?>>
                                <label class="form-check-label" for="recipient_admin">
                                    Specific Admin
                                </label>
                                
                                <!-- Admin selection dropdown (shown only when admin is selected) -->
                                <div id="adminSelection" class="ml-4 mt-2" style="display: <?= (isset($_POST['recipient_type']) && $_POST['recipient_type'] === 'admin') ? 'block' : 'none' ?>;">
                                    <select name="specific_admin_id" class="form-control" <?= (isset($_POST['recipient_type']) && $_POST['recipient_type'] === 'admin') ? 'required' : '' ?>>
                                        <option value="">Select Admin</option>
                                        <?php 
                                        // Get admins for selection
                                        $admins = $pdo->query("SELECT a.id, a.first_name, a.last_name, u.email 
                                                              FROM admins a 
                                                              JOIN users u ON a.id = u.id 
                                                              WHERE u.is_active = 1
                                                              ORDER BY a.last_name, a.first_name")->fetchAll();
                                        foreach ($admins as $admin): ?>
                                            <option value="<?= $admin['id'] ?>" <?= ($admin['id'] == ($_POST['specific_admin_id'] ?? '')) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($admin['first_name'] . ' ' . $admin['last_name']) ?> (<?= htmlspecialchars($admin['email']) ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>File Upload *</label>
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" name="document_file" id="documentFile" required>
                            <label class="custom-file-label" for="documentFile">Choose file...</label>
                        </div>
                        <small class="form-text text-muted">Maximum 10MB - PDF, JPG, PNG, DOC, DOCX</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Additional Notes (Optional)</label>
                        <textarea name="notes" class="form-control" rows="3" 
                                  placeholder="Any additional information about this document"><?= htmlspecialchars($_POST['notes'] ?? '') ?></textarea>
                    </div>
                    
                    <button type="submit" name="upload_document" class="btn btn-primary">
                        <i class="fas fa-upload"></i> Upload Document
                    </button>
                </form>
            </div>

            <!-- Uploaded Documents -->
            <div class="bg-white p-4 rounded">
                <h5 class="mb-4">Your Uploaded Documents</h5>
                
                <?php if (empty($documents)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-folder-open fa-3x text-muted mb-3"></i>
                        <p>You haven't uploaded any documents yet.</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Document</th>
                                    <th>Status</th>
                                    <th>Uploaded</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($documents as $doc): ?>
                                <tr>
                                    <td>
                                        <i class="fas fa-file-alt file-icon mr-2"></i>
                                        <?= $document_types[$doc['document_type']] ?>
                                    </td>
                                    <td>
                                        <span class="status-badge status-<?= $doc['status'] ?>">
                                            <?= ucfirst($doc['status']) ?>
                                        </span>
                                    </td>
                                    <td><?= date('M j, Y', strtotime($doc['created_at'])) ?></td>
                                    <td>
                                        <a href="<?= htmlspecialchars($doc['file_path']) ?>" 
                                           class="btn btn-sm btn-primary" target="_blank">
                                            <i class="fas fa-eye"></i> View
                                        </a>
                                        <?php if ($doc['status'] === 'rejected'): ?>
                                        <button class="btn btn-sm btn-warning re-upload" data-id="<?= $doc['id'] ?>">
                                            <i class="fas fa-redo"></i> Re-upload
                                        </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="bg-light p-4 rounded">
                <h6><i class="fas fa-check-circle"></i> Why Upload Documents?</h6>
                <ul class="small">
                    <li>Required for university applications</li>
                    <li>Necessary for visa processing</li>
                    <li>Needed for scholarship applications</li>
                    <li>Essential for financial verification</li>
                </ul>
                
                <hr>
                
                <h6><i class="fas fa-clock"></i> Processing Time</h6>
                <p class="small">Documents are typically reviewed within 24-48 business hours. You'll receive a notification when your document has been approved or if additional information is needed.</p>
                
                <hr>
                
                <h6><i class="fas fa-question-circle"></i> Need Help?</h6>
                <p class="small mb-1">Contact your counselor:</p>
                <?php if ($student['counselor_name']): ?>
                    <p class="font-weight-bold"><?= htmlspecialchars($student['counselor_name']) ?></p>
                <?php else: ?>
                    <p class="font-weight-bold">Not assigned yet</p>
                <?php endif; ?>
                <p class="small">+256 788 289 235</p>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    // Update file input label with selected filename
    $('.custom-file-input').on('change', function() {
        let fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').addClass("selected").html(fileName);
    });
    
    // Re-upload button handler
    $('.re-upload').on('click', function() {
        const docId = $(this).data('id');
        alert('To re-upload, please use the main upload form above and select the same document type.');
    });
    
    // Form submission confirmation
    $('form').on('submit', function(e) {
        const docType = $('select[name="document_type"]').val();
        if (docType) {
            const docName = $('option:selected', 'select[name="document_type"]').text();
            if (!confirm(`You are about to upload a ${docName}. Continue?`)) {
                e.preventDefault();
            }
        }
    });
    
    // Toggle admin selection dropdown based on radio button
    $('#recipient_counselor, #recipient_admin').on('change', function() {
        if ($('#recipient_admin').is(':checked')) {
            $('#adminSelection').show();
            $('select[name="specific_admin_id"]').prop('required', true);
        } else {
            $('#adminSelection').hide();
            $('select[name="specific_admin_id"]').prop('required', false);
        }
    });
</script>
</body>
</html>