<?php
// includes/functions.php - توابع کامل سیستم

header('Content-Type: text/html; charset=UTF-8');

// =============================================
// توابع تبدیل تاریخ
// =============================================

function gregorianToJalali($g_y, $g_m, $g_d) {
    $g_days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    $j_days_in_month = array(31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29);

    $gy = $g_y - 1600;
    $gm = $g_m - 1;
    $gd = $g_d - 1;

    $g_day_no = 365 * $gy + (int)(($gy + 3) / 4) - (int)(($gy + 99) / 100) + (int)(($gy + 399) / 400);

    for ($i = 0; $i < $gm; ++$i) {
        $g_day_no += $g_days_in_month[$i];
    }

    if ($gm > 1 && (($gy % 4 == 0 && $gy % 100 != 0) || ($gy % 400 == 0))) {
        $g_day_no++;
    }

    $g_day_no += $gd;

    $j_day_no = $g_day_no - 79;

    $j_np = (int)($j_day_no / 12053);
    $j_day_no %= 12053;

    $jy = 979 + 33 * $j_np + 4 * (int)($j_day_no / 1461);
    $j_day_no %= 1461;

    if ($j_day_no >= 366) {
        $jy += (int)(($j_day_no - 1) / 365);
        $j_day_no = ($j_day_no - 1) % 365;
    }

    for ($i = 0; $i < 11 && $j_day_no >= $j_days_in_month[$i]; ++$i) {
        $j_day_no -= $j_days_in_month[$i];
    }

    $jm = $i + 1;
    $jd = $j_day_no + 1;

    return array($jy, $jm, $jd);
}

function jalaliDate($date, $format = 'Y/m/d') {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return '-';
    }

    // حذف زمان (اگر وجود داشته باشد)
    $dateParts = explode(' ', trim($date));
    $dateStr = $dateParts[0];

    // اگر تاریخ به صورت شمسی است (سال بین 1300 تا 1500)
    $parts = explode('-', $dateStr);
    if (count($parts) == 3) {
        $year = (int)$parts[0];
        if ($year >= 1300 && $year <= 1500) {
            return str_replace('-', '/', $dateStr);
        }
    }

    // تجزیه تاریخ میلادی
    if (count($parts) != 3) return $dateStr;

    $gy = (int)$parts[0];
    $gm = (int)$parts[1];
    $gd = (int)$parts[2];

    if ($gy < 1900 || $gy > 2100 || $gm < 1 || $gm > 12 || $gd < 1 || $gd > 31) {
        return $dateStr;
    }

    list($jy, $jm, $jd) = gregorianToJalali($gy, $gm, $gd);

    $output = '';
    for ($i = 0; $i < strlen($format); $i++) {
        $char = $format[$i];
        if ($char == 'Y') $output .= $jy;
        elseif ($char == 'y') $output .= substr($jy, -2);
        elseif ($char == 'm') $output .= str_pad($jm, 2, '0', STR_PAD_LEFT);
        elseif ($char == 'n') $output .= $jm;
        elseif ($char == 'd') $output .= str_pad($jd, 2, '0', STR_PAD_LEFT);
        elseif ($char == 'j') $output .= $jd;
        else $output .= $char;
    }
    return $output;
}

// =============================================
// تابع تبدیل تاریخ شمسی به میلادی
// =============================================

function shamsiToMiladi($shamsiDate) {
    if (empty($shamsiDate)) return null;
    
    $shamsiDate = trim($shamsiDate);
    $shamsiDate = str_replace(['-', '،', ' '], '/', $shamsiDate);
    
    $parts = explode('/', $shamsiDate);
    if (count($parts) != 3) return null;
    
    $year = (int)$parts[0];
    $month = (int)$parts[1];
    $day = (int)$parts[2];
    
    if ($year < 1300 || $year > 1500) return null;
    if ($month < 1 || $month > 12) return null;
    if ($day < 1 || $day > 31) return null;
    
    $baseShamsiYear = 1300;
    $baseMiladiYear = 1921;
    $baseMiladiMonth = 3;
    $baseMiladiDay = 22;
    
    $shamsiMonthDays = [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29];
    
    $dayOfYear = 0;
    for ($i = 0; $i < $month - 1; $i++) {
        $dayOfYear += $shamsiMonthDays[$i];
    }
    $dayOfYear += $day;
    
    $leapYears = 0;
    for ($i = $baseShamsiYear; $i < $year; $i++) {
        if (($i % 4 == 0 && $i % 100 != 0) || ($i % 400 == 0)) {
            $leapYears++;
        }
    }
    
    $totalDays = ($year - $baseShamsiYear) * 365 + $leapYears + $dayOfYear;
    
    $timestamp = mktime(0, 0, 0, $baseMiladiMonth, $baseMiladiDay, $baseMiladiYear);
    $timestamp += $totalDays * 86400;
    
    return date('Y-m-d', $timestamp);
}

