<?php

function is_job_expired(?string $deadline): bool {
    if (empty($deadline)) return false;
    $today = new DateTime('today');
    $dl = DateTime::createFromFormat('Y-m-d', $deadline);
    if (!$dl) return false;
    return $dl < $today;
}

function format_date_pretty(?string $ymd): string {
    if (empty($ymd)) return '—';
    $d = DateTime::createFromFormat('Y-m-d', $ymd);
    return $d ? $d->format('d M Y') : $ymd;
}

function h(?string $s): string {
    return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8');
}

function truncate_text(?string $s, int $len = 220): string {
    $s = strip_tags($s ?? '');
    $s = trim(preg_replace('/\s+/', ' ', $s));
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        return mb_strlen($s) > $len ? mb_substr($s, 0, $len) . '…' : $s;
    }
    return strlen($s) > $len ? substr($s, 0, $len) . '…' : $s;
}

function get_job_links(PDO $pdo, int $jobId): array {
    $stmt = $pdo->prepare('SELECT * FROM job_links WHERE job_id = ? ORDER BY id');
    $stmt->execute([$jobId]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function get_all_skills(PDO $pdo): array {
    return $pdo->query('SELECT * FROM skills ORDER BY name')->fetchAll(PDO::FETCH_ASSOC);
}

function get_job_skills(PDO $pdo, int $jobId): array {
    $stmt = $pdo->prepare('SELECT s.* FROM skills s
        INNER JOIN job_skills js ON js.skill_id = s.id
        WHERE js.job_id = ? ORDER BY s.name');
    $stmt->execute([$jobId]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

/**
 * Accepts a comma-separated string of skill names, creates any that
 * don't already exist, and links them all to the given job (replacing
 * any previous links). Newly typed skills are saved for future reuse.
 */
function save_job_skills(PDO $pdo, int $jobId, string $skillsCsv): void {
    $pdo->prepare('DELETE FROM job_skills WHERE job_id = ?')->execute([$jobId]);

    $names = array_filter(array_map('trim', explode(',', $skillsCsv)), fn($s) => $s !== '');
    $names = array_values(array_unique($names, SORT_STRING | SORT_FLAG_CASE));
    if (!$names) return;

    $findStmt = $pdo->prepare('SELECT id FROM skills WHERE name = ? COLLATE NOCASE');
    $insStmt = $pdo->prepare('INSERT INTO skills (name) VALUES (?)');
    $linkStmt = $pdo->prepare('INSERT OR IGNORE INTO job_skills (job_id, skill_id) VALUES (?, ?)');

    foreach ($names as $name) {
        $findStmt->execute([$name]);
        $skillId = $findStmt->fetchColumn();
        if (!$skillId) {
            $insStmt->execute([$name]);
            $skillId = $pdo->lastInsertId();
        }
        $linkStmt->execute([$jobId, $skillId]);
    }
}

/**
 * Handle an uploaded resume/document file safely.
 * Returns [storedPath, originalName] or [null, null] if no file was sent.
 * Throws Exception on validation failure.
 */
function handle_upload(string $fieldName, bool $required = false): array {
    if (empty($_FILES[$fieldName]) || $_FILES[$fieldName]['error'] === UPLOAD_ERR_NO_FILE) {
        if ($required) {
            throw new Exception(ucfirst($fieldName) . ' is required.');
        }
        return [null, null];
    }

    $file = $_FILES[$fieldName];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('Upload failed (error code ' . $file['error'] . ').');
    }

    $maxBytes = 5 * 1024 * 1024; // 5 MB
    if ($file['size'] > $maxBytes) {
        throw new Exception('File is too large. Maximum size is 5 MB.');
    }

    $allowedExt = ['pdf', 'doc', 'docx'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExt, true)) {
        throw new Exception('Only PDF, DOC, or DOCX files are allowed.');
    }

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    $allowedMime = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/zip', // some docx detect as zip container
        'application/octet-stream',
    ];
    if (!in_array($mime, $allowedMime, true)) {
        throw new Exception('The uploaded file does not look like a valid PDF/DOC/DOCX.');
    }

    if (!is_dir(UPLOAD_DIR)) {
        mkdir(UPLOAD_DIR, 0755, true);
    }

    $safeName = bin2hex(random_bytes(16)) . '.' . $ext;
    $dest = UPLOAD_DIR . $safeName;
    if (!move_uploaded_file($file['tmp_name'], $dest)) {
        throw new Exception('Could not save the uploaded file. Please try again.');
    }

    return [$safeName, $file['name']];
}
