-- ============================================================
--  Profit Shop App — Core MySQL schema + safe defaults
--  Version: 1.1.0 (Profit Shop)
--  Engine: InnoDB | Charset: utf8mb4
--
--  FRESH INSTALL
--    1. Create the database (phpMyAdmin / cPanel).
--    2. Import this file. Every table is CREATE TABLE IF NOT EXISTS,
--       and every default row uses INSERT IGNORE / a guard.
--    3. Run migrate.php to apply newer schema changes.
--    4. Run seed_demo.php --yes to load demo earning/shop catalog.
--
--  EXISTING INSTALL
--    Do not re-import this file to upgrade. Run migrate.php instead; it
--    only adds missing tables/columns/indexes/foreign keys.
--
--  This file contains NO demo users, wallets, tasks, products, orders
--  or financial records. It never deletes or overwrites live rows.
-- ============================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ------------------------------------------------------------
-- 1. ADMINS (admin panel login)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `admins` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `email` VARCHAR(150) NOT NULL,
  `password_hash` VARCHAR(255) NOT NULL,
  `role` ENUM('super_admin','manager','support') NOT NULL DEFAULT 'super_admin',
  `status` ENUM('active','banned') NOT NULL DEFAULT 'active',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_admins_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 2. APP SETTINGS (key-value, editable from admin panel)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `app_settings` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `skey` VARCHAR(100) NOT NULL,
  `svalue` TEXT NULL,
  `description` VARCHAR(255) NULL,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_settings_key` (`skey`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 3. PAYMENT METHODS (bKash / Nagad / Rocket / Bank / Auto gateway)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `payment_methods` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `method_key` VARCHAR(30) NOT NULL DEFAULT '' COMMENT 'bkash, nagad, rocket, upay — stable API/admin key',
  `name` VARCHAR(100) NOT NULL,
  `type` ENUM('manual','auto') NOT NULL DEFAULT 'manual',
  `account_type` ENUM('Personal','Agent','Merchant') NOT NULL DEFAULT 'Personal',
  `account_number` VARCHAR(100) NULL,
  `account_name` VARCHAR(100) NULL,
  `instructions` TEXT NULL,
  `qr_image_url` VARCHAR(255) NULL,
  `logo` VARCHAR(255) NULL,
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  `min_deposit` DECIMAL(10,2) NOT NULL DEFAULT 50.00 COMMENT 'Floor enforced by deposits/create',
  `max_deposit` DECIMAL(10,2) NOT NULL DEFAULT 25000.00 COMMENT 'Ceiling enforced by deposits/create',
  `sort_order` INT NOT NULL DEFAULT 0,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_method_key` (`method_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 4. VERIFICATION PACKAGES (e.g. Gold Package)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `verification_packages` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `fee` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `duration_days` INT NOT NULL DEFAULT 365,
  `features` TEXT NULL COMMENT 'JSON: list of unlocked features',
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 5. MEMBERSHIP PLANS (v2 tiers: Free/Bronze/Silver/Gold/Platinum)
--    Defined BEFORE users so the users.package_id FK always resolves,
--    even on hosts that validate references at CREATE TABLE time.
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `membership_plans` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `slug` VARCHAR(50) NOT NULL,
  `name` VARCHAR(100) NOT NULL,
  `price` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `daily_task_limit` INT NOT NULL DEFAULT 2,
  `mlm_levels_unlocked` INT NOT NULL DEFAULT 1,
  `direct_commission_pct` DECIMAL(5,2) NOT NULL DEFAULT 0.00 COMMENT 'Level-1 rate (display)',
  `cashback_pct` DECIMAL(5,2) NOT NULL DEFAULT 0.00,
  `min_withdraw` DECIMAL(12,2) NOT NULL DEFAULT 200.00,
  `validity_days` INT NOT NULL DEFAULT 0 COMMENT '0 = lifetime access',
  `description` TEXT NULL COMMENT 'Short plan pitch shown in the app',
  `badge_color` VARCHAR(20) NOT NULL DEFAULT '#9E9E9E',
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_plan_slug` (`slug`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `membership_level_rates` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `plan_id` INT UNSIGNED NOT NULL,
  `level` INT UNSIGNED NOT NULL COMMENT '1..10',
  `commission_pct` DECIMAL(5,2) NOT NULL DEFAULT 0.00,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_plan_level` (`plan_id`,`level`),
  CONSTRAINT `fk_mlr_plan` FOREIGN KEY (`plan_id`)
    REFERENCES `membership_plans` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- NOTE: membership_payments is defined with the transaction tables
-- below (it references users, so it must come after the users table).

-- ------------------------------------------------------------
-- 6. USERS
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `users` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `phone` VARCHAR(20) NOT NULL COMMENT 'Primary login identity',
  `email` VARCHAR(150) NULL,
  `password_hash` VARCHAR(255) NOT NULL,
  `avatar` VARCHAR(255) NULL,
  `referral_code` VARCHAR(20) NOT NULL COMMENT 'Own code to invite others',
  `referred_by` INT UNSIGNED NULL COMMENT 'FK -> users.id (upline)',
  `is_verified` TINYINT(1) NOT NULL DEFAULT 0,
  `verification_package_id` INT UNSIGNED NULL,
  `package_id` INT UNSIGNED NULL COMMENT 'FK -> membership_plans.id (v2 tiers)',
  `verified_at` DATETIME NULL,
  `membership_expiry` DATETIME NULL COMMENT 'NULL = lifetime; set from plan validity_days on upgrade',
  `status` ENUM('active','banned','pending','deleted') NOT NULL DEFAULT 'pending',
  `operator` VARCHAR(50) NULL COMMENT 'Auto-detected or manual mobile operator',
  `device_id` VARCHAR(64) NULL COMMENT 'Anti-fraud: bound Android SSAID (one device, one account)',
  `fcm_token` VARCHAR(512) NULL COMMENT 'Firebase Cloud Messaging registration token',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_users_phone` (`phone`),
  UNIQUE KEY `uq_users_email` (`email`),
  UNIQUE KEY `uq_users_referral_code` (`referral_code`),
  UNIQUE KEY `uq_users_device_id` (`device_id`),
  KEY `idx_users_referred_by` (`referred_by`),
  KEY `idx_users_status` (`status`),
  KEY `idx_users_verified` (`is_verified`),
  CONSTRAINT `fk_users_referred_by` FOREIGN KEY (`referred_by`)
    REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `fk_users_ver_package` FOREIGN KEY (`verification_package_id`)
    REFERENCES `verification_packages` (`id`) ON DELETE SET NULL,
  CONSTRAINT `fk_users_package` FOREIGN KEY (`package_id`)
    REFERENCES `membership_plans` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 6. OTPS (registration / login / password reset)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `otps` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `phone` VARCHAR(20) NULL,
  `email` VARCHAR(150) NULL,
  `otp_code` VARCHAR(10) NOT NULL,
  `purpose` ENUM('register','login','reset','verify_payment') NOT NULL DEFAULT 'register',
  `is_used` TINYINT(1) NOT NULL DEFAULT 0,
  `expires_at` DATETIME NOT NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_otps_phone` (`phone`),
  KEY `idx_otps_email` (`email`),
  KEY `idx_otps_code` (`otp_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 7. VERIFICATION PAYMENTS (profile verification fee)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `verification_payments` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `package_id` INT UNSIGNED NOT NULL,
  `amount` DECIMAL(12,2) NOT NULL,
  `payment_method_id` INT UNSIGNED NULL,
  `txn_id` VARCHAR(100) NULL,
  `screenshot` VARCHAR(255) NULL,
  `status` ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `admin_note` VARCHAR(255) NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_vp_user` (`user_id`),
  KEY `idx_vp_status` (`status`),
  CONSTRAINT `fk_vp_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_vp_package` FOREIGN KEY (`package_id`)
    REFERENCES `verification_packages` (`id`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 8. WALLETS (one row per user)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `wallets` (
  `user_id` INT UNSIGNED NOT NULL,
  `balance` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `total_earned` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `total_withdrawn` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`),
  CONSTRAINT `fk_wallets_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 9. WALLET TRANSACTIONS (immutable ledger)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `wallet_transactions` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `type` ENUM('credit','debit') NOT NULL,
  `source` VARCHAR(50) NOT NULL COMMENT 'task, referral, cashback, recharge, purchase, deposit, withdraw, bonus, verification_fee, adjustment',
  `amount` DECIMAL(12,2) NOT NULL,
  `balance_after` DECIMAL(12,2) NOT NULL,
  `reference_id` VARCHAR(100) NULL,
  `note` VARCHAR(255) NULL,
  `status` ENUM('pending','completed','failed') NOT NULL DEFAULT 'completed',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_wt_user` (`user_id`),
  KEY `idx_wt_source` (`source`),
  KEY `idx_wt_created` (`created_at`),
  CONSTRAINT `fk_wt_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 10. DEPOSITS (add fund requests)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `deposits` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `payment_method_id` INT UNSIGNED NULL,
  `method` VARCHAR(50) NULL COMMENT 'Denormalized method key (bkash/nagad/...) for direct display',
  `amount` DECIMAL(12,2) NOT NULL,
  `txn_id` VARCHAR(100) NULL COMMENT 'Legacy id (mirrors trx_id; nullable so inserts never fail)',
  `trx_id` VARCHAR(100) NULL COMMENT 'Canonical transaction id (mirrors txn_id)',
  `screenshot` VARCHAR(255) NULL,
  `screenshot_url` VARCHAR(500) NULL COMMENT 'Mirror of screenshot (extended URL length)',
  `sender_account` VARCHAR(50) NULL COMMENT 'Number the user paid from',
  `sender_number` VARCHAR(50) NULL COMMENT 'Mirror of sender_account',
  `status` ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `admin_note` VARCHAR(255) NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_dep_txn` (`txn_id`),
  UNIQUE KEY `uq_dep_trx` (`trx_id`),
  KEY `idx_dep_user` (`user_id`),
  KEY `idx_dep_status` (`status`),
  KEY `idx_dep_user_status` (`user_id`,`status`),
  CONSTRAINT `fk_dep_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 11. WITHDRAWALS
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `withdrawals` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `method` VARCHAR(50) NOT NULL COMMENT 'bkash, nagad, rocket, bank',
  `account_number` VARCHAR(50) NOT NULL,
  `account_type` VARCHAR(20) NULL COMMENT 'Personal / Agent (user-declared)',
  `amount` DECIMAL(12,2) NOT NULL,
  `charge` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `net_amount` DECIMAL(12,2) NOT NULL,
  `payout_trx_id` VARCHAR(100) NULL COMMENT 'Admin payout transaction id (set on approve)',
  `status` ENUM('pending','approved','rejected','paid') NOT NULL DEFAULT 'pending',
  `admin_note` VARCHAR(255) NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_wd_user` (`user_id`),
  KEY `idx_wd_status` (`status`),
  CONSTRAINT `fk_wd_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 12. MLM LEVELS (commission % per level, editable in admin)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `mlm_levels` (
  `level` INT UNSIGNED NOT NULL COMMENT '1..20',
  `name` VARCHAR(50) NULL COMMENT 'Display label, e.g. Level 1',
  `commission_percent` DECIMAL(5,2) NOT NULL DEFAULT 0.00,
  `commission_fixed` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT 'Used if percent is 0',
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`level`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 13. REFERRAL EARNINGS (team income ledger)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `referral_earnings` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `earner_user_id` INT UNSIGNED NOT NULL COMMENT 'Who receives commission',
  `from_user_id` INT UNSIGNED NOT NULL COMMENT 'Whose action triggered it',
  `level` INT UNSIGNED NOT NULL,
  `source_type` VARCHAR(50) NOT NULL COMMENT 'verification_fee, task, purchase, deposit',
  `source_id` INT UNSIGNED NULL,
  `amount` DECIMAL(12,2) NOT NULL,
  `status` ENUM('paid','pending','credited','cancelled') NOT NULL DEFAULT 'credited'
    COMMENT "'paid' kept for legacy rows; new rows use credited/pending/cancelled",
  `release_at` DATETIME NULL DEFAULT NULL COMMENT 'When a pending commission matures',
  `credited_at` DATETIME NULL DEFAULT NULL COMMENT 'When the wallet was credited',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_re_earner` (`earner_user_id`),
  KEY `idx_re_from` (`from_user_id`),
  KEY `idx_re_level` (`level`),
  KEY `idx_re_earner_status_release` (`earner_user_id`,`status`,`release_at`),
  CONSTRAINT `fk_re_earner` FOREIGN KEY (`earner_user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_re_from` FOREIGN KEY (`from_user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 13b. REFERRAL COMMISSIONS (standardized MLM ledger mirror)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `referral_commissions` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `beneficiary_user_id` INT UNSIGNED NOT NULL COMMENT 'Upline earner (mirrors referral_earnings.earner_user_id)',
  `source_user_id` INT UNSIGNED NOT NULL COMMENT 'Downline trigger (mirrors from_user_id)',
  `level` INT UNSIGNED NOT NULL,
  `source_event` VARCHAR(50) NOT NULL COMMENT 'task, plan_upgrade, deposit, ...',
  `source_amount` DECIMAL(10,2) NULL COMMENT 'Base amount the commission was calculated from',
  `commission_amount` DECIMAL(10,2) NOT NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_rc_beneficiary` (`beneficiary_user_id`),
  KEY `idx_rc_source` (`source_user_id`),
  KEY `idx_rc_level` (`level`),
  CONSTRAINT `fk_rc_beneficiary` FOREIGN KEY (`beneficiary_user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_rc_source` FOREIGN KEY (`source_user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 14. TASK CATEGORIES
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `task_categories` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `slug` VARCHAR(100) NOT NULL COMMENT 'ads, quiz, typing, marketing, microjob, jobpost, course, digital_service, gmail, instagram, whatsapp, telegram',
  `icon` VARCHAR(255) NULL,
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  `sort_order` INT NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_taskcat_slug` (`slug`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 15. TASKS (all earning modules, dynamic via admin)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tasks` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `category_id` INT UNSIGNED NOT NULL,
  `title` VARCHAR(200) NOT NULL,
  `description` TEXT NULL,
  `reward` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `instructions` TEXT NULL COMMENT 'Step-by-step guide shown in the app',
  `action_url` VARCHAR(500) NULL COMMENT 'Ad link / social link / course link (YouTube, website, Telegram...)',
  `image` VARCHAR(255) NULL,
  `task_type` ENUM('visit_timer','watch_ad','quiz','screenshot','social') NOT NULL DEFAULT 'visit_timer' COMMENT 'Guided completion method driving the app UI',
  `timer_seconds` INT NOT NULL DEFAULT 20 COMMENT 'Countdown requirement for visit_timer tasks',
  `required_plan_id` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '0 = all users; else minimum membership_plans.id required',
  `required_proof` ENUM('none','screenshot','text','both') NOT NULL DEFAULT 'screenshot',
  `daily_limit` INT NOT NULL DEFAULT 1 COMMENT 'Max completions per user per day',
  `total_limit` INT NOT NULL DEFAULT 0 COMMENT '0 = unlimited overall',
  `requires_verification` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1 = only verified users',
  `start_date` DATE NULL,
  `end_date` DATE NULL,
  `status` ENUM('active','paused','expired') NOT NULL DEFAULT 'active',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_tasks_cat` (`category_id`),
  KEY `idx_tasks_status` (`status`),
  CONSTRAINT `fk_tasks_cat` FOREIGN KEY (`category_id`)
    REFERENCES `task_categories` (`id`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 16. QUIZ QUESTIONS (for quiz-type tasks).
--     Canonical store: JSON `options` (4 entries = A..D) + zero-based
--     `correct_index`. The admin builder + API accept A/B/C/D keys and
--     map them onto this shape, so one table serves every client.
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `quiz_questions` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `task_id` INT UNSIGNED NOT NULL,
  `question` VARCHAR(500) NOT NULL,
  `options` TEXT NOT NULL COMMENT 'JSON array of 4 options (A, B, C, D)',
  `correct_index` TINYINT NOT NULL DEFAULT 0 COMMENT '0=A, 1=B, 2=C, 3=D',
  PRIMARY KEY (`id`),
  KEY `idx_qq_task` (`task_id`),
  CONSTRAINT `fk_qq_task` FOREIGN KEY (`task_id`)
    REFERENCES `tasks` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 17. TASK SUBMISSIONS (user proof + review)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `task_submissions` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `task_id` INT UNSIGNED NOT NULL,
  `status` ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `proof_text` TEXT NULL,
  `proof_image` VARCHAR(255) NULL,
  `elapsed_seconds` INT UNSIGNED NULL COMMENT 'Visit-timer audit: seconds the user spent before submitting',
  `reward_earned` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `admin_note` VARCHAR(255) NULL,
  `rejection_reason` VARCHAR(255) NULL,
  `submitted_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `reviewed_at` DATETIME NULL,
  PRIMARY KEY (`id`),
  KEY `idx_ts_user` (`user_id`),
  KEY `idx_ts_task` (`task_id`),
  KEY `idx_ts_status` (`status`),
  CONSTRAINT `fk_ts_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_ts_task` FOREIGN KEY (`task_id`)
    REFERENCES `tasks` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 18. QUICK EARN — INTERACTIVE QUIZZES + CAPTCHA TYPING
--      Standalone engines (Home > Easy Earning tiles). Separate from
--      the guided task quizzes in `tasks` / `quiz_questions`.
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `quizzes` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `question` TEXT NOT NULL,
  `option_a` VARCHAR(255) NOT NULL,
  `option_b` VARCHAR(255) NOT NULL,
  `option_c` VARCHAR(255) NOT NULL,
  `option_d` VARCHAR(255) NOT NULL,
  `correct_option` ENUM('a','b','c','d') NOT NULL,
  `reward_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.50,
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_quizzes_active` (`is_active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `user_quiz_attempts` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `quiz_id` INT UNSIGNED NOT NULL,
  `selected_option` ENUM('a','b','c','d') NOT NULL,
  `is_correct` TINYINT(1) NOT NULL DEFAULT 0,
  `earned_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_uqa_user_date` (`user_id`,`created_at`),
  KEY `idx_uqa_quiz` (`quiz_id`),
  CONSTRAINT `fk_uqa_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_uqa_quiz` FOREIGN KEY (`quiz_id`)
    REFERENCES `quizzes` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `typing_logs` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `captcha_code` VARCHAR(50) NOT NULL,
  `reward_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.30,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_typing_user_date` (`user_id`,`created_at`),
  CONSTRAINT `fk_typing_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Internal challenge store: keeps the issued captcha server-side so a
-- stateless JWT API can verify it, enforce expiry/retry limits and the
-- 4-second human delay. Never exposed to clients beyond the token.
CREATE TABLE IF NOT EXISTS `typing_challenges` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `token` VARCHAR(64) NOT NULL,
  `captcha_code` VARCHAR(50) NOT NULL,
  `reward_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.30,
  `attempts` TINYINT UNSIGNED NOT NULL DEFAULT 0,
  `used` TINYINT(1) NOT NULL DEFAULT 0,
  `expires_at` DATETIME NOT NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_typing_token` (`token`),
  KEY `idx_typing_challenge_user` (`user_id`,`used`,`created_at`),
  CONSTRAINT `fk_typing_challenge_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 18c. REWARDED VIDEO AD VIEWS (Phase 3 earning engine)
-- One row per completed rewarded video. The API locks the user row,
-- re-counts today's views and re-checks the cooldown before inserting
-- here, so parallel claims cannot exceed the daily quota.
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `ad_views` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `ad_network` VARCHAR(50) NOT NULL DEFAULT 'admob' COMMENT 'admob | startio | unity',
  `reward_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.25,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_ad_views_user_created` (`user_id`,`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 18d. WEEKLY LEADERBOARD PRIZE HISTORY (Phase 3 payouts)
-- The unique key is the final duplicate-payout guard: even if two
-- admins/cron runs race, only one row can exist per week + rank.
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `leaderboard_prize_history` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `period_type` ENUM('weekly','monthly') NOT NULL DEFAULT 'weekly',
  `rank_position` INT NOT NULL COMMENT '1-based board rank',
  `prize_amount` DECIMAL(10,2) NOT NULL,
  `period_label` VARCHAR(50) NOT NULL COMMENT 'ISO week label, e.g. 2026-W42',
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_lph_user` (`user_id`),
  KEY `idx_lph_period` (`period_label`),
  UNIQUE KEY `uq_lph_period_rank` (`period_label`,`period_type`,`rank_position`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 19. OPERATORS + DRIVE OFFERS (recharge)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `operators` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `code` VARCHAR(50) NOT NULL COMMENT 'grameenphone, banglalink, robi, teletalk',
  `prefixes` VARCHAR(255) NULL COMMENT 'CSV: 017,013,... for auto-detect',
  `logo` VARCHAR(255) NULL,
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_op_code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `drive_offers` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `operator_id` INT UNSIGNED NOT NULL,
  `title` VARCHAR(200) NOT NULL,
  `offer_type` ENUM('airtime','data','minute','combo') NOT NULL DEFAULT 'data',
  `price` DECIMAL(12,2) NOT NULL COMMENT 'User pays',
  `mrp` DECIMAL(12,2) NULL COMMENT 'Regular price for strike-through UI',
  `cashback` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `validity` VARCHAR(50) NULL COMMENT 'e.g. 30 days',
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_do_op` (`operator_id`),
  CONSTRAINT `fk_do_op` FOREIGN KEY (`operator_id`)
    REFERENCES `operators` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `recharge_orders` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `phone_number` VARCHAR(20) NOT NULL,
  `operator_id` INT UNSIGNED NULL,
  `offer_id` INT UNSIGNED NULL COMMENT 'NULL = custom airtime amount',
  `amount_paid` DECIMAL(12,2) NOT NULL,
  `status` ENUM('pending','completed','failed') NOT NULL DEFAULT 'pending',
  `txn_id` VARCHAR(100) NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_ro_user` (`user_id`),
  KEY `idx_ro_status` (`status`),
  CONSTRAINT `fk_ro_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 20. SHOP: CATEGORIES, PRODUCTS, ORDERS
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `product_categories` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `slug` VARCHAR(100) NOT NULL,
  `image` VARCHAR(255) NULL,
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_pcat_slug` (`slug`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `products` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `vendor_id` INT UNSIGNED NULL,
  `category_id` INT UNSIGNED NOT NULL,
  `name` VARCHAR(200) NOT NULL,
  `title` VARCHAR(200) NULL COMMENT 'Alias of name for vendor API compat (mirrors name)',
  `description` TEXT NULL,
  `price` DECIMAL(10,2) NOT NULL,
  `mrp` DECIMAL(12,2) NULL,
  `cashback` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT 'Buyer earning',
  `stock` INT NOT NULL DEFAULT 10,
  `images` TEXT NULL COMMENT 'JSON array of image URLs',
  `image_url` VARCHAR(500) NULL COMMENT 'Primary image URL for vendor API compat (mirrors images[0])',
  `is_popular` TINYINT(1) NOT NULL DEFAULT 0,
  `product_type` ENUM('physical','virtual') NOT NULL DEFAULT 'physical' COMMENT 'physical=hand delivery, virtual=gift card/digital code',
  `delivery_charge` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '0 for virtual products',
  `status` ENUM('active','inactive','out_of_stock') NOT NULL DEFAULT 'active',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_prod_cat` (`category_id`),
  KEY `idx_prod_popular` (`is_popular`),
  KEY `idx_prod_status` (`status`),
  KEY `idx_prod_vendor` (`vendor_id`),
  CONSTRAINT `fk_prod_cat` FOREIGN KEY (`category_id`)
    REFERENCES `product_categories` (`id`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `orders` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `order_code` VARCHAR(30) NOT NULL,
  `total_amount` DECIMAL(12,2) NOT NULL,
  `cashback_earned` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `status` ENUM('pending','processing','confirmed','shipped','delivered','cancelled') NOT NULL DEFAULT 'pending',
  `payment_method` VARCHAR(50) NOT NULL DEFAULT 'wallet',
  `address` VARCHAR(500) NULL,
  `phone` VARCHAR(20) NULL,
  `delivery_info` VARCHAR(500) NULL COMMENT 'address (physical) or email/whatsapp (virtual)',
  `delivery_total` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT 'delivery charges debited at order time',
  `courier_name` VARCHAR(100) NULL COMMENT 'Fulfillment courier (Steadfast, Pathao, RedX, ...)',
  `tracking_code` VARCHAR(150) NULL COMMENT 'Consignment / tracking number given to the customer',
  `fulfillment_note` TEXT NULL COMMENT 'Digital code (virtual) or courier remarks, visible to customer',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_orders_code` (`order_code`),
  KEY `idx_orders_user` (`user_id`),
  KEY `idx_orders_status` (`status`),
  CONSTRAINT `fk_orders_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `order_items` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `order_id` INT UNSIGNED NOT NULL,
  `vendor_id` INT UNSIGNED NULL COMMENT 'NULL = platform stock; vendor rows reference vendors.id (strict per-vendor fulfillment)',
  `product_id` INT UNSIGNED NOT NULL,
  `qty` INT NOT NULL DEFAULT 1,
  `quantity` INT NULL COMMENT 'Mirror of qty (vendor order API canonical)',
  `price` DECIMAL(12,2) NOT NULL,
  `unit_price` DECIMAL(10,2) NULL COMMENT 'Mirror of price (vendor order API canonical)',
  `cashback` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `delivery_charge` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Line delivery total (unit delivery x qty; 0 for virtual)',
  `total_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT 'qty x unit_price + delivery_charge (vendor payout base)',
  `status` ENUM('pending','processing','shipped','delivered','cancelled') NOT NULL DEFAULT 'pending' COMMENT 'Per-item vendor fulfillment state',
  `customer_name` VARCHAR(255) NULL,
  `customer_phone` VARCHAR(50) NULL,
  `shipping_address` TEXT NULL,
  `fulfillment_note` TEXT NULL COMMENT 'Tracking number (physical) or digital code (virtual)',
  `is_payout_credited` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '1 = vendor wallet already credited for this line',
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_oi_order` (`order_id`),
  KEY `idx_oi_vendor` (`vendor_id`),
  KEY `idx_oi_status` (`status`),
  CONSTRAINT `fk_oi_order` FOREIGN KEY (`order_id`)
    REFERENCES `orders` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_oi_product` FOREIGN KEY (`product_id`)
    REFERENCES `products` (`id`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 21. VENDORS (apply + approval + fee)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `vendors` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `shop_name` VARCHAR(150) NOT NULL,
  `shop_description` TEXT NULL COMMENT 'Vendor shop description (simplified fee-based flow)',
  `phone` VARCHAR(20) NULL COMMENT 'Vendor contact phone (simplified flow)',
  `logo_url` VARCHAR(500) NULL COMMENT 'Vendor logo/image URL (optional)',
  `address` VARCHAR(500) NULL COMMENT 'Legacy KYC shop address (nullable for simplified flow)',
  `district` VARCHAR(100) NULL COMMENT 'Vendor district / store location',
  `trade_license_image` VARCHAR(500) NULL COMMENT 'KYC trade license (file path, URL or base64-stored path)',
  `nid_front` VARCHAR(500) NULL COMMENT 'KYC NID front (file path, URL or base64-stored path)',
  `nid_back` VARCHAR(500) NULL COMMENT 'KYC NID back (file path, URL or base64-stored path)',
  `application_fee` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT 'Legacy column; mirrors fee_paid',
  `fee_paid` DECIMAL(10,2) NOT NULL DEFAULT 500.00 COMMENT 'Fee-based application amount (mirrors application_fee)',
  `payment_txn_id` VARCHAR(100) NULL,
  `status` ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `admin_note` VARCHAR(255) NULL COMMENT 'Legacy admin note; mirrors rejection_reason when rejected',
  `rejection_reason` TEXT NULL COMMENT 'Rejection reason (mirrors admin_note when rejected)',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_vendors_user` (`user_id`),
  KEY `idx_vendors_user` (`user_id`),
  KEY `idx_vendors_status` (`status`),
  CONSTRAINT `fk_vendors_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Add FK from products.vendor_id now that vendors exists.
-- Guarded with INFORMATION_SCHEMA so re-importing this file never fails on
-- an existing constraint or on a legacy table that lacks the column.
-- migrate.php performs the same check before adding the FK.
SET @fk_prod_vendor_col := (
  SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE()
     AND TABLE_NAME = 'products'
     AND COLUMN_NAME = 'vendor_id'
);
SET @fk_prod_vendor_exists := (
  SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS
   WHERE CONSTRAINT_SCHEMA = DATABASE()
     AND TABLE_NAME = 'products'
     AND CONSTRAINT_NAME = 'fk_prod_vendor'
     AND CONSTRAINT_TYPE = 'FOREIGN KEY'
);
SET @sql_fk_prod_vendor := IF(
  @fk_prod_vendor_col = 1 AND @fk_prod_vendor_exists = 0,
  'ALTER TABLE `products` ADD CONSTRAINT `fk_prod_vendor` FOREIGN KEY (`vendor_id`) REFERENCES `vendors` (`id`) ON DELETE SET NULL',
  'SELECT 1'
);
PREPARE stmt_fk_prod_vendor FROM @sql_fk_prod_vendor;
EXECUTE stmt_fk_prod_vendor;
DEALLOCATE PREPARE stmt_fk_prod_vendor;

-- ------------------------------------------------------------
-- 22. AGENCIES
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `agencies` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `owner_user_id` INT UNSIGNED NOT NULL,
  `name` VARCHAR(150) NOT NULL,
  `description` TEXT NULL,
  `logo` VARCHAR(255) NULL,
  `cover` VARCHAR(255) NULL,
  `followers_required` INT NOT NULL DEFAULT 10000,
  `status` ENUM('pending','approved','suspended','rejected') NOT NULL DEFAULT 'pending',
  `admin_note` VARCHAR(255) NULL COMMENT 'Reject/suspend reason shown to the owner',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_ag_owner` (`owner_user_id`),
  KEY `idx_ag_status` (`status`),
  CONSTRAINT `fk_ag_owner` FOREIGN KEY (`owner_user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `agency_posts` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `agency_id` INT UNSIGNED NOT NULL,
  `user_id` INT UNSIGNED NOT NULL COMMENT 'Author (agency owner/admin)',
  `title` VARCHAR(200) NULL COMMENT 'Campaign title (new flow; legacy rows use content)',
  `description` TEXT NULL COMMENT 'Campaign description',
  `action_url` VARCHAR(500) NULL COMMENT 'Campaign target URL',
  `content` TEXT NOT NULL,
  `image` VARCHAR(255) NULL,
  `image_url` VARCHAR(500) NULL COMMENT 'Direct banner link (new campaign flow)',
  `likes_count` INT NOT NULL DEFAULT 0,
  `total_budget` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Wallet-funded budget',
  `reward_per_action` DECIMAL(10,2) NOT NULL DEFAULT 0.00,
  `spent_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Paid out to completers',
  `timer_seconds` INT NOT NULL DEFAULT 20 COMMENT 'Required visit length for earners',
  `daily_limit` INT NOT NULL DEFAULT 0 COMMENT 'Traffic pacing: max completions per day (0 = unlimited)',
  `frequency_cap` ENUM('once','daily') NOT NULL DEFAULT 'once' COMMENT 'once = 1x per user lifetime, daily = 1x per 24h',
  `status` ENUM('active','paused','completed','cancelled') NOT NULL DEFAULT 'active',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_ap_agency` (`agency_id`),
  CONSTRAINT `fk_ap_agency` FOREIGN KEY (`agency_id`)
    REFERENCES `agencies` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_ap_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `agency_follows` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `agency_id` INT UNSIGNED NOT NULL,
  `user_id` INT UNSIGNED NOT NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_agfollow` (`agency_id`,`user_id`),
  CONSTRAINT `fk_af_agency` FOREIGN KEY (`agency_id`)
    REFERENCES `agencies` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_af_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `agency_campaign_completions` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `campaign_id` INT UNSIGNED NOT NULL COMMENT 'FK -> agency_posts.id',
  `user_id` INT UNSIGNED NOT NULL,
  `reward` DECIMAL(10,2) NOT NULL DEFAULT 0.00,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_campaign_user_created` (`campaign_id`,`user_id`,`created_at`),
  CONSTRAINT `fk_acc_campaign` FOREIGN KEY (`campaign_id`)
    REFERENCES `agency_posts` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_acc_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 22b. COMMUNITY MICRO JOBS (user-to-user marketplace)
--      `campaigns.user_id` is the employer/poster (users.id).
--      Budget is escrowed from the employer's wallet on create.
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `campaigns` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NULL COMMENT 'Employer/poster (users.id); NULL for admin posts',
  `is_admin_post` TINYINT(1) NOT NULL DEFAULT 0,
  `title` VARCHAR(255) NOT NULL,
  `work_link` VARCHAR(500) NULL,
  `work_limit` INT NOT NULL DEFAULT 0 COMMENT 'Total workers required',
  `completed_workers` INT NOT NULL DEFAULT 0,
  `per_work_cost` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Reward per completed work',
  `total_cost` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Escrowed/admin-funded total',
  `image_url` VARCHAR(255) NULL COMMENT 'Job thumbnail/banner',
  `description` TEXT NOT NULL,
  `status` ENUM('active','paused','completed','cancelled') NOT NULL DEFAULT 'active',
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  -- Legacy columns kept in sync for the existing proof/review flow.
  `category` VARCHAR(80) NULL COMMENT 'Legacy UI category',
  `proof_instruction` TEXT NOT NULL COMMENT 'Legacy worker proof instructions',
  `proof_type` ENUM('screenshot','text','both') NOT NULL DEFAULT 'both',
  `reward_per_worker` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT 'Legacy mirror of per_work_cost',
  `total_workers` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'Legacy mirror of work_limit',
  `total_budget` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT 'Legacy mirror of total_cost',
  `spent_amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT 'Approved worker payouts',
  PRIMARY KEY (`id`),
  KEY `idx_campaigns_user` (`user_id`),
  KEY `idx_campaigns_admin` (`is_admin_post`),
  KEY `idx_campaigns_status` (`status`),
  KEY `idx_campaigns_category` (`category`),
  CONSTRAINT `fk_campaigns_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `campaign_submissions` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `campaign_id` INT UNSIGNED NOT NULL,
  `user_id` INT UNSIGNED NOT NULL COMMENT 'Worker (users.id)',
  `proof_text` TEXT NULL,
  `proof_image` VARCHAR(255) NULL,
  `status` ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `rejection_reason` VARCHAR(255) NULL,
  `reward` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `reviewed_at` DATETIME NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_campaign_worker` (`campaign_id`,`user_id`),
  KEY `idx_cs_worker` (`user_id`),
  KEY `idx_cs_status` (`status`),
  CONSTRAINT `fk_cs_campaign` FOREIGN KEY (`campaign_id`)
    REFERENCES `campaigns` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_cs_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 23. BANNERS / SLIDERS + NOTIFICATIONS
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `banners` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(150) NOT NULL,
  `image` VARCHAR(255) NOT NULL,
  `link_type` VARCHAR(50) NULL COMMENT 'task, product, offer, url, none',
  `link_value` VARCHAR(255) NULL,
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  `sort_order` INT NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `notifications` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NULL COMMENT 'NULL means broadcast to all users, specific INT means private notification',
  `title` VARCHAR(150) NOT NULL,
  `message` TEXT NOT NULL,
  `type` ENUM('general','deposit','withdraw','bonus','system') NOT NULL DEFAULT 'general',
  `action_url` VARCHAR(255) NULL,
  `is_read` TINYINT(1) NOT NULL DEFAULT 0,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_notif_user_created` (`user_id`,`created_at`),
  KEY `idx_notif_read` (`is_read`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Per-user read receipts for broadcast notifications. Broadcast rows keep
-- is_read = 0 forever; only this table records who has opened them.
CREATE TABLE IF NOT EXISTS `user_notification_reads` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `notification_id` INT UNSIGNED NOT NULL,
  `read_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_notif_unique` (`user_id`,`notification_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------
-- 24. MEMBERSHIP PAYMENTS (upgrade ledger; plans tables are defined
--     up in section 5, before users, so all FKs resolve in order)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `membership_payments` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `plan_id` INT UNSIGNED NOT NULL,
  `amount` DECIMAL(12,2) NOT NULL,
  `payment_method_id` INT UNSIGNED NULL,
  `txn_id` VARCHAR(100) NULL,
  `status` ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `admin_note` VARCHAR(255) NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_mp_user` (`user_id`),
  KEY `idx_mp_status` (`status`),
  CONSTRAINT `fk_mp_user` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_mp_plan` FOREIGN KEY (`plan_id`)
    REFERENCES `membership_plans` (`id`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- FK checks stay OFF through all seed INSERTs below and are
-- re-enabled at the very end of this file.

-- ============================================================
-- SEED DATA
-- ============================================================

-- Default admin: email admin@modernearning.com / password admin123
-- INSERT IGNORE keeps an existing admin password/status untouched.
INSERT IGNORE INTO `admins` (`name`,`email`,`password_hash`,`role`,`status`) VALUES
('Super Admin','admin@modernearning.com','$2y$10$pcEKXMXCQd05I8bVKoIPs./KIgvYOwOUNe/P8u4LB.9d2R2nNXNDO','super_admin','active');

-- Core settings — INSERT IGNORE only, so configured live values
-- (including fcm_service_account_json) are never overwritten.
INSERT IGNORE INTO `app_settings` (`skey`,`svalue`,`description`) VALUES
('app_name','Profit Shop','App display name'),
('mlm_max_levels','10','Max referral levels to pay commission (1-20)'),
('referral_hold_days','4','Days to hold referral commission before crediting main wallet (0 = instant, e.g. 4 = 4 days)'),
('verification_required','1','1 = unverified users have locked features'),
('min_withdraw','200','Minimum withdrawal amount (uniform, all tiers)'),
('withdraw_charge_percent','5','Withdrawal charge %'),
('vendor_application_fee','500','Fee to apply as vendor'),
('vendor_registration_fee','500','Vendor registration fee (৳) — fee-based application, mirrors vendor_application_fee'),
('agency_min_followers','10000','Followers required to create agency'),
('support_whatsapp','8801712345678','Support contact'),
('support_phone','8801712345678','Support hotline'),
('app_version','1.0.0','Current app version'),
('ads_active_network','disabled','Ad network: startio | unity | admob | disabled'),
('ads_startio_app_id','','Start.io App ID'),
('ads_unity_game_id','','Unity Game ID'),
('ads_admob_app_id','','AdMob App ID (ca-app-pub-…)'),
('ads_rewarded_ad_unit_id','','Rewarded ad unit ID (active network)'),
('ads_banner_ad_unit_id','','Banner ad unit ID (active network)'),
('ads_unity_test_mode','0','Unity test ads (1 = on)'),
('ads_unity_rewarded_placement','','Unity rewarded placement ID (blank = shared unit)'),
('ads_unity_banner_placement','','Unity banner placement ID (blank = shared unit)'),
('ads_admob_rewarded_unit','','AdMob rewarded ad unit ID (blank = shared unit)'),
('ads_admob_banner_unit','','AdMob banner ad unit ID (blank = shared unit)'),
('ads_banner_enabled','1','Master toggle for banners'),
('ads_rewarded_enabled','1','Master toggle for rewarded ads on tasks'),
('telegram_url','https://t.me/','Home community link: Telegram group'),
('support_video_url','https://meet.google.com/','Home community link: support video channel'),
('facebook_url','https://facebook.com/','Home community link: Facebook group/page'),
('youtube_url','https://youtube.com/','Home community link: YouTube channel'),
('quiz_daily_limit','15','Quiz engine: max quizzes a user can answer per day'),
('quiz_default_reward','0.50','Quiz engine: fallback reward per correct answer (৳)'),
('typing_daily_limit','20','Typing engine: max captchas a user can verify per day'),
('typing_default_reward','0.30','Typing engine: reward per verified captcha (৳)'),
('typing_case_sensitive','0','Typing engine: 1 = captcha match is case-sensitive, 0 = ignore case'),
('marquee_notice_text','🎉 Profit Shop-এ স্বাগতম! প্রতিদিন টাস্ক করুন, কুইজ দিন, বন্ধু ইনভাইট করুন এবং BDT আয় করুন।','Home scrolling notice text (marquee)'),
('marquee_is_active','1','Home scrolling notice enabled (1 = on)'),
('marquee_speed','50','Home scrolling notice speed (px/second)'),
-- Phase 3: ad network aliases + weekly leaderboard prizes
('admob_rewarded_unit_id','ca-app-pub-3940256099942544/5224354917','AdMob rewarded test unit (replace with live unit)'),
('startio_app_id','','Start.io App ID for rewarded ads'),
('leaderboard_weekly_prize_pool','1000.00','Weekly leaderboard total prize pool (৳)'),
('leaderboard_rank1_prize','300.00','Weekly leaderboard rank 1 prize (৳)'),
('leaderboard_rank2_prize','200.00','Weekly leaderboard rank 2 prize (৳)'),
('leaderboard_rank3_prize','100.00','Weekly leaderboard rank 3 prize (৳)');

-- MLM: 10 levels default (admin can edit % later)
INSERT IGNORE INTO `mlm_levels` (`level`,`name`,`commission_percent`,`commission_fixed`,`is_active`) VALUES
(1,'Level 1',10.00,0.00,1),
(2,'Level 2',5.00,0.00,1),
(3,'Level 3',2.00,0.00,1),
(4,'Level 4',1.00,0.00,1),
(5,'Level 5',0.50,0.00,1),
(6,'Level 6',1.00,0.00,1),
(7,'Level 7',1.00,0.00,1),
(8,'Level 8',1.00,0.00,1),
(9,'Level 9',0.50,0.00,1),
(10,'Level 10',0.50,0.00,1);

-- Payment methods (deposit gateways; numbers edited live in Admin > Settings)
-- INSERT IGNORE preserves live account numbers and custom names.
INSERT IGNORE INTO `payment_methods` (`method_key`,`name`,`type`,`account_type`,`account_number`,`account_name`,`instructions`,`qr_image_url`,`is_active`,`sort_order`) VALUES
('bkash','bKash','manual','Personal','01XXXXXXXXX','Profit Shop','Send Money korar por TrxID niche din.',NULL,1,1),
('nagad','Nagad','manual','Personal','01XXXXXXXXX','Profit Shop','Send Money korar por TrxID niche din.',NULL,1,2),
('rocket','Rocket','manual','Personal','01XXXXXXXXX','Profit Shop','Send Money korar por TrxID niche din.',NULL,1,3),
('upay','Upay','manual','Personal','01XXXXXXXXX','Profit Shop','Send Money korar por TrxID niche din.',NULL,1,4);

-- Verification package (legacy v1; v2 uses membership_plans)
-- Conditional insert because this table has no unique key.
INSERT INTO `verification_packages` (`name`,`fee`,`duration_days`,`features`,`is_active`)
SELECT 'Gold Package',500.00,365,'["ads","quiz","typing","marketing","microjob","referral","recharge","shop_cashback"]',1
WHERE NOT EXISTS (SELECT 1 FROM `verification_packages` WHERE `name` = 'Gold Package');

-- Membership plans (v2 tiers, min withdraw 200 uniform)
INSERT IGNORE INTO `membership_plans`
  (slug, name, price, daily_task_limit, mlm_levels_unlocked, direct_commission_pct, cashback_pct, min_withdraw, badge_color, is_active) VALUES
('free','Free',0,2,1,5,0,200,'#9E9E9E',1),
('bronze','Bronze',500,8,3,12,1,200,'#CD7F32',1),
('silver','Silver',1000,18,5,15,2,200,'#C0C0C0',1),
('gold','Gold',2000,30,8,18,3,200,'#FFD700',1),
('platinum','Platinum',5000,50,10,22,5,200,'#7C3AED',1);

-- Per-level commission rates per plan
INSERT IGNORE INTO `membership_level_rates` (plan_id, level, commission_pct) VALUES
((SELECT id FROM membership_plans WHERE slug='free'),1,5),
((SELECT id FROM membership_plans WHERE slug='bronze'),1,12),
((SELECT id FROM membership_plans WHERE slug='bronze'),2,3),
((SELECT id FROM membership_plans WHERE slug='bronze'),3,1),
((SELECT id FROM membership_plans WHERE slug='silver'),1,15),
((SELECT id FROM membership_plans WHERE slug='silver'),2,5),
((SELECT id FROM membership_plans WHERE slug='silver'),3,3),
((SELECT id FROM membership_plans WHERE slug='silver'),4,2),
((SELECT id FROM membership_plans WHERE slug='silver'),5,1),
((SELECT id FROM membership_plans WHERE slug='gold'),1,18),
((SELECT id FROM membership_plans WHERE slug='gold'),2,6),
((SELECT id FROM membership_plans WHERE slug='gold'),3,4),
((SELECT id FROM membership_plans WHERE slug='gold'),4,2),
((SELECT id FROM membership_plans WHERE slug='gold'),5,1),
((SELECT id FROM membership_plans WHERE slug='gold'),6,1),
((SELECT id FROM membership_plans WHERE slug='gold'),7,0.5),
((SELECT id FROM membership_plans WHERE slug='gold'),8,0.5),
((SELECT id FROM membership_plans WHERE slug='platinum'),1,22),
((SELECT id FROM membership_plans WHERE slug='platinum'),2,8),
((SELECT id FROM membership_plans WHERE slug='platinum'),3,5),
((SELECT id FROM membership_plans WHERE slug='platinum'),4,3),
((SELECT id FROM membership_plans WHERE slug='platinum'),5,2),
((SELECT id FROM membership_plans WHERE slug='platinum'),6,1),
((SELECT id FROM membership_plans WHERE slug='platinum'),7,1),
((SELECT id FROM membership_plans WHERE slug='platinum'),8,0.5),
((SELECT id FROM membership_plans WHERE slug='platinum'),9,0.5),
((SELECT id FROM membership_plans WHERE slug='platinum'),10,0.5);

-- Demo catalog data is intentionally NOT seeded here.
-- Run seed_demo.php (after migrate.php) to load tasks, quizzes, shop,
-- resell products, recharge offers and admin micro jobs.

-- ------------------------------------------------------------
-- 25. RESELLING (Life Good model)
-- Resellers browse wholesale products, set their own retail price,
-- and place customer orders. Profit is settled after delivery.
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `resell_products` (
  `id` INT AUTO_INCREMENT PRIMARY KEY,
  `title` VARCHAR(255) NOT NULL,
  `description` TEXT NOT NULL,
  `category` VARCHAR(100) NOT NULL DEFAULT 'Home Accessories',
  `wholesale_price` DECIMAL(10,2) NOT NULL COMMENT 'Cost price from platform/admin',
  `suggested_retail_price` DECIMAL(10,2) NOT NULL,
  `max_sell_price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Maximum price reseller may charge per unit',
  `delivery_charge_inside` DECIMAL(10,2) DEFAULT 70.00,
  `delivery_charge_outside` DECIMAL(10,2) DEFAULT 130.00,
  `stock_quantity` INT DEFAULT 100,
  `image_url` VARCHAR(255) NOT NULL,
  `gallery_images` TEXT NULL COMMENT 'JSON array of extra photo URLs',
  `vendor_id` INT UNSIGNED NULL COMMENT 'NULL = platform/admin product; otherwise vendors.id',
  `vendor_name` VARCHAR(150) NULL,
  `vendor_whatsapp` VARCHAR(30) NULL,
  `is_approved` TINYINT(1) NOT NULL DEFAULT 1 COMMENT 'Admin moderation flag for vendor-submitted products',
  `is_active` TINYINT(1) DEFAULT 1,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX `idx_resell_products_active` (`is_active`),
  INDEX `idx_resell_products_category` (`category`),
  INDEX `idx_resell_products_vendor` (`vendor_id`),
  CONSTRAINT `fk_resell_products_vendor` FOREIGN KEY (`vendor_id`)
    REFERENCES `vendors` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `resell_orders` (
  `id` INT AUTO_INCREMENT PRIMARY KEY,
  `user_id` INT NOT NULL COMMENT 'The Reseller',
  `product_id` INT NOT NULL,
  `quantity` INT DEFAULT 1,
  `wholesale_price` DECIMAL(10,2) NOT NULL,
  `reseller_selling_price` DECIMAL(10,2) NOT NULL COMMENT 'Price charged to customer',
  `profit_amount` DECIMAL(10,2) NOT NULL COMMENT '(selling_price - wholesale_price) * qty',
  `delivery_zone` ENUM('inside_dhaka', 'outside_dhaka') DEFAULT 'inside_dhaka',
  `delivery_charge` DECIMAL(10,2) NOT NULL,
  `delivery_charge_paid` TINYINT(1) NOT NULL DEFAULT 0,
  `delivery_charge_payment_method` VARCHAR(50) NOT NULL DEFAULT '' COMMENT 'wallet, bkash, nagad, rocket',
  `delivery_charge_sender_phone` VARCHAR(30) NULL,
  `delivery_charge_trx_id` VARCHAR(100) NULL,
  `delivery_payment_status` ENUM('paid_wallet', 'pending_verification', 'rejected') NOT NULL DEFAULT 'pending_verification',
  `customer_name` VARCHAR(150) NOT NULL,
  `customer_phone` VARCHAR(25) NOT NULL,
  `district` VARCHAR(100) NOT NULL DEFAULT '',
  `upazila` VARCHAR(100) NOT NULL DEFAULT '',
  `customer_address` TEXT NOT NULL,
  `additional_instruction` TEXT NULL,
  `payment_method` VARCHAR(50) NOT NULL DEFAULT 'cod_manual',
  `courier_name` VARCHAR(100) NULL COMMENT 'e.g. Steadfast / Pathao / RedX',
  `tracking_code` VARCHAR(100) NULL,
  `status` ENUM('pending', 'confirmed', 'processing', 'shipped', 'delivered', 'cancelled', 'returned') DEFAULT 'pending',
  `is_profit_settled` TINYINT(1) DEFAULT 0,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX `idx_resell_orders_user_created` (`user_id`, `created_at`),
  INDEX `idx_resell_orders_status` (`status`),
  INDEX `idx_resell_orders_district` (`district`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Re-enable FK enforcement now that schema + seeds are fully in place.
SET FOREIGN_KEY_CHECKS = 1;