// =============================================
// توابع عمومی
// =============================================

function persianNumber($number) {
    $persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    $english = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    return str_replace($english, $persian, $number);
}

function formatPrice($amount) {
    $amount = round($amount);
    return number_format($amount) . ' ریال';
}

function getShebaStatus($isConfirmed) {
    if ($isConfirmed) {
        return '<span class="badge-success"><i class="fas fa-check-circle"></i> تأیید شده</span>';
    }
    return '<span class="badge-warning"><i class="fas fa-clock"></i> در انتظار تأیید</span>';
}

function getStatusBadge($status) {
    if ($status) {
        return '<span class="badge-success">فعال</span>';
    }
    return '<span class="badge-danger">غیرفعال</span>';
}

function getTermName($termId) {
    if (empty($termId)) return '-';
    $term = fetchOne("SELECT name FROM terms WHERE id = ?", [$termId]);
    return $term ? $term['name'] : '-';
}

function validateNationalCode($code) {
    if (!preg_match('/^\d{10}$/', $code)) return false;
    $check = (int) substr($code, 9, 1);
    $sum = 0;
    for ($i = 0; $i < 9; $i++) {
        $sum += (int) substr($code, $i, 1) * (10 - $i);
    }
    $remain = $sum % 11;
    if ($remain < 2) {
        return $check == $remain;
    } else {
        return $check == (11 - $remain);
    }
}

function validateMobile($mobile) {
    return preg_match('/^09\d{9}$/', $mobile);
}

function validateSheba($sheba) {
    $sheba = preg_replace('/[^A-Za-z0-9]/', '', $sheba);
    return strlen($sheba) == 26;
}

// =============================================
// توابع آماری
// =============================================

function getTotalTeachers() {
    return fetchCount("SELECT id FROM users WHERE role_id = (SELECT id FROM roles WHERE level = 6)");
}

function getTeachersWithSheba() {
    return fetchCount("SELECT id FROM users WHERE role_id = (SELECT id FROM roles WHERE level = 6) AND sheba_number IS NOT NULL AND sheba_number != '' AND is_sheba_confirmed = 1");
}

function getTeachersWithoutSheba() {
    return fetchCount("SELECT id FROM users WHERE role_id = (SELECT id FROM roles WHERE level = 6) AND (sheba_number IS NULL OR sheba_number = '')");
}

function getPendingSheba() {
    return fetchCount("SELECT id FROM users WHERE role_id = (SELECT id FROM roles WHERE level = 6) AND sheba_number IS NOT NULL AND sheba_number != '' AND is_sheba_confirmed = 0");
}

function getRecentLogins($limit = 10) {
    return fetchAll(
        "SELECT u.*, r.name as role_name 
         FROM users u 
         LEFT JOIN roles r ON u.role_id = r.id 
         WHERE u.last_login IS NOT NULL 
         ORDER BY u.last_login DESC 
         LIMIT ?",
        [$limit]
    );
}

function getAllTeachers($limit = null, $offset = 0) {
    $sql = "SELECT u.*, r.name as role_name 
            FROM users u 
            LEFT JOIN roles r ON u.role_id = r.id 
            WHERE u.role_id = (SELECT id FROM roles WHERE level = 6)";
    if ($limit) {
        $sql .= " LIMIT $offset, $limit";
    }
    return fetchAll($sql);
}

function getTeacherCourses($teacherId) {
    return fetchAll(
        "SELECT c.*, t.name as term_name, t.code as term_code
         FROM courses c 
         LEFT JOIN terms t ON c.term_id = t.id
         WHERE c.teacher_id = ? 
         ORDER BY c.created_at DESC",
        [$teacherId]
    );
}

