<?php

if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

// --- Pagination Helper ---

function buildPaginationRow(string $action, int $offset, int $limit, int $total, array $extra_params = []): array {
    $pagination_row = [];
    
    if ($total > $limit) {
        $current_page = floor($offset / $limit) + 1;
        $total_pages = ceil($total / $limit);

        if ($offset > 0) {
             $prev_params = array_merge($extra_params, ['offset' => max(0, $offset - $limit)]);
            $pagination_row[] = ['text' => '⬅️ قبلی', 'callback_data' => buildCallbackData($action, $prev_params)]; 
        } else {
           $pagination_row[] = ['text' => ' ', 'callback_data' => 'noop'];
        }

        $pagination_row[] = ['text' => "{$current_page}/{$total_pages}", 'callback_data' => 'noop'];

        if (($offset + $limit) < $total) {
            $next_params = array_merge($extra_params, ['offset' => $offset + $limit]);
             $pagination_row[] = ['text' => 'بعدی ➡️', 'callback_data' => buildCallbackData($action, $next_params)]; 
        } else {
           $pagination_row[] = ['text' => ' ', 'callback_data' => 'noop']; 
        }
    }
    
    return (count($pagination_row) > 1) ? $pagination_row : []; 
}


// --- Birth Date Keyboards ---

function buildBirthYearKeyboard(string $action_prefix, int $offset = 0): array {
    $buttons = [];
    $years_per_page = 20;
    $years_per_row = 5;

    $start_year = 1340;
    $end_year = 1400; 

    $all_years = range($start_year, $end_year);
    $all_years = array_reverse($all_years);
    $total_years = count($all_years);

    $current_page_years = array_slice($all_years, $offset, $years_per_page);
    
    $year_chunks = array_chunk($current_page_years, $years_per_row);
    foreach ($year_chunks as $row_years) {
        $row = [];
        foreach ($row_years as $year) {
            $year_display = convertPersianToEnglishDigits((string)$year);
           $row[] = ['text' => $year_display, 'callback_data' => buildCallbackData($action_prefix . 'Year', ['y' => $year])];
        }
        if (!empty($row)) $buttons[] = $row;
    }
    
    $pagination_row = buildPaginationRow($action_prefix . 'YearPage', $offset, $years_per_page, $total_years);
    if (!empty($pagination_row)) {
        $buttons[] = $pagination_row;
    }
    
    return ['inline_keyboard' => $buttons];
}


function buildBirthMonthKeyboard(string $action_prefix, int $year): array {
    $buttons = []; 
    $persian_months = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند']; 
    $month_chunks = array_chunk($persian_months, 3); 
    
    foreach ($month_chunks as $index => $row_months) {
        $row = []; 
       $start_month = $index * 3 + 1; 
        foreach ($row_months as $m_index => $month_name) {
            $month_num = $start_month + $m_index; 
           $row[] = ['text' => $month_name, 'callback_data' => buildCallbackData($action_prefix . 'Month', ['y' => $year, 'm' => $month_num])]; 
        }
        $buttons[] = $row; 
    }
    
    $buttons[] = [['text' => '🔙 بازگشت (انتخاب سال)', 'callback_data' => buildCallbackData('backToBirthYear')]]; 
    return ['inline_keyboard' => $buttons]; 
}


function buildBirthDayKeyboard(string $action_prefix, int $year, int $month): array {
    $buttons = []; 
     
    $is_leap = false; 
    try {
        $a = $year % 33;
        $is_leap = in_array($a, [1, 5, 9, 13, 17, 22, 26, 30]);
    } catch (Exception $e) {}
    
    $days_in_month = ($month <= 6) ? 31 : (($month <= 11) ? 30 : ($is_leap ? 30 : 29)); 
    $day = 1; 
    $rows_needed = ceil($days_in_month / 7); 

    for ($i = 0; $i < $rows_needed; $i++) { 
       $row = []; 
        for ($j = 0; $j < 7; $j++) { 
            if ($day <= $days_in_month) {
                 $day_display = convertPersianToEnglishDigits((string)$day); 
                 $row[] = ['text' => $day_display, 'callback_data' => buildCallbackData($action_prefix . 'Day', ['y' => $year, 'm' => $month, 'd' => $day])]; 
                 $day++; 
            } else {
               $row[] = ['text' => ' ', 'callback_data' => 'noop'];
            }
        }
        if (!empty($row)) {
           $buttons[] = $row; 
        }
    }

    $buttons[] = [['text' => '🔙 بازگشت (انتخاب ماه)', 'callback_data' => buildCallbackData('backToBirthMonth', ['y' => $year])]]; 
    return ['inline_keyboard' => $buttons]; 
}


