<?php
include 'includes/db.php';
include 'includes/header.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$message = "";
$error = "";

// Handle Document Deletion
if (isset($_GET['delete'])) {
    $doc_id = $_GET['delete'];
    // Get file path to delete from server
    $sql_get = "SELECT file_path FROM documents WHERE id = $doc_id AND user_id = $user_id";
    $res_get = $conn->query($sql_get);
    if ($res_get->num_rows > 0) {
        $row = $res_get->fetch_assoc();
        if (file_exists($row['file_path'])) {
            unlink($row['file_path']);
        }
        $conn->query("DELETE FROM documents WHERE id = $doc_id");
    }
    header("Location: application_documents.php");
    exit();
}

// Handle Document Upload
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $document_type = $_POST['document_type'];
    
    if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "png" => "image/png", "pdf" => "application/pdf");
        $filename = $_FILES['file']['name'];
        $filetype = $_FILES['file']['type'];
        $filesize = $_FILES['file']['size'];

        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if (!array_key_exists($ext, $allowed)) {
            $error = "Error: Please select a valid file format (JPG, PNG, PDF).";
        } else {
            // Verify file size - 5MB maximum
            if ($filesize > 5 * 1024 * 1024) {
                $error = "Error: File size is larger than the allowed limit (5MB).";
            } else {
                // Clean document type to remove special characters and create valid directory name
                $clean_document_type = preg_replace('/[^a-zA-Z0-9_-]/', '_', $document_type);
                $new_filename = $user_id . "_" . $clean_document_type . "_" . time() . "." . $ext;
                $upload_dir = "uploads/" . $user_id . "_" . $clean_document_type . "/";
                
                // Create directory if it doesn't exist
                if (!file_exists($upload_dir)) {
                    if (!mkdir($upload_dir, 0777, true)) {
                        $error = "Error creating upload directory. Please check permissions.";
                        // Skip to next iteration if there's an error
                        goto error_handling;
                    }
                }
                $destination = $upload_dir . $new_filename;

                if (move_uploaded_file($_FILES['file']['tmp_name'], $destination)) {
                    $sql = "INSERT INTO documents (user_id, document_type, file_path) VALUES ($user_id, '$document_type', '$destination')";
                    if ($conn->query($sql) === TRUE) {
                        $message = "File uploaded successfully!";
                    } else {
                        $error = "Database Error: " . $conn->error;
                    }
                } else {
                    $error = "Error uploading file. Please check folder permissions.";
                }
                error_handling:
                // This label allows us to skip the upload process if directory creation fails
            }
        }
    } else {
        $error = "Error: " . $_FILES['file']['error'];
    }
}

// Fetch existing documents
$sql_docs = "SELECT * FROM documents WHERE user_id = $user_id";
$result_docs = $conn->query($sql_docs);

// Define required documents
$required_docs = ['CNIC/B-Form', 'Passport Size Photo', 'Matric/O-Level Result', 'Inter/A-Level Result'];
$uploaded_types = [];
if ($result_docs->num_rows > 0) {
    while($row = $result_docs->fetch_assoc()) {
        $uploaded_types[] = $row['document_type'];
    }
    // Reset pointer for display loop
    $result_docs->data_seek(0);
}
?>

<div class="dashboard-container">
    <div class="sidebar">
        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-tachometer-alt" style="margin-right: 10px;"></i> Dashboard</a></li>
            <li><a href="application.php" class="active"><i class="fas fa-edit" style="margin-right: 10px;"></i> New Application</a></li>
            <li><a href="profile.php"><i class="fas fa-user" style="margin-right: 10px;"></i> My Profile</a></li>
            <li><a href="logout.php"><i class="fas fa-sign-out-alt" style="margin-right: 10px;"></i> Logout</a></li>
        </ul>
    </div>

    <div class="main-content">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Step 3: Document Uploads</h3>
            </div>
            
            <div style="margin-bottom: 20px;">
                <span class="badge badge-success">Step 1: Personal</span>
                <span class="badge badge-success">Step 2: Academic</span>
                <span class="badge badge-success">Step 3: Documents</span>
                <span class="badge badge-warning">Step 4: Review</span>
            </div>

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

            <div class="alert alert-info" style="background-color: #e3f2fd; color: #0d47a1; border-color: #bbdefb;">
                <strong>Important:</strong> Please upload clear scans/photos of your documents. Max size 5MB. Formats: JPG, PNG, PDF.
            </div>

            <!-- Upload Form -->
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 30px; border: 1px solid #ddd;">
                <h4 style="margin-top: 0; margin-bottom: 20px;">Upload New Document</h4>
                <form method="POST" action="" enctype="multipart/form-data">
                    <div style="display: flex; gap: 20px; align-items: flex-end; flex-wrap: wrap;">
                        <div class="form-group" style="flex: 1; min-width: 200px;">
                            <label>Document Type</label>
                            <select name="document_type" class="form-control" required>
                                <option value="">-- Select Type --</option>
                                <?php foreach($required_docs as $doc): ?>
                                    <option value="<?php echo $doc; ?>"><?php echo $doc; ?></option>
                                <?php endforeach; ?>
                                <option value="Other">Other Document</option>
                            </select>
                        </div>
                        <div class="form-group" style="flex: 1; min-width: 200px;">
                            <label>Select File</label>
                            <input type="file" name="file" class="form-control" style="padding: 7px;" required>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn-primary" style="padding: 10px 20px;"><i class="fas fa-upload"></i> Upload</button>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Uploaded Documents List -->
            <h4 style="margin-bottom: 15px;">Uploaded Documents</h4>
            <table>
                <thead>
                    <tr>
                        <th>Document Type</th>
                        <th>File Name</th>
                        <th>Uploaded At</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($result_docs->num_rows > 0): ?>
                        <?php while($row = $result_docs->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $row['document_type']; ?></td>
                            <td><a href="<?php echo $row['file_path']; ?>" target="_blank">View File</a></td>
                            <td><?php echo date('d M, Y', strtotime($row['uploaded_at'])); ?></td>
                            <td>
                                <a href="application_documents.php?delete=<?php echo $row['id']; ?>" style="color: red;" onclick="return confirm('Are you sure you want to delete this file?')"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="4" class="text-center">No documents uploaded yet.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <div style="text-align: right; margin-top: 30px;">
                <a href="application_academic.php" class="btn-outline" style="padding: 10px 20px; margin-right: 10px; text-decoration: none;">Back</a>
                <?php if ($result_docs->num_rows >= 2): // Just ensuring they uploaded something ?>
                    <a href="application_submit.php" class="btn-primary" style="padding: 10px 30px; text-decoration: none;">Next: Review & Submit <i class="fas fa-arrow-right"></i></a>
                <?php else: ?>
                    <button class="btn-primary" style="padding: 10px 30px; opacity: 0.5; cursor: not-allowed;" disabled>Next: Review & Submit <i class="fas fa-arrow-right"></i></button>
                    <p style="color: red; font-size: 0.9rem; margin-top: 5px;">Please upload at least 2 documents to proceed.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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