-- =====================================================================
-- ZALO TAXI V6.2 - LỊCH CHUYẾN + GIA HẠN + ĐỐI SOÁT NGÂN HÀNG
-- Nâng từ V6.1. KHÔNG XÓA dữ liệu cũ.
-- Backup database trước khi chạy.
-- =====================================================================
SET NAMES utf8mb4;
SET time_zone = '+07:00';
SET @db := DATABASE();

-- 1) Thời hạn sử dụng của người dùng
SET @sql := (
  SELECT IF(COUNT(*)=0,
    'ALTER TABLE users ADD COLUMN subscription_expires_at DATETIME NULL AFTER last_login_at',
    'SELECT 1')
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA=@db AND TABLE_NAME='users' AND COLUMN_NAME='subscription_expires_at'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql := (
  SELECT IF(COUNT(*)=0,
    'ALTER TABLE users ADD INDEX idx_users_subscription_expiry (subscription_expires_at)',
    'SELECT 1')
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA=@db AND TABLE_NAME='users' AND INDEX_NAME='idx_users_subscription_expiry'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- 2) Yêu cầu thanh toán gia hạn
CREATE TABLE IF NOT EXISTS subscription_payment_intents (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    amount BIGINT UNSIGNED NOT NULL,
    payment_content VARCHAR(120) NOT NULL,
    duration_months INT UNSIGNED NOT NULL DEFAULT 1,
    duration_days INT UNSIGNED NOT NULL DEFAULT 0,
    status ENUM('WAITING','CONFIRMED','EXPIRED','CANCELLED') NOT NULL DEFAULT 'WAITING',
    confirmed_transaction_id VARCHAR(120) NULL,
    expires_at DATETIME NOT NULL,
    confirmed_at DATETIME NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_sub_intent_user (user_id,status,created_at),
    INDEX idx_sub_intent_expiry (status,expires_at),
    CONSTRAINT fk_sub_intent_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 3) Giao dịch đã dùng. transaction_id UNIQUE để không xác nhận 2 lần.
CREATE TABLE IF NOT EXISTS subscription_transactions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    intent_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    transaction_id VARCHAR(120) NOT NULL UNIQUE,
    amount BIGINT UNSIGNED NOT NULL,
    description TEXT NULL,
    transaction_date DATE NULL,
    raw_json JSON NULL,
    confirmed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_sub_tx_user (user_id,confirmed_at),
    INDEX idx_sub_tx_intent (intent_id),
    CONSTRAINT fk_sub_tx_intent FOREIGN KEY (intent_id) REFERENCES subscription_payment_intents(id) ON DELETE RESTRICT,
    CONSTRAINT fk_sub_tx_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 4) Nhật ký cộng/trừ thời gian để admin truy vết
CREATE TABLE IF NOT EXISTS subscription_extensions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    source ENUM('PAYMENT','ADMIN') NOT NULL,
    months_added INT NOT NULL DEFAULT 0,
    days_added INT NOT NULL DEFAULT 0,
    old_expires_at DATETIME NULL,
    new_expires_at DATETIME NOT NULL,
    transaction_id VARCHAR(120) NULL,
    admin_id BIGINT UNSIGNED NULL,
    note VARCHAR(500) NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_sub_ext_user (user_id,created_at),
    CONSTRAINT fk_sub_ext_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    CONSTRAINT fk_sub_ext_admin FOREIGN KEY (admin_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 5) Cài đặt gói sử dụng và ngân hàng. Token API để trống, nhập trong Admin.
INSERT INTO settings (`key`,`value`,`type`,description) VALUES
('subscription.enabled','1','BOOL','Bắt buộc còn hạn sử dụng mới được đăng hoặc nhận chuyến'),
('subscription.price','500000','INT','Số tiền gia hạn'),
('subscription.duration_months','1','INT','Số tháng cộng khi thanh toán thành công'),
('subscription.duration_days','0','INT','Số ngày cộng thêm ngoài số tháng'),
('subscription.bank_code','MB','STRING','Mã ngân hàng dùng cho VietQR'),
('subscription.bank_name','MB Bank','STRING','Tên ngân hàng hiển thị'),
('subscription.bank_account','603788888','STRING','Số tài khoản nhận tiền'),
('subscription.bank_account_name','LE KHAC NHAT','STRING','Tên chủ tài khoản'),
('subscription.qr_base_url','https://img.vietqr.io/image','STRING','Địa chỉ tạo ảnh QR VietQR'),
('subscription.history_api_base_url','https://sieuthicode.com/historyapimbbankv3','STRING','Địa chỉ API lịch sử giao dịch, không bao gồm token'),
('subscription.history_api_token','','STRING','Token API lịch sử giao dịch - chỉ lưu ở backend'),
('subscription.history_timeout','15','INT','Timeout kiểm tra lịch sử ngân hàng (giây)'),
('ride.max_booking_days','30','INT','Số ngày tối đa được đặt chuyến trước')
ON DUPLICATE KEY UPDATE `type`=VALUES(`type`),description=VALUES(description);

-- Giữ màu chủ đạo xanh lá cho toàn hệ thống.
INSERT INTO settings (`key`,`value`,`type`,description) VALUES
('branding.primary_color','#0B8F69','STRING','Màu chủ đạo giao diện')
ON DUPLICATE KEY UPDATE `value`='#0B8F69',`type`='STRING',description=VALUES(description);