// --- Address (Province/City) Keyboards ---

function buildProvinceKeyboard(int $offset = 0): array {
    if (!isset($GLOBALS['provinces_cities']) || !is_array($GLOBALS['provinces_cities'])) {
        if (function_exists('get_iran_provinces_and_cities')) {
             $GLOBALS['provinces_cities'] = get_iran_provinces_and_cities(); 
        } else {
             if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Error: iran_cities data not available in buildProvinceKeyboard.\n", FILE_APPEND); }
             return ['inline_keyboard' => [[['text'=>'خطا در بارگذاری استان‌ها','callback_data'=>'noop']]]]; 
        }
    }

    $provinces_cities = $GLOBALS['provinces_cities']; 
    $provinces = array_keys($provinces_cities); 
    sort($provinces); 
    $limit = defined('PROVINCES_CITIES_PER_PAGE') ? PROVINCES_CITIES_PER_PAGE : 8; 
    $total = count($provinces); 
    $keyboard_rows = [];

    if ($offset < 0) $offset = 0; 
    if ($offset >= $total && $total > 0) $offset = max(0, floor(($total - 1) / $limit) * $limit); 

    $current_page_provinces = array_slice($provinces, $offset, $limit); 
    
    for ($i = 0; $i < count($current_page_provinces); $i += 2) { 
        $row = []; 
        $province1_name = $current_page_provinces[$i]; 
        $province1_index = array_search($province1_name, $provinces); 

        if ($province1_index !== false) {
            $row[] = ['text' => $province1_name, 'callback_data' => buildCallbackData('selectProvince', ['p_idx' => $province1_index])]; 
        }
        if (isset($current_page_provinces[$i + 1])) {
            $province2_name = $current_page_provinces[$i + 1]; 
            $province2_index = array_search($province2_name, $provinces); 
             if ($province2_index !== false) {
                 $row[] = ['text' => $province2_name, 'callback_data' => buildCallbackData('selectProvince', ['p_idx' => $province2_index])]; 
             }
        }
        if (!empty($row)) { 
            $keyboard_rows[] = $row; 
        }
     }
    
    $pagination_row = buildPaginationRow('selectProvincePage', $offset, $limit, $total); 
    if (!empty($pagination_row)) {
         $keyboard_rows[] = $pagination_row; 
    }
    
   $keyboard_rows[] = [['text' => '🔙 بازگشت', 'callback_data' => buildCallbackData('checkoutStart')]]; 
    
    return ['inline_keyboard' => $keyboard_rows]; 
}


function buildCityKeyboard(int $province_index, int $offset = 0): array {
     if (!isset($GLOBALS['provinces_cities']) || !is_array($GLOBALS['provinces_cities'])) {
       if (function_exists('get_iran_provinces_and_cities')) {
             $GLOBALS['provinces_cities'] = get_iran_provinces_and_cities();
       } else {
             if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Error: iran_cities data not available in buildCityKeyboard.\n", FILE_APPEND); }
           return ['inline_keyboard' => [[['text'=>'خطا در بارگذاری شهرها','callback_data'=>'noop']]]]; 
       }
     }

    $provinces_cities = $GLOBALS['provinces_cities']; 
    $provinces = array_keys($provinces_cities); 
    sort($provinces); 

    if (!isset($provinces[$province_index])) {
       if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Error: Province index '{$province_index}' not found in buildCityKeyboard.\n", FILE_APPEND); }
       return ['inline_keyboard' => [[['text' => 'خطا: استان یافت نشد', 'callback_data' => buildCallbackData('backToProvinceSelection')]]]]; 
    }
    $province_name = $provinces[$province_index]; 
    $cities = $provinces_cities[$province_name] ?? []; 
    sort($cities); 
    $limit = defined('PROVINCES_CITIES_PER_PAGE') ? PROVINCES_CITIES_PER_PAGE : 8; 
    $total = count($cities); 

    $keyboard_rows = []; 

    if ($offset < 0) $offset = 0; 
    if ($offset >= $total && $total > 0) $offset = max(0, floor(($total - 1) / $limit) * $limit); 
    
    $current_page_cities = array_slice($cities, $offset, $limit); 
    
    for ($i = 0; $i < count($current_page_cities); $i += 2) { 
        $row = []; 
         $city1_name = $current_page_cities[$i]; 
         $city1_index = array_search($city1_name, $cities); 
         if ($city1_index !== false) {
            $row[] = ['text' => $city1_name, 'callback_data' => buildCallbackData('selectCity', ['p_idx' => $province_index, 'c_idx' => $city1_index])]; 
         }
       
       if (isset($current_page_cities[$i + 1])) {
            $city2_name = $current_page_cities[$i + 1]; 
            $city2_index = array_search($city2_name, $cities); 
             if ($city2_index !== false) {
               $row[] = ['text' => $city2_name, 'callback_data' => buildCallbackData('selectCity', ['p_idx' => $province_index, 'c_idx' => $city2_index])];
             }
       }
         if (!empty($row)) {
            $keyboard_rows[] = $row; 
        }
    }
 
    $pagination_row = buildPaginationRow('selectCityPage', $offset, $limit, $total, ['p_idx' => $province_index]); 
    if (!empty($pagination_row)) {
        $keyboard_rows[] = $pagination_row; 
    }
    
    $keyboard_rows[] = [['text' => '🔙 بازگشت (انتخاب استان)', 'callback_data' => buildCallbackData('backToProvinceSelection')]]; 
   
    return ['inline_keyboard' => $keyboard_rows]; 
}


// --- Main Menus ---

function getCustomerMainMenuKeyboard(array $user): array {
    $is_partner = false;
    if (isset($user) && ($user['is_admin'] ?? false) == false && $user['referred_by_user_id'] === null) {
        $is_partner = true;
    }
    
    $keyboard = [
        [['text' => '🛍 مشاهده فروشگاه'], ['text' => '🛒 سبد خرید']],
    ];

    if ($is_partner) {
        // منوی همکار
        $keyboard[] = [['text' => '📦 سفارشات محصول'], ['text' => '📈 سفارشات مشتریانم']];
        $keyboard[] = [['text' => '🧾 فاکتورهای آزاد'], ['text' => '💳 مدیریت کارت‌ها']];
        $keyboard[] = [['text' => '🛍️ فروشگاه من'], ['text' => '💰 نقد کردن درآمد']];
        $keyboard[] = [['text' => '🔎 جستجوی محصول']];
    } else {
        // منوی مشتریِ همکار
        $keyboard[] = [['text' => '📦 سفارشات محصول'], ['text' => '🧾 فاکتورهای آزاد']];
        $keyboard[] = [['text' => '💳 مدیریت کارت‌ها'], ['text' => '🔎 جستجوی محصول']];
    }
    
    return [
      'keyboard' => $keyboard,
      'resize_keyboard' => true
    ];
}

function getAdminMainMenuKeyboard(): array {
   return [
        'keyboard' => [
            [['text' => '➕ افزودن محصول'], ['text' => '📝 مدیریت محصولات']],
            [['text' => '🗂 مدیریت دسته‌بندی‌ها'], ['text' => '🎁 مدیریت تخفیف‌ها']],
            [['text' => '👥 مدیریت کاربران'], ['text' => '📢 پیام‌رسانی']],
            [['text' => '📋 سفارشات عادی'], ['text' => '📈 سفارشات ارجاعی']],
            [['text' => '🛎 درخواست‌های در انتظار'], ['text' => '💳 درخواست‌های تسویه']],
            [['text' => '🧾 ایجاد فاکتور آزاد'], ['text' => '⚙️ تنظیمات فروشگاه']]
        ],
        'resize_keyboard' => true
   ];
}

?>