<?php
require_once '../config/config.php';
requireLogin('candidate');

$database = new Database();
$db = $database->getConnection();

$candidate_id = $_SESSION['user_id'];

$error = '';
$success = '';

// Handle document upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_document'])) {
    if (!isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
        $error = 'Please select a file to upload.';
    } else {
        $title = sanitize($_POST['title']);
        $document_type = $_POST['document_type'];
        $description = sanitize($_POST['description']);
        
        if (empty($title)) {
            $error = 'Document title is required.';
        } else {
            $file = $_FILES['document'];
            $upload_dir = UPLOAD_PATH . 'documents/';
            
            // Create upload directory if it doesn't exist
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            // Validate file type
            $allowed_types = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png'];
            $allowed_extensions = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png'];
            
            $file_type = $file['type'];
            $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            
            // Validate file size (5MB max)
            if ($file['size'] > 5 * 1024 * 1024) {
                $error = 'File size must be less than 5MB.';
            } elseif (!in_array($file_type, $allowed_types) && !in_array($file_extension, $allowed_extensions)) {
                $error = 'Invalid file type. Please upload PDF, DOC, DOCX, JPG, or PNG files only.';
            } else {
                // Generate unique filename
                $new_filename = uniqid() . '.' . $file_extension;
                $upload_path = $upload_dir . $new_filename;
                
                if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                    try {
                        $stmt = $db->prepare("
                            INSERT INTO candidate_documents (candidate_id, document_type, title, file_path, file_size, file_type, description, is_public)
                            VALUES (?, ?, ?, ?, ?, ?, ?, 0)
                        ");
                        $stmt->execute([
                            $candidate_id,
                            $document_type,
                            $title,
                            $new_filename,
                            $file['size'],
                            $file['type'],
                            $description
                        ]);
                        
                        $success = 'Document uploaded successfully!';
                    } catch (PDOException $e) {
                        $error = 'Error saving document. Please try again.';
                        // Clean up uploaded file if database save failed
                        if (file_exists($upload_path)) {
                            unlink($upload_path);
                        }
                    }
                } else {
                    $error = 'Failed to upload file. Please try again.';
                }
            }
        }
    }
}

// Handle certificate addition
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_certificate'])) {
    $title = sanitize($_POST['cert_title']);
    $issuing_organization = sanitize($_POST['cert_organization']);
    $issue_date = $_POST['cert_issue_date'];
    $description = sanitize($_POST['cert_description']);
    
    if (empty($title) || empty($issuing_organization)) {
        $error = 'Certificate title and issuing organization are required.';
    } else {
        try {
            $file_path = null;
            
            // Handle certificate file upload if provided
            if (isset($_FILES['cert_file']) && $_FILES['cert_file']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['cert_file'];
                $upload_dir = UPLOAD_PATH . 'certificates/';
                
                // Create upload directory if it doesn't exist
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }
                
                // Validate file type
                $allowed_types = ['application/pdf', 'image/jpeg', 'image/png'];
                $allowed_extensions = ['pdf', 'jpg', 'jpeg', 'png'];
                
                $file_type = $file['type'];
                $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                
                // Validate file size (5MB max)
                if ($file['size'] > 5 * 1024 * 1024) {
                    $error = 'Certificate file size must be less than 5MB.';
                } elseif (!in_array($file_type, $allowed_types) && !in_array($file_extension, $allowed_extensions)) {
                    $error = 'Invalid certificate file type. Please upload PDF, JPG, or PNG files only.';
                } else {
                    // Generate unique filename
                    $cert_filename = uniqid() . '.' . $file_extension;
                    $cert_upload_path = $upload_dir . $cert_filename;
                    
                    if (move_uploaded_file($file['tmp_name'], $cert_upload_path)) {
                        $file_path = $cert_filename;
                    } else {
                        $error = 'Failed to upload certificate file.';
                    }
                }
            }
            
            $stmt = $db->prepare("
                INSERT INTO certificates (candidate_id, title, issuing_organization, issue_date, description, file_path)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $candidate_id,
                $title,
                $issuing_organization,
                $issue_date ?: null,
                $description,
                $file_path
            ]);
            
            $success = 'Certificate added successfully!';
        } catch (PDOException $e) {
            $error = 'Error adding certificate. Please try again.';
        }
    }
}

// Get existing documents
$stmt = $db->prepare("SELECT * FROM candidate_documents WHERE candidate_id = ? ORDER BY created_at DESC");
$stmt->execute([$candidate_id]);
$documents = $stmt->fetchAll();