function getTeacherTransactions($teacherId) {
    return fetchAll(
        "SELECT t.*, tm.name as term_name, tm.code as term_code
         FROM transactions t 
         LEFT JOIN terms tm ON t.term_id = tm.id
         WHERE t.teacher_id = ? 
         ORDER BY t.payment_date DESC",
        [$teacherId]
    );
}

// =============================================
// توابع مدیریتی
// =============================================

function getAllRoles() {
    return fetchAll("SELECT * FROM roles ORDER BY level ASC");
}

function getRolePermissions($roleId) {
    return fetchAll(
        "SELECT * FROM permissions WHERE role_id = ? ORDER BY permission_name",
        [$roleId]
    );
}

function getAllTerms() {
    return fetchAll("SELECT * FROM terms ORDER BY id DESC");
}

function getActiveTerm() {
    return fetchOne("SELECT * FROM terms WHERE is_active = 1 LIMIT 1");
}

function updateTeacherSheba($teacherId, $shebaNumber) {
    return updateData(
        'users',
        ['sheba_number' => $shebaNumber, 'is_sheba_confirmed' => 0],
        'id = :id',
        ['id' => $teacherId]
    );
}

function confirmTeacherSheba($teacherId) {
    return updateData(
        'users',
        ['is_sheba_confirmed' => 1],
        'id = :id',
        ['id' => $teacherId]
    );
}

function updateTeacher($teacherId, $data) {
    return updateData('users', $data, 'id = :id', ['id' => $teacherId]);
}

function deleteTeacher($teacherId) {
    return updateData('users', ['is_active' => 0], 'id = :id', ['id' => $teacherId]);
}

function createCourse($data) {
    return insertData('courses', $data);
}

function updateCourse($courseId, $data) {
    return updateData('courses', $data, 'id = :id', ['id' => $courseId]);
}

function deleteCourse($courseId) {
    return deleteData('courses', 'id = :id', ['id' => $courseId]);
}

function createTransaction($data) {
    return insertData('transactions', $data);
}

function updateTransaction($transactionId, $data) {
    return updateData('transactions', $data, 'id = :id', ['id' => $transactionId]);
}

// =============================================
// توابع تیکتینگ
// =============================================

function getUserTickets($userId, $status = 'all', $priority = 'all', $search = '') {
    $sql = "SELECT t.*, 
                   u1.name as sender_name, u1.family as sender_family,
                   u2.name as receiver_name, u2.family as receiver_family,
                   r.name as receiver_role_name
            FROM tickets t
            LEFT JOIN users u1 ON t.sender_id = u1.id
            LEFT JOIN users u2 ON t.receiver_id = u2.id
            LEFT JOIN roles r ON t.receiver_role_id = r.id
            WHERE t.sender_id = ? OR t.receiver_id = ? OR t.receiver_role_id = ?";
    $params = [$userId, $userId, getUserRoleId($userId)];
    
    if ($status != 'all') {
        $sql .= " AND t.status = ?";
        $params[] = $status;
    }
    
    if ($priority != 'all') {
        $sql .= " AND t.priority = ?";
        $params[] = $priority;
    }
    
    if (!empty($search)) {
        $sql .= " AND (t.subject LIKE ? OR t.body LIKE ?)";
        $searchTerm = "%$search%";
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }
    
    $sql .= " ORDER BY t.created_at DESC";
    
    return fetchAll($sql, $params);
}

function getTicketById($ticketId) {
    return fetchOne(
        "SELECT t.*, 
                u1.name as sender_name, u1.family as sender_family,
                u2.name as receiver_name, u2.family as receiver_family,
                r.name as receiver_role_name
         FROM tickets t
         LEFT JOIN users u1 ON t.sender_id = u1.id
         LEFT JOIN users u2 ON t.receiver_id = u2.id
         LEFT JOIN roles r ON t.receiver_role_id = r.id
         WHERE t.id = ?",
        [$ticketId]
    );
}

function getTicketReplies($ticketId) {
    return fetchAll(
        "SELECT r.*, u.name, u.family
         FROM ticket_replies r
         LEFT JOIN users u ON r.user_id = u.id
         WHERE r.ticket_id = ?
         ORDER BY r.created_at ASC",
        [$ticketId]
    );
}

function getUserRoleId($userId) {
    $user = fetchOne("SELECT role_id FROM users WHERE id = ?", [$userId]);
    return $user ? $user['role_id'] : null;
}

function getTicketStats($userId) {
    $roleId = getUserRoleId($userId);
    
    return [
        'total' => fetchCount(
            "SELECT id FROM tickets WHERE sender_id = ? OR receiver_id = ? OR receiver_role_id = ?",
            [$userId, $userId, $roleId]
        ),
        'new' => fetchCount(
            "SELECT id FROM tickets WHERE (sender_id = ? OR receiver_id = ? OR receiver_role_id = ?) AND status = 'new'",
            [$userId, $userId, $roleId]
        ),
        'replied' => fetchCount(
            "SELECT id FROM tickets WHERE (sender_id = ? OR receiver_id = ? OR receiver_role_id = ?) AND status = 'replied'",
            [$userId, $userId, $roleId]
        ),
        'closed' => fetchCount(
            "SELECT id FROM tickets WHERE (sender_id = ? OR receiver_id = ? OR receiver_role_id = ?) AND status = 'closed'",
            [$userId, $userId, $roleId]
        ),
        'unread' => fetchCount(
            "SELECT id FROM tickets WHERE (receiver_id = ? OR receiver_role_id = ?) AND is_read = 0",
            [$userId, $roleId]
        )
    ];
}

function createTicket($data) {
    return insertData('tickets', $data);
}

function createTicketReply($data) {
    return insertData('ticket_replies', $data);
}

function updateTicketStatus($ticketId, $status) {
    return updateData('tickets', ['status' => $status], 'id = :id', ['id' => $ticketId]);
}

function markTicketAsRead($ticketId, $userId) {
    $ticket = getTicketById($ticketId);
    if (!$ticket) return false;
    
    if ($ticket['receiver_id'] == $userId || $ticket['receiver_role_id'] == getUserRoleId($userId)) {
        return updateData('tickets', [
            'is_read' => 1,
            'read_at' => date('Y-m-d H:i:s'),
            'status' => 'viewed'
        ], 'id = :id', ['id' => $ticketId]);
    }
    return false;
}

// =============================================
// تابع حذف تیکت (اصلاح شده)
// =============================================

function deleteTicket($ticketId, $userId) {
    // ===== دریافت اطلاعات کاربر =====
    $user = fetchOne("SELECT role_level FROM users WHERE id = ?", [$userId]);
    
    // ===== اگر کاربر وجود نداشت =====
    if (!$user) {
        return false;
    }
    
    // ===== اگر مدیر سامانه نبود =====
    if ($user['role_level'] != 1) {
        return false;
    }
    
    // ===== حذف تیکت =====
    return deleteData('tickets', 'id = :id', ['id' => $ticketId]);
}

function getUnreadTicketCount($userId) {
    $roleId = getUserRoleId($userId);
    return fetchCount(
        "SELECT id FROM tickets WHERE (receiver_id = ? OR receiver_role_id = ?) AND is_read = 0",
        [$userId, $roleId]
    );
}

function getPriorityList() {
    return [
        'low' => 'کم',
        'medium' => 'متوسط',
        'high' => 'بالا',
        'critical' => 'بحرانی'
    ];
}

function getPriorityColor($priority) {
    $colors = [
        'low' => 'badge-info',
        'medium' => 'badge-warning',
        'high' => 'badge-danger',
        'critical' => 'badge-danger'
    ];
    return $colors[$priority] ?? 'badge-info';
}

// =============================================
// دریافت نام مدرک تحصیلی بر اساس کد
// =============================================

function getDegreeName($degreeCode) {
    $degrees = [
        1 => 'کارشناسی',
        2 => 'کارشناسی ارشد',
        3 => 'دکتری'
    ];
    return $degrees[$degreeCode] ?? '-';
}

// =============================================
// توابع تنظیمات حق التدریس
// =============================================

function getCourseTypeName($type) {
    $types = [
        'theoretical' => 'نظری - علمی',
        'internship' => 'کاربینی',
        'practicum' => 'کارورزی',
        'project' => 'پروژه'
    ];
    return $types[$type] ?? $type;
}

function getSalaryAmount($degree, $courseType) {
    $setting = fetchOne(
        "SELECT amount_per_hour, amount_per_student FROM salary_settings 
         WHERE degree = ? AND course_type = ?",
        [$degree, $courseType]
    );
    return $setting;
}

function getTaxSettings() {
    return fetchOne("SELECT * FROM tax_settings WHERE id = 1");
}

?>