<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "baseInfo.php";

echo "<pre>";
echo "=== ساخت جداول دیتابیس ===\n\n";

$connection = new mysqli('localhost', $dbUserName, $dbPassword, $dbName);
if($connection->connect_error){
    die("❌ خطا در اتصال: " . $connection->connect_error);  
}

echo "✅ اتصال به دیتابیس موفق\n\n";
$connection->set_charset("utf8mb4");

// لیست تمام جداول
$tables = [
    "CREATE TABLE IF NOT EXISTS `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `userid` varchar(40) NOT NULL,
      `name` varchar(100) NOT NULL,
      `username` varchar(100) NOT NULL,
      `refcode` varchar(50) NOT NULL,
      `wallet` int(11) NOT NULL DEFAULT 0,
      `date` varchar(50) NOT NULL,
      `phone` varchar(15) DEFAULT NULL,
      `refered_by` bigint(10) DEFAULT NULL,
      `step` varchar(1000) NOT NULL DEFAULT 'none',
      `freetrial` varchar(10) DEFAULT NULL,
      `isAdmin` tinyint(1) NOT NULL DEFAULT 0,
      `first_start` varchar(10) DEFAULT NULL,
      `temp` text DEFAULT NULL,
      `is_agent` int(1) NOT NULL DEFAULT 0,
      `discount_percent` int(255) NOT NULL DEFAULT 0,
      `agent_date` int(255) NOT NULL DEFAULT 0,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `server_plans` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `fileid` varchar(250) NOT NULL,
      `catid` int(11) NOT NULL,
      `server_id` int(11) NOT NULL,
      `inbound_id` int(11) NOT NULL DEFAULT 0,
      `acount` bigint(20) NOT NULL,
      `limitip` int(11) NOT NULL DEFAULT 1,
      `title` varchar(150) NOT NULL,
      `protocol` varchar(100) NOT NULL,
      `days` float NOT NULL,
      `volume` float NOT NULL,
      `type` varchar(50) NOT NULL,
      `price` int(11) NOT NULL,
      `descr` text NOT NULL,
      `pic` varchar(100) NOT NULL,
      `active` int(11) NOT NULL DEFAULT 0,
      `step` int(11) NOT NULL,
      `date` varchar(50) NOT NULL,
      `rahgozar` int(10) DEFAULT 0,
      `dest` varchar(1000) DEFAULT NULL,
      `serverNames` TEXT DEFAULT NULL,
      `spiderX` varchar(500) DEFAULT NULL,
      `flow` varchar(50) NOT NULL DEFAULT 'None',
      `custom_path` int(10) DEFAULT 1,
      `custom_port` int(255) NOT NULL DEFAULT 0,
      `custom_sni` varchar(500) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `orders_list` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `userid` varchar(30) NOT NULL,
      `token` varchar(100) NOT NULL,
      `transid` varchar(150) NOT NULL,
      `fileid` int(11) NOT NULL,
      `server_id` int(11) NOT NULL,
      `inbound_id` int(11) NOT NULL DEFAULT 0,
      `remark` varchar(100) NOT NULL,
      `protocol` varchar(20) NOT NULL,
      `expire_date` int(11) NOT NULL,
      `link` text NOT NULL,
      `amount` int(11) NOT NULL,
      `status` int(11) NOT NULL,
      `date` varchar(50) NOT NULL,
      `notif` int(11) NOT NULL DEFAULT 0,
      `rahgozar` int(10) DEFAULT 0,
      `agent_bought` int(1) NOT NULL DEFAULT 0,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `pays` (
      `id` int(255) NOT NULL AUTO_INCREMENT,
      `hash_id` varchar(1000) NOT NULL,
      `description` varchar(5000) DEFAULT NULL,
      `payid` varchar(500) DEFAULT NULL,
      `user_id` bigint(10) NOT NULL,
      `type` varchar(100) DEFAULT NULL,
      `plan_id` int(255) DEFAULT NULL,
      `volume` int(255) DEFAULT NULL,
      `day` int(255) DEFAULT NULL,
      `price` int(255) NOT NULL,
      `request_date` int(255) NOT NULL,
      `state` varchar(255) NOT NULL,
      `agent_bought` int(1) NOT NULL DEFAULT 0,
      `agent_count` int(255) NOT NULL DEFAULT 0,
      `fish_photo_id` varchar(500) DEFAULT NULL,
      `fish_type` varchar(50) DEFAULT NULL,
      `fish_caption` text DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `server_info` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(200) NOT NULL,
      `ucount` varchar(20) NOT NULL,
      `remark` varchar(100) NOT NULL,
      `flag` varchar(100) NOT NULL,
      `active` int(11) NOT NULL DEFAULT 0,
      `state` int(255) NOT NULL DEFAULT 1,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `server_config` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `panel_url` varchar(254) NOT NULL,
      `ip` text NOT NULL,
      `sni` varchar(254) NOT NULL,
      `header_type` enum('none','http') NOT NULL,
      `request_header` text NOT NULL,
      `response_header` text NOT NULL,
      `security` enum('xtls', 'tls','none') NOT NULL,
      `tlsSettings` text NOT NULL,
      `type` varchar(100) DEFAULT NULL,
      `username` varchar(100) NOT NULL,
      `password` varchar(100) NOT NULL,
      `port_type` varchar(10) DEFAULT 'auto',
      `reality` varchar(10) DEFAULT 'false',
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci",
    
    "CREATE TABLE IF NOT EXISTS `server_categories` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `server_id` varchar(20) NOT NULL,
      `title` varchar(50) NOT NULL,
      `parent` int(11) NOT NULL DEFAULT 0,
      `step` int(11) NOT NULL,
      `active` int(11) NOT NULL DEFAULT 0,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `setting` (
      `id` int(255) NOT NULL AUTO_INCREMENT,
      `type` varchar(500) NOT NULL,
      `value` text NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `chats` (
      `id` int(255) NOT NULL AUTO_INCREMENT,
      `user_id` bigint(10) NOT NULL,
      `create_date` int(255) NOT NULL,
      `title` varchar(1000) NOT NULL,
      `category` varchar(1000) NOT NULL,
      `state` int(5) NOT NULL,
      `rate` int(5) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `chats_info` (
      `id` int(255) NOT NULL AUTO_INCREMENT,
      `chat_id` int(255) NOT NULL,
      `sent_date` int(255) NOT NULL,
      `msg_type` varchar(50) DEFAULT NULL,
      `text` varchar(2000) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `discounts` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `code` varchar(50) NOT NULL UNIQUE,
      `type` ENUM('percent', 'fixed') NOT NULL DEFAULT 'percent',
      `amount` int(11) NOT NULL,
      `max_use` int(11) DEFAULT 0 COMMENT '0 = نامحدود',
      `used_count` int(11) DEFAULT 0,
      `expire_date` int(11) DEFAULT NULL,
      `status` ENUM('active', 'inactive') DEFAULT 'active',
      `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      INDEX `idx_code` (`code`),
      INDEX `idx_status` (`status`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
    
    "CREATE TABLE IF NOT EXISTS `discount_usage` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_id` bigint(20) NOT NULL,
      `discount_id` int(11) NOT NULL,
      `plan_id` int(11) NOT NULL,
      `discount_amount` int(11) NOT NULL,
      `used_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      INDEX `idx_user_discount` (`user_id`, `discount_id`),
      INDEX `idx_discount` (`discount_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
    
    "CREATE TABLE IF NOT EXISTS `increase_day` (
      `id` int(255) NOT NULL AUTO_INCREMENT,
      `volume` float NOT NULL,
      `price` int(255) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `increase_plan` (
      `id` int(255) NOT NULL AUTO_INCREMENT,
      `volume` float NOT NULL,
      `price` int(255) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `increase_order` (
      `id` int(255) NOT NULL AUTO_INCREMENT,
      `userid` varchar(30) NOT NULL,
      `server_id` int(255) NOT NULL,
      `inbound_id` int(255) NOT NULL,
      `remark` varchar(100) NOT NULL,
      `amount` int(255) NOT NULL,
      `date` varchar(30) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `needed_sofwares` (
      `id` int(255) NOT NULL AUTO_INCREMENT,
      `title` varchar(100) NOT NULL,
      `link` varchar(250) NOT NULL,
      `status` int(11) NOT NULL DEFAULT 1,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `trading_plans_status` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `plan_key` varchar(50) NOT NULL,
      `enabled` tinyint(1) NOT NULL DEFAULT 1,
      `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `plan_key` (`plan_key`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
    
    "CREATE TABLE IF NOT EXISTS `vip_plans_status` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `plan_key` varchar(50) NOT NULL,
      `enabled` tinyint(1) NOT NULL DEFAULT 1,
      `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `plan_key` (`plan_key`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci"
];

echo "در حال ساخت جداول...\n\n";

$success = 0;
$failed = 0;

foreach($tables as $index => $sql) {
    // استخراج نام جدول
    preg_match('/CREATE TABLE.*?`(\w+)`/', $sql, $matches);
    $tableName = $matches[1] ?? "جدول " . ($index + 1);
    
    if($connection->query($sql)) {
        echo "✅ جدول $tableName ساخته شد\n";
        $success++;
    } else {
        echo "❌ خطا در ساخت $tableName: " . $connection->error . "\n";
        $failed++;
    }
}

echo "\n" . str_repeat("=", 50) . "\n";
echo "خلاصه:\n";
echo "✅ موفق: $success جدول\n";
echo "❌ ناموفق: $failed جدول\n";

if($failed == 0) {
    echo "\n🎉 تمام جداول با موفقیت ساخته شدند!\n\n";
    echo "مرحله بعدی:\n";
    echo "1. Webhook را دوباره تنظیم کنید:\n";
    echo "   <a href='setWebhook.php'>setWebhook.php</a>\n\n";
    echo "2. ربات را تست کنید:\n";
    echo "   در تلگرام /start بزنید\n";
} else {
    echo "\n⚠️ برخی جداول ساخته نشدند!\n";
    echo "لطفا خطاها را بررسی کنید.\n";
}

// درج داده‌های اولیه
echo "\n" . str_repeat("=", 50) . "\n";
echo "درج داده‌های اولیه...\n\n";

// چک کردن و درج تنظیمات
$connection->query("INSERT IGNORE INTO `setting` (`id`, `type`, `value`) VALUES
(1, 'TICKETS_CATEGORY', 'شکایت'),
(2, 'INVITE_BANNER_AMOUNT', '3000'),
(4, 'PAYMENT_KEYS', '{\"nowpayment\":\"\",\"zarinpal\":\"\",\"nextpay\":\"\",\"bankAccount\":\"\",\"holderName\":\"\"}'),
(5, 'BOT_STATES', '{\"requirePhone\":\"off\",\"requireIranPhone\":\"off\",\"sellState\":\"on\",\"botState\":\"on\",\"searchState\":\"on\",\"rewaredTime\":\"3\",\"cartToCartState\":\"on\",\"nextpay\":\"off\",\"zarinpal\":\"off\",\"nowPaymentWallet\":\"off\",\"nowPaymentOther\":\"off\",\"walletState\":\"on\",\"rewardChannel\":\"\",\"lockChannel\":\"\",\"changeProtocolState\":\"on\",\"renewAccountState\":\"on\",\"switchLocationState\":\"on\",\"increaseTimeState\":\"on\",\"increaseVolumeState\":\"on\",\"gbPrice\":\"1000\",\"dayPrice\":\"500\",\"subLinkState\":\"on\",\"plandelkhahState\":\"off\",\"weSwapState\":\"off\",\"agencyState\":\"off\",\"testAccount\":\"off\",\"sharedExistence\":\"on\",\"individualExistence\":\"off\",\"renewConfigLinkState\":\"on\",\"updateConfigLinkState\":\"on\",\"remark\":\"digits\"}')");

echo "✅ تنظیمات پیش‌فرض درج شد\n";

// درج نرم‌افزارهای پیش‌فرض
$connection->query("INSERT IGNORE INTO `needed_sofwares` (`id`, `title`, `link`, `status`) VALUES
(1, 'ios fair-vpn', 'https://apps.apple.com/us/app/fair-vpn/id1533873488', 1),
(2, 'ios napsternetv', 'https://apps.apple.com/us/app/napsternetv/id1629465476', 1),
(3, 'ios oneclick', 'https://apps.apple.com/us/app/id1545555197', 1),
(4, 'android v2rayng', 'https://play.google.com/store/apps/details?id=com.v2ray.ang', 1),
(5, 'android sagernet', 'https://play.google.com/store/apps/details?id=io.nekohasekai.sagernet', 1),
(6, 'windows v2rayng', 'https://github.com/2dust/v2rayN/releases', 1)");

echo "✅ لیست نرم‌افزارها درج شد\n";

echo "\n</pre>";
?>
