<?php
require_once __DIR__ . '/../models/SharedCV.php';
require_once __DIR__ . '/../models/User.php';
require_once __DIR__ . '/../database/helpers/session.php';
require_once __DIR__ . '/../database/helpers/csrf.php';

class SharedCVController {
    private $sharedCV;
    private $user;

    public function __construct($conn) {
        $this->sharedCV = new SharedCV($conn);
        $this->user = new User($conn);
    }

    public function shareCV() {
        if (!isAuthenticated() || !isJobSeeker()) {
            $_SESSION['errors'] = ["Unauthorized access."];
            redirect('/auth/login');
            return;
        }

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect('/profile');
            return;
        }

        // CSRF validation
        if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
            $_SESSION['errors'] = ["Invalid request. Please try again."];
            redirect('/profile');
            return;
        }

        $userId = $_SESSION['user_uuid'] ?? $_SESSION['user_id'] ?? $_SESSION['uuid'] ?? null;
        if (!$userId) {
            $_SESSION['errors'] = ["Session expired. Please login again."];
            redirect('/auth/login');
            return;
        }

        $cvSource = $_POST['cv_source'] ?? '';
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $personalNotes = trim($_POST['personal_notes'] ?? '');
        $isPublic = isset($_POST['is_public']) ? 'true' : 'false';
        $cvFilePath = null;

        // Handle CV source
        if ($cvSource === 'profile') {
            // Use CV from profile
            $profile = $this->user->getUserProfile($userId);
            if (empty($profile['resume_file'])) {
                $_SESSION['errors'] = ["No CV found in your profile. Please upload a CV first."];
                redirect('/profile');
                return;
            }
            $cvFilePath = $profile['resume_file'];
        } elseif ($cvSource === 'upload') {
            // Handle file upload
            if (isset($_FILES['cv_file']) && $_FILES['cv_file']['error'] === UPLOAD_ERR_OK) {
                $cvFilePath = $this->handleFileUpload($_FILES['cv_file']);
                if (!$cvFilePath) {
                    $_SESSION['errors'] = ["Failed to upload CV file. Please check file type and size."];
                    redirect('/profile');
                    return;
                }
            } else {
                $_SESSION['errors'] = ["Please select a CV file to share."];
                redirect('/profile');
                return;
            }
        } else {
            $_SESSION['errors'] = ["Please select a CV source."];
            redirect('/profile');
            return;
        }

        // Share the CV
        $shareId = $this->sharedCV->shareCV($userId, $cvFilePath, $title, $description, $personalNotes);
        if ($shareId) {
            // Update public status if requested
            if ($isPublic) {
                $this->sharedCV->updateSharedCV($shareId, ['is_public' => 1]);
            }
            $_SESSION['success'] = "Your CV has been shared successfully!";
        } else {
            $_SESSION['errors'] = ["Failed to share your CV. Please try again."];
        }

        redirect('/profile');
    }

    public function getUserSharedCVs() {
        if (!isAuthenticated() || !isJobSeeker()) {
            return [];
        }

        $userId = $_SESSION['user_uuid'] ?? $_SESSION['user_id'] ?? $_SESSION['uuid'] ?? null;
        if (!$userId) {
            return [];
        }

        return $this->sharedCV->getUserSharedCVs($userId);
    }

    public function getAllSharedCVs() {
        if (!isAuthenticated() || (!isAdmin() && !isEmployer())) {
            $_SESSION['errors'] = ["Unauthorized access."];
            redirect('/auth/login');
            return [];
        }

        $filters = [];
        if (isset($_GET['search']) && !empty($_GET['search'])) {
            $filters['search'] = $_GET['search'];
        }
        if (isset($_GET['is_public'])) {
            $filters['is_public'] = $_GET['is_public'];
        }

        return $this->sharedCV->getAllSharedCVs($filters);
    }

    public function viewSharedCV($uuid) {
        $sharedCV = $this->sharedCV->getSharedCV($uuid);
        if (!$sharedCV) {
            return false;
        }

        // Record access for analytics
        $this->sharedCV->recordAccess($uuid);

        return $sharedCV;
    }

    public function updateSharedCV() {
        if (!isAuthenticated() || !isJobSeeker()) {
            $_SESSION['errors'] = ["Unauthorized access."];
            redirect('/mfanyakazi/public/auth/login');
            return;
        }

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect('/profile');
            return;
        }

        $userId = $_SESSION['user_uuid'] ?? $_SESSION['user_id'] ?? $_SESSION['uuid'] ?? null;
        $cvId = $_POST['cv_id'] ?? '';

        if (empty($cvId)) {
            $_SESSION['errors'] = ["Invalid request."];
            redirect('/profile');
            return;
        }

        $data = [];
        if (isset($_POST['title'])) {
            $data['title'] = trim($_POST['title']);
        }
        if (isset($_POST['description'])) {
            $data['description'] = trim($_POST['description']);
        }
        if (isset($_POST['personal_notes'])) {
            $data['personal_notes'] = trim($_POST['personal_notes']);
        }
        if (isset($_POST['is_public'])) {
            $data['is_public'] = 'true';
        } else {
            $data['is_public'] = 'false';
        }

        if ($this->sharedCV->updateSharedCV($cvId, $data)) {
            $_SESSION['success'] = "Shared CV updated successfully.";
        } else {
            $_SESSION['errors'] = ["Failed to update shared CV."];
        }

        redirect('/profile');
    }

    public function deleteSharedCV() {
        if (!isAuthenticated() || !isJobSeeker()) {
            $_SESSION['errors'] = ["Unauthorized access."];
            redirect('/auth/login');
            return;
        }

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect('/profile');
            return;
        }

        $userId = $_SESSION['user_uuid'] ?? $_SESSION['user_id'] ?? $_SESSION['uuid'] ?? null;
        $cvId = $_POST['cv_id'] ?? '';

        if (empty($cvId)) {
            $_SESSION['errors'] = ["Invalid request."];
            redirect('/profile');
            return;
        }

        if ($this->sharedCV->deleteSharedCV($cvId, $userId)) {
            $_SESSION['success'] = "Shared CV removed successfully.";
        } else {
            $_SESSION['errors'] = ["Failed to remove shared CV."];
        }

        redirect('/profile');
    }

    private function handleFileUpload($file) {
        $uploadDir = __DIR__ . '/../public/uploads/shared_cvs/';

        // Create directory if it doesn't exist
        if (!is_dir($uploadDir)) {
            if (!mkdir($uploadDir, 0755, true)) {
                error_log("Failed to create shared CVs upload directory: " . $uploadDir);
                return false;
            }
        }

        // Generate unique filename
        $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $fileName = 'shared_cv_' . uniqid() . '.' . $fileExtension;
        $filePath = $uploadDir . $fileName;

        // Validate file type
        $allowedTypes = ['pdf', 'doc', 'docx'];
        if (!in_array(strtolower($fileExtension), $allowedTypes)) {
            error_log("Invalid shared CV file type: " . $fileExtension . ". Allowed types: " . implode(', ', $allowedTypes));
            return false;
        }

        // Validate file size (max 10MB for shared CVs)
        if ($file['size'] > 10 * 1024 * 1024) {
            error_log("Shared CV file too large: " . $file['size'] . " bytes. Max allowed: 10MB");
            return false;
        }

        if (!is_uploaded_file($file['tmp_name'])) {
            error_log("Shared CV file was not uploaded via HTTP POST: " . $file['tmp_name']);
            return false;
        }

        if (move_uploaded_file($file['tmp_name'], $filePath)) {
            return $fileName;
        }

        error_log("Failed to move uploaded shared CV file from " . $file['tmp_name'] . " to " . $filePath);
        return false;
    }
}
?>