<?php
session_start();

// File paths
define('DATA_DIR', dirname(__DIR__) . '/data/');

// ============ JSON FILE HANDLING ============
function initDataFiles() {
    $files = ['users', 'memos', 'quizzes', 'questions', 'results', 'reports', 'maintenance_manual', 'maintenance_manuals_history', 'tools'];
    foreach ($files as $file) {
        $path = DATA_DIR . $file . '.json';
        if (!file_exists($path)) {
            file_put_contents($path, json_encode([]));
        }
    }
}

function readJson($filename) {
    $path = DATA_DIR . $filename . '.json';
    if (!file_exists($path)) return [];
    $content = file_get_contents($path);
    return json_decode($content, true) ?: [];
}

function writeJson($filename, $data) {
    $path = DATA_DIR . $filename . '.json';
    return file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT));
}

function getNextId($filename) {
    $data = readJson($filename);
    if (empty($data)) return 1;
    $ids = array_column($data, 'id');
    return max($ids) + 1;
}

// ============ USER AUTHENTICATION ============
function authenticate($username, $password) {
    $users = readJson('users');
    foreach ($users as $user) {
        if ($user['username'] === $username && $user['password'] === $password) {
            return $user;
        }
    }
    return false;
}

function getUserById($id) {
    $users = readJson('users');
    foreach ($users as $user) {
        if ($user['id'] == $id) return $user;
    }
    return null;
}

function getAllEmployees() {
    $users = readJson('users');
    return array_values(array_filter($users, function($user) {
        return $user['role'] === 'employee';
    }));
}

function getActiveEmployees() {
    $users = readJson('users');
    return array_values(array_filter($users, function($user) {
        $isActive = isset($user['is_active']) ? $user['is_active'] : true;
        return $user['role'] === 'employee' && $isActive;
    }));
}

function renumberUserIds() {
    $users = readJson('users');
    $newUsers = [];
    $newId = 1;
    foreach ($users as $user) {
        $user['id'] = $newId;
        $newUsers[] = $user;
        $newId++;
    }
    writeJson('users', $newUsers);
    return count($newUsers);
}

// Get user's work cycle (stored or calculated)
function getUserCycle($userId) {
    $user = getUserById($userId);
    if (!$user) return 'Odd';
    if (isset($user['cycle']) && !empty($user['cycle'])) {
        return $user['cycle'];
    }
    // Fallback to ID-based calculation for existing users
    return ($userId % 2 == 0) ? 'Even' : 'Odd';
}

// ============ AIRCRAFT ENDORSEMENTS ============
function getAircraftTypes() {
    return [
        'Boeing 737' => 'B737', 'Boeing 747' => 'B747', 'Boeing 767' => 'B767',
        'Boeing 777' => 'B777', 'Boeing 787' => 'B787', 'Airbus A320' => 'A320',
        'Airbus A330' => 'A330', 'Airbus A350' => 'A350', 'Airbus A380' => 'A380',
        'Embraer E175' => 'E175', 'Embraer E190' => 'E190', 'CRJ900' => 'CRJ900',
        'Dash 8 Q400' => 'DH8D'
    ];
}

function getEmployeeEndorsements($userId) {
    $users = readJson('users');
    foreach ($users as $user) {
        if ($user['id'] == $userId) {
            return isset($user['endorsements']) ? $user['endorsements'] : [];
        }
    }
    return [];
}

function updateEmployeeEndorsements($userId, $endorsements) {
    $users = readJson('users');
    foreach ($users as &$user) {
        if ($user['id'] == $userId) {
            $user['endorsements'] = $endorsements;
            writeJson('users', $users);
            return true;
        }
    }
    return false;
}

function formatEndorsements($endorsements) {
    if (empty($endorsements)) return '';
    return implode(' • ', $endorsements);
}

// ============ MEMOS ============
function getUnreadMemos($userId) {
    $memos = readJson('memos');
    $unread = [];
    foreach ($memos as $memo) {
        if (in_array($userId, $memo['assigned_to']) && !in_array($userId, $memo['read_by'] ?? [])) {
            $unread[] = $memo;
        }
    }
    return $unread;
}

function markMemoAsRead($memoId, $userId) {
    $memos = readJson('memos');
    foreach ($memos as &$memo) {
        if ($memo['id'] == $memoId) {
            if (!in_array($userId, $memo['read_by'] ?? [])) {
                $memo['read_by'][] = $userId;
                $memo['read_at'][$userId] = date('Y-m-d H:i:s');
                writeJson('memos', $memos);
                return true;
            }
        }
    }
    return false;
}

function isMemoRead($memoId, $userId) {
    $memos = readJson('memos');
    foreach ($memos as $memo) {
        if ($memo['id'] == $memoId) {
            return in_array($userId, $memo['read_by'] ?? []);
        }
    }
    return false;
}

function getUserMemos($userId) {
    $memos = readJson('memos');
    $userMemos = [];
    foreach ($memos as $memo) {
        if (in_array($userId, $memo['assigned_to'])) {
            $memo['is_read'] = in_array($userId, $memo['read_by'] ?? []);
            $userMemos[] = $memo;
        }
    }
    usort($userMemos, function($a, $b) {
        if ($a['is_read'] != $b['is_read']) return $a['is_read'] ? 1 : -1;
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    return $userMemos;
}

// ============ QUIZZES ============
function getPendingQuizzes($userId) {
    $quizzes = readJson('quizzes');
    $results = readJson('results');
    $completedQuizIds = [];
    foreach ($results as $result) {
        if ($result['user_id'] == $userId) $completedQuizIds[] = $result['quiz_id'];
    }
    $pending = [];
    foreach ($quizzes as $quiz) {
        if (in_array($userId, $quiz['assigned_to']) && !in_array($quiz['id'], $completedQuizIds)) {
            $pending[] = $quiz;
        }
    }
    return $pending;
}

// ============ LICENSE EXPIRY ============
function getUserExpiringLicenses($userId) {
    $user = getUserById($userId);
    if (!$user) return [];
    $expiring = [];
    $today = date('Y-m-d');
    $ninetyDays = date('Y-m-d', strtotime('+90 days'));
    
    if (!empty($user['ame_expiry']) && $user['ame_expiry'] >= $today && $user['ame_expiry'] <= $ninetyDays) {
        $daysLeft = ceil((strtotime($user['ame_expiry']) - strtotime($today)) / (60 * 60 * 24));
        $expiring[] = ['type' => 'AME License', 'number' => $user['ame_license'] ?? '', 'expiry_date' => $user['ame_expiry'], 'days_left' => $daysLeft];
    }
    if (!empty($user['raic_expiry']) && $user['raic_expiry'] >= $today && $user['raic_expiry'] <= $ninetyDays) {
        $daysLeft = ceil((strtotime($user['raic_expiry']) - strtotime($today)) / (60 * 60 * 24));
        $expiring[] = ['type' => 'RAIC', 'number' => $user['raic_number'] ?? '', 'expiry_date' => $user['raic_expiry'], 'days_left' => $daysLeft];
    }
    if (!empty($user['da_expiry']) && $user['da_expiry'] >= $today && $user['da_expiry'] <= $ninetyDays) {
        $daysLeft = ceil((strtotime($user['da_expiry']) - strtotime($today)) / (60 * 60 * 24));
        $expiring[] = ['type' => 'DA Number', 'number' => $user['da_number'] ?? '', 'expiry_date' => $user['da_expiry'], 'days_left' => $daysLeft];
    }
    if (!empty($user['amo_stamp_expiry']) && $user['amo_stamp_expiry'] >= $today && $user['amo_stamp_expiry'] <= $ninetyDays) {
        $daysLeft = ceil((strtotime($user['amo_stamp_expiry']) - strtotime($today)) / (60 * 60 * 24));
        $expiring[] = ['type' => 'AMO Stamp', 'number' => $user['amo_stamp_number'] ?? '', 'expiry_date' => $user['amo_stamp_expiry'], 'days_left' => $daysLeft];
    }
    return $expiring;
}

function getAllExpiringLicenses() {
    $users = getAllEmployees();
    $allExpiring = [];
    foreach ($users as $user) {
        $expiring = getUserExpiringLicenses($user['id']);
        if (!empty($expiring)) {
            $allExpiring[] = [
                'user_id' => $user['id'],
                'user_name' => $user['full_name'],
                'user_email' => $user['email'],
                'expiring_items' => $expiring
            ];
        }
    }
    return $allExpiring;
}

function getExpiringLicenses($user) {
    $expiring = [];
    $thirtyDays = date('Y-m-d', strtotime('+30 days'));
    if (isset($user['ame_expiry']) && $user['ame_expiry'] && $user['ame_expiry'] <= $thirtyDays) $expiring[] = "AME License expires on " . $user['ame_expiry'];
    if (isset($user['raic_expiry']) && $user['raic_expiry'] && $user['raic_expiry'] <= $thirtyDays) $expiring[] = "RAIC expires on " . $user['raic_expiry'];
    if (isset($user['da_expiry']) && $user['da_expiry'] && $user['da_expiry'] <= $thirtyDays) $expiring[] = "DA Number expires on " . $user['da_expiry'];
    if (isset($user['amo_stamp_expiry']) && $user['amo_stamp_expiry'] && $user['amo_stamp_expiry'] <= $thirtyDays) $expiring[] = "AMO Stamp expires on " . $user['amo_stamp_expiry'];
    return $expiring;
}

// ============ SAFETY REPORTS & REPLIES ============
function addReportReply($reportId, $userId, $replyText, $userRole) {
    $reports = readJson('reports');
    foreach ($reports as &$report) {
        if ($report['id'] == $reportId) {
            if (!isset($report['replies'])) $report['replies'] = [];
            $report['replies'][] = [
                'id' => count($report['replies']) + 1,
                'user_id' => $userId,
                'user_role' => $userRole,
                'reply' => $replyText,
                'created_at' => date('Y-m-d H:i:s')
            ];
            writeJson('reports', $reports);
            return true;
        }
    }
    return false;
}

function getReportReplies($reportId) {
    $reports = readJson('reports');
    foreach ($reports as $report) {
        if ($report['id'] == $reportId) return isset($report['replies']) ? $report['replies'] : [];
    }
    return [];
}

function getUserSafetyReports($userId) {
    $reports = readJson('reports');
    $userReports = [];
    foreach ($reports as $report) {
        if ($report['user_id'] == $userId) $userReports[] = $report;
    }
    usort($userReports, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    return $userReports;
}

function getAllSafetyReports() {
    $reports = readJson('reports');
    $allReports = [];
    foreach ($reports as $report) {
        $user = getUserById($report['user_id']);
        $report['user_name'] = $user ? $user['full_name'] : 'Unknown';
        $report['user_email'] = $user ? $user['email'] : 'Unknown';
        $report['reply_count'] = isset($report['replies']) ? count($report['replies']) : 0;
        $allReports[] = $report;
    }
    usort($allReports, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    return $allReports;
}

function markReportAsRead($reportId) {
    $reports = readJson('reports');
    foreach ($reports as &$report) {
        if ($report['id'] == $reportId) {
            $report['status'] = 'read';
            writeJson('reports', $reports);
            return true;
        }
    }
    return false;
}

// ============ EMPLOYEE DOCUMENTS (Resume & Certificates) ============
function getUserDocsFolder($userId) {
    return __DIR__ . '/../uploads/user_docs/' . $userId . '/';
}

function getUserDocuments($userId) {
    $folder = getUserDocsFolder($userId);
    if (!file_exists($folder)) return [];
    $files = scandir($folder);
    $documents = [];
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            $type = (stripos($file, 'resume') !== false) ? 'resume' : 'certificate';
            $documents[] = [
                'filename' => $file,
                'path' => 'uploads/user_docs/' . $userId . '/' . $file,
                'type' => $type,
                'size' => filesize($folder . $file),
                'uploaded_at' => date('Y-m-d H:i:s', filemtime($folder . $file))
            ];
        }
    }
    return $documents;
}

function saveUserDocument($userId, $file, $docType) {
    $folder = getUserDocsFolder($userId);
    if (!file_exists($folder)) mkdir($folder, 0777, true);
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $timestamp = time();
    $random = uniqid();
    $newName = ($docType == 'resume' ? 'resume_' : 'cert_') . $timestamp . '_' . $random . '.' . $ext;
    $destination = $folder . $newName;
    if (move_uploaded_file($file['tmp_name'], $destination)) {
        return $newName;
    }
    return false;
}

function deleteUserDocument($userId, $filename) {
    $folder = getUserDocsFolder($userId);
    $filepath = $folder . $filename;
    if (file_exists($filepath)) {
        return unlink($filepath);
    }
    return false;
}

// ============ CHAT FUNCTIONS ============
function getChatGroups() {
    return [
        'CE CARGO' => 'ce_cargo',
        'CS CARGO' => 'cs_cargo',
        'CE PAX'   => 'ce_pax',
        'CS PAX'   => 'cs_pax',
        'BIMAN'    => 'biman',
        'AIRLINE'  => 'airline'
    ];
}

function getChatMessages($groupId, $limit = 100) {
    $file = DATA_DIR . 'chat_' . $groupId . '.json';
    if (!file_exists($file)) return [];
    $messages = json_decode(file_get_contents($file), true);
    if (!is_array($messages)) return [];
    return array_slice($messages, -$limit);
}

function saveChatMessage($groupId, $userId, $message, $fileAttachment = null) {
    $file = DATA_DIR . 'chat_' . $groupId . '.json';
    $messages = [];
    if (file_exists($file)) {
        $messages = json_decode(file_get_contents($file), true);
        if (!is_array($messages)) $messages = [];
    }
    $newMessage = [
        'id' => count($messages) + 1,
        'user_id' => $userId,
        'message' => $message,
        'file' => $fileAttachment,
        'timestamp' => date('Y-m-d H:i:s')
    ];
    $messages[] = $newMessage;
    file_put_contents($file, json_encode($messages, JSON_PRETTY_PRINT));
    return true;
}

function getChatDisplayName($userId, $forAdmin = false) {
    $user = getUserById($userId);
    if (!$user) return 'Unknown';
    if ($forAdmin) {
        return $user['full_name'];
    } else {
        return !empty($user['amo_stamp_number']) ? $user['amo_stamp_number'] : $user['username'];
    }
}

// ============ TOOLS MANAGEMENT ============
function getTools() {
    $tools = readJson('tools');
    usort($tools, function($a, $b) {
        return strtotime($a['calibration_date']) - strtotime($b['calibration_date']);
    });
    return $tools;
}

function addTool($toolName, $partNumber, $calibrationDate) {
    $tools = readJson('tools');
    $newId = getNextId('tools');
    $tools[] = [
        'id' => $newId,
        'tool_name' => $toolName,
        'part_number' => $partNumber,
        'calibration_date' => $calibrationDate,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s')
    ];
    writeJson('tools', $tools);
    return $newId;
}

function updateTool($id, $toolName, $partNumber, $calibrationDate) {
    $tools = readJson('tools');
    foreach ($tools as &$tool) {
        if ($tool['id'] == $id) {
            $tool['tool_name'] = $toolName;
            $tool['part_number'] = $partNumber;
            $tool['calibration_date'] = $calibrationDate;
            $tool['updated_at'] = date('Y-m-d H:i:s');
            writeJson('tools', $tools);
            return true;
        }
    }
    return false;
}

function deleteTool($id) {
    $tools = readJson('tools');
    $newTools = [];
    foreach ($tools as $tool) {
        if ($tool['id'] != $id) $newTools[] = $tool;
    }
    writeJson('tools', $newTools);
    return true;
}

// ============ EMAIL FUNCTIONS (disabled for free hosting) ============
function sendEmailNotification($to, $subject, $message) { return true; }
function sendWelcomeEmail($email, $username, $password, $fullName) { return true; }
function sendNewMemoNotification($email, $fullName, $memoTitle, $memoContent, $memoId, $hasPDF = false) { return true; }
function sendNewQuizNotification($email, $fullName, $quizTitle, $quizDescription, $passingScore, $quizId) { return true; }
function sendSafetyReportNotification($adminEmail, $employeeName, $employeeEmail, $reportTitle, $reportContent, $reportId) { return true; }

// ============ INITIALIZATION ============
initDataFiles();

// Create default admin if none exists
$users = readJson('users');
if (empty($users)) {
    $users[] = [
        'id' => 1,
        'username' => 'admin',
        'password' => 'admin123',
        'email' => 'rxaero.mro@gmail.com',
        'phone' => '1234567890',
        'full_name' => 'System Administrator',
        'cycle' => 'Odd',
        'ame_license' => '',
        'ame_expiry' => '',
        'raic_number' => '',
        'raic_expiry' => '',
        'da_number' => '',
        'da_expiry' => '',
        'amo_stamp_number' => '',
        'amo_stamp_expiry' => '',
        'endorsements' => [],
        'is_active' => true,
        'role' => 'admin',
        'created_at' => date('Y-m-d H:i:s')
    ];
    writeJson('users', $users);
}
?>