<?php
// Staff and administrator CV API. Uses the application's existing login session.
declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/session_auth.php';

header('Content-Type: application/json; charset=UTF-8');

function cv_reply(array $data, int $status = 200): void {
    http_response_code($status);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function cv_text($value, int $limit = 5000): ?string {
    $value = trim((string)($value ?? ''));
    if ($value === '') return null;
    if (function_exists('mb_substr')) return mb_substr($value, 0, $limit);
    return substr($value, 0, $limit);
}

function cv_role(array $user): string {
    return strtolower(trim((string)($user['role'] ?? '')));
}

function cv_public_row(PDO $pdo, int $userId, bool $includeHistory = false): ?array {
    $stmt = $pdo->prepare('SELECT u.id AS user_id, u.full_name, u.email AS account_email, u.role, u.campus, u.program, u.profile_picture AS account_photo, p.cv_name, p.professional_title, p.career_objective, p.professional_summary, p.phone, p.contact_email, p.address, p.photo_url, p.website, p.linkedin_url, p.nationality, p.languages, p.hobbies, p.date_of_birth, p.marital_status, p.place_of_birth, p.religion, p.gender, p.nrc_number, p.updated_at FROM users u LEFT JOIN cv_profiles p ON p.user_id = u.id WHERE u.id = ? LIMIT 1');
    $stmt->execute([$userId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row || !in_array(strtolower((string)$row['role']), ['admin', 'staff'], true)) return null;
    $row['user_id'] = (int)$row['user_id'];
    $entries = $pdo->prepare('SELECT section, entry_data FROM cv_entries WHERE user_id = ? ORDER BY section, sort_order, id');
    $entries->execute([$userId]);
    $row['entries'] = ['education'=>[], 'experience'=>[], 'certification'=>[], 'project'=>[], 'skill'=>[], 'referee'=>[], 'internship'=>[], 'work_learning'=>[]];
    foreach ($entries->fetchAll(PDO::FETCH_ASSOC) as $entry) {
        $data = json_decode((string)$entry['entry_data'], true);
        if (isset($row['entries'][$entry['section']]) && is_array($data)) $row['entries'][$entry['section']][] = $data;
    }
    $row['change_history'] = [];
    if ($includeHistory) {
        $history = $pdo->prepare('SELECT l.changed_sections, l.changed_at, u.full_name AS changed_by_name FROM cv_change_log l LEFT JOIN users u ON u.id = l.changed_by_user_id WHERE l.cv_user_id = ? ORDER BY l.changed_at DESC LIMIT 30');
        $history->execute([$userId]);
        $row['change_history'] = $history->fetchAll(PDO::FETCH_ASSOC);
    }
    return $row;
}

$user = rvu_current_user($pdo);
if (!$user) {
    cv_reply(['detail'=>'Your session is missing, expired, or invalid. Please sign in again.'], 401);
}
$userId = (int)$user['id'];
$role = cv_role($user);
if (!in_array($role, ['admin', 'staff'], true)) cv_reply(['detail'=>'Only staff members and administrators can use CV Management.'], 403);

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

try {
    if ($method === 'GET' && $id > 0) {
        if ($role !== 'admin' && $id !== $userId) cv_reply(['detail'=>'You can only view your own CV.'], 403);
        $data = cv_public_row($pdo, $id, $role === 'admin');
        if (!$data) cv_reply(['detail'=>'CV owner was not found.'], 404);
        cv_reply(['data'=>$data]);
    }

    if ($method === 'GET' && $role === 'admin' && ($_GET['scope'] ?? '') === 'directory') {
        $search = cv_text($_GET['search'] ?? '', 120) ?? '';
        $stmt = $pdo->prepare("SELECT u.id AS user_id, u.full_name, u.email AS account_email, u.role, u.campus, u.program, u.profile_picture AS account_photo, p.professional_title, p.professional_summary, p.updated_at FROM users u LEFT JOIN cv_profiles p ON p.user_id = u.id WHERE LOWER(u.role) IN ('admin','staff') AND (CAST(u.id AS TEXT) ILIKE ? OR COALESCE(u.full_name,'') ILIKE ? OR COALESCE(u.email,'') ILIKE ? OR COALESCE(u.campus,'') ILIKE ?) ORDER BY CASE WHEN p.updated_at IS NULL THEN 1 ELSE 0 END, p.updated_at DESC NULLS LAST, u.full_name ASC");
        $like = '%' . $search . '%';
        $stmt->execute([$like, $like, $like, $like]);
        cv_reply(['data'=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
    }

    if ($method === 'GET') {
        cv_reply(['data'=>cv_public_row($pdo, $userId)]);
    }

    if ($method !== 'POST') cv_reply(['detail'=>'Use GET to view and POST to save a CV.'], 405);
    $input = json_decode((string)file_get_contents('php://input'), true);
    if (!is_array($input)) cv_reply(['detail'=>'Send a valid JSON CV.'], 400);

    $profile = is_array($input['profile'] ?? null) ? $input['profile'] : [];
    $sections = is_array($input['entries'] ?? null) ? $input['entries'] : [];
    $profileData = [
        cv_text($profile['professional_title'] ?? '', 180),
        cv_text($profile['career_objective'] ?? '', 5000),
        cv_text($profile['professional_summary'] ?? '', 5000),
        cv_text($profile['phone'] ?? '', 80),
        cv_text($profile['contact_email'] ?? '', 255),
        cv_text($profile['address'] ?? '', 1000),
        cv_text($profile['photo_url'] ?? '', 500),
        cv_text($profile['website'] ?? '', 255),
        cv_text($profile['linkedin_url'] ?? '', 255),
        cv_text($profile['nationality'] ?? '', 120),
        cv_text($profile['languages'] ?? '', 500),
        cv_text($profile['hobbies'] ?? '', 2000),
        cv_text($profile['date_of_birth'] ?? '', 10),
        cv_text($profile['marital_status'] ?? '', 80),
        cv_text($profile['place_of_birth'] ?? '', 150),
        cv_text($profile['religion'] ?? '', 100),
        cv_text($profile['gender'] ?? '', 40),
        cv_text($profile['nrc_number'] ?? '', 80),
        cv_text($profile['cv_name'] ?? '', 150),
    ];
    $photoPath = cv_text($profile['photo_url'] ?? '', 500);
    $photoData = (string)($input['photo_data'] ?? '');
    if ($photoData !== '') {
        if (strlen($photoData) > 2800000) cv_reply(['detail'=>'Choose a photo smaller than 2 MB.'], 413);
        $photoBytes = base64_decode($photoData, true);
        $imageInfo = $photoBytes === false ? false : @getimagesizefromstring($photoBytes);
        $extensions = ['image/jpeg'=>'jpg', 'image/png'=>'png', 'image/webp'=>'webp'];
        $mime = is_array($imageInfo) ? ($imageInfo['mime'] ?? '') : '';
        if ($photoBytes === false || !$imageInfo || !isset($extensions[$mime])) {
            cv_reply(['detail'=>'Choose a valid JPG, PNG or WEBP photo.'], 422);
        }
        $photoDirectory = __DIR__ . '/uploads/cv';
        if (!is_dir($photoDirectory) && !mkdir($photoDirectory, 0755, true) && !is_dir($photoDirectory)) {
            cv_reply(['detail'=>'The CV photo folder is not writable. Create api/uploads/cv and allow PHP to write to it.'], 500);
        }
        $photoName = $userId . '_' . bin2hex(random_bytes(10)) . '.' . $extensions[$mime];
        if (file_put_contents($photoDirectory . '/' . $photoName, $photoBytes, LOCK_EX) === false) {
            cv_reply(['detail'=>'The CV photo could not be stored on the server.'], 500);
        }
        $photoPath = 'uploads/cv/' . $photoName;
    }
    $profile['photo_url'] = $photoPath;
    $profileData[6] = $photoPath;

    $allowed = ['education','experience','internship','work_learning','certification','project','skill','referee'];
    $pdo->beginTransaction();
    $upsert = $pdo->prepare('INSERT INTO cv_profiles (user_id, professional_title, career_objective, professional_summary, phone, contact_email, address, photo_url, website, linkedin_url, nationality, languages, hobbies, date_of_birth, marital_status, place_of_birth, religion, gender, nrc_number, cv_name, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) ON CONFLICT (user_id) DO UPDATE SET professional_title=EXCLUDED.professional_title, career_objective=EXCLUDED.career_objective, professional_summary=EXCLUDED.professional_summary, phone=EXCLUDED.phone, contact_email=EXCLUDED.contact_email, address=EXCLUDED.address, photo_url=EXCLUDED.photo_url, website=EXCLUDED.website, linkedin_url=EXCLUDED.linkedin_url, nationality=EXCLUDED.nationality, languages=EXCLUDED.languages, hobbies=EXCLUDED.hobbies, date_of_birth=EXCLUDED.date_of_birth, marital_status=EXCLUDED.marital_status, place_of_birth=EXCLUDED.place_of_birth, religion=EXCLUDED.religion, gender=EXCLUDED.gender, nrc_number=EXCLUDED.nrc_number, cv_name=EXCLUDED.cv_name, updated_at=CURRENT_TIMESTAMP');
    $upsert->execute(array_merge([$userId], $profileData));
    $pdo->prepare('DELETE FROM cv_entries WHERE user_id = ?')->execute([$userId]);
    $insert = $pdo->prepare('INSERT INTO cv_entries (user_id, section, sort_order, entry_data) VALUES (?, ?, ?, CAST(? AS JSONB))');
    foreach ($allowed as $section) {
        $rows = $sections[$section] ?? [];
        if (!is_array($rows)) continue;
        foreach (array_values($rows) as $order => $entry) {
            if (!is_array($entry)) continue;
            $clean = [];
            foreach ($entry as $key => $value) {
                $key = preg_replace('/[^a-zA-Z0-9_]/', '', (string)$key);
                if ($key === '') continue;
                $clean[$key] = cv_text($value, 5000);
            }
            if (count(array_filter($clean, fn($value) => $value !== null)) === 0) continue;
            $insert->execute([$userId, $section, $order, json_encode($clean, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)]);
        }
    }
    $changed = ['Contact information', 'Personal information', 'Professional profile'];
    foreach ($allowed as $section) {
        if (!empty($sections[$section])) $changed[] = ucwords(str_replace('_', ' ', $section));
    }
    $log = $pdo->prepare('INSERT INTO cv_change_log (cv_user_id, changed_by_user_id, changed_sections) VALUES (?, ?, ?)');
    $log->execute([$userId, $userId, implode(', ', array_unique($changed))]);
    $pdo->commit();
    cv_reply(['message'=>'Your CV has been saved.','data'=>cv_public_row($pdo, $userId)], 200);
} catch (Throwable $error) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log('CV module error: ' . $error->getMessage());
    cv_reply(['detail'=>'The CV could not be saved. Check the database setup and try again.'], 500);
}