// Get existing certificates
$stmt = $db->prepare("SELECT * FROM certificates WHERE candidate_id = ? ORDER BY created_at DESC");
$stmt->execute([$candidate_id]);
$certificates = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Documents - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['first_name'] . ' ' . $_SESSION['last_name']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="fas fa-user me-2"></i>My Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="cv-builder.php">
                                <i class="fas fa-file-alt me-2"></i>CV Builder
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="documents.php">
                                <i class="fas fa-file-upload me-2"></i>Documents
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-paper-plane me-2"></i>My Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../jobs.php">
                                <i class="fas fa-search me-2"></i>Browse Jobs
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-file-upload me-2"></i>Document Management
                        </h1>
                        <a href="profile.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left me-1"></i>Back to Profile
                        </a>
                    </div>

                    <?php if ($error): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-8">
                            <!-- Upload Document Form -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-upload me-2"></i>Upload Document
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST" enctype="multipart/form-data">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="title" class="form-label">Document Title *</label>
                                                <input type="text" class="form-control" id="title" name="title" 
                                                       placeholder="e.g., Driver's License, Passport Copy" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="document_type" class="form-label">Document Type *</label>
                                                <select class="form-select" id="document_type" name="document_type" required>
                                                    <option value="">Select Type</option>
                                                    <option value="cv">CV/Resume</option>
                                                    <option value="certificate">Certificate/Qualification</option>
                                                    <option value="other">ID/License/Other</option>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="document" class="form-label">Select File *</label>
                                            <input type="file" class="form-control" id="document" name="document" 
                                                   accept=".pdf,.doc,.docx,.jpg,.jpeg,.png" required>
                                            <div class="form-text">Supported formats: PDF, DOC, DOCX, JPG, PNG (max 5MB)</div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="description" class="form-label">Description</label>
                                            <textarea class="form-control" id="description" name="description" rows="2" 
                                                      placeholder="Optional description or notes about this document"></textarea>
                                        </div>
                                        
                                        <button type="submit" name="upload_document" class="btn btn-primary">
                                            <i class="fas fa-upload me-1"></i>Upload Document
                                        </button>
                                    </form>
                                </div>
                            </div>

                            <!-- Add Certificate Form -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-certificate me-2"></i>Add Certificate/Qualification
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST" enctype="multipart/form-data">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="cert_title" class="form-label">Certificate Title *</label>
                                                <input type="text" class="form-control" id="cert_title" name="cert_title" 
                                                       placeholder="e.g., Bachelor's Degree, Professional Certification" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="cert_organization" class="form-label">Issuing Organization *</label>
                                                <input type="text" class="form-control" id="cert_organization" name="cert_organization" 
                                                       placeholder="e.g., University of Cape Town, Microsoft" required>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="cert_issue_date" class="form-label">Issue Date</label>
                                                <input type="date" class="form-control" id="cert_issue_date" name="cert_issue_date">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="cert_file" class="form-label">Certificate File (Optional)</label>
                                                <input type="file" class="form-control" id="cert_file" name="cert_file" 
                                                       accept=".pdf,.jpg,.jpeg,.png">
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="cert_description" class="form-label">Description</label>
                                            <textarea class="form-control" id="cert_description" name="cert_description" rows="2" 
                                                      placeholder="Additional details about this certification"></textarea>
                                        </div>
                                        
                                        <button type="submit" name="add_certificate" class="btn btn-success">
                                            <i class="fas fa-plus me-1"></i>Add Certificate
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Document Lists -->
                        <div class="col-lg-4">
                            <!-- Uploaded Documents -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h6 class="card-title mb-0">
                                        <i class="fas fa-file me-2"></i>Uploaded Documents (<?php echo count($documents); ?>)
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($documents)): ?>
                                        <p class="text-muted small">No documents uploaded yet.</p>
                                    <?php else: ?>
                                        <?php foreach ($documents as $doc): ?>
                                            <div class="mb-3 pb-2 border-bottom">
                                                <h6 class="mb-1"><?php echo htmlspecialchars($doc['title']); ?></h6>
                                                <small class="text-muted">
                                                    Type: <?php echo ucfirst($doc['document_type']); ?><br>
                                                    Uploaded: <?php echo formatDate($doc['created_at']); ?>
                                                </small>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Certificates -->
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="card-title mb-0">
                                        <i class="fas fa-certificate me-2"></i>Certificates (<?php echo count($certificates); ?>)
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($certificates)): ?>
                                        <p class="text-muted small">No certificates added yet.</p>
                                    <?php else: ?>
                                        <?php foreach ($certificates as $cert): ?>
                                            <div class="mb-3 pb-2 border-bottom">
                                                <h6 class="mb-1"><?php echo htmlspecialchars($cert['title']); ?></h6>
                                                <small class="text-muted">
                                                    <?php echo htmlspecialchars($cert['issuing_organization']); ?><br>
                                                    <?php if ($cert['issue_date']): ?>
                                                        Issued: <?php echo formatDate($cert['issue_date']); ?>
                                                    <?php endif; ?>
                                                </small>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>