MyRewardsViewController.swift 17.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
//
//  MyRewardsViewController.swift
//  SwiftWarplyFramework
//
//  Created by Manos Chorianopoulos on 22/5/25.
//

import UIKit


@objc public class MyRewardsViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    
    // MARK: - Initializers
    public convenience init() {
        self.init(nibName: "MyRewardsViewController", bundle: Bundle.frameworkBundle)
    }
    
    public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    
    // match - survey - tesla - energy saver
    // COMMENTED OUT: Static contest URLs no longer used
    // let contestUrls: [String] = [
    //     "https://warply.s3.amazonaws.com/dei/campaigns/match_dev/index.html",
    //     "https://warply.s3.amazonaws.com/dei/campaigns/questionnaire_dev/index.html",
    //     "https://warply.s3.amazonaws.com/dei/campaigns/tesla_dev/index.html",
    //     "https://warply.s3.amazonaws.com/dei/campaigns/EnergySaverContest_dev/index.html"
    // ]
    
    // Dynamic sections array - populated by API calls
    var sections: [SectionModel] = []
    
    // Campaign data for banners
    var bannerCampaigns: [CampaignItemModel] = []
    
    // Coupon sets data
    var couponSets: [CouponSetItemModel] = []
    
    // Merchants data
    var merchants: [MerchantModel] = []
    
    // Merchant categories data
    var merchantCategories: [MerchantCategoryModel] = []
    
    // Profile data
    var profileModel: ProfileModel?
    var profileSection: SectionModel?
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        // Hide the navigation bar
        // self.navigationController?.setNavigationBarHidden(true, animated: false)
    
        // UPDATED: Safe XIB registration with error handling
        registerTableViewCells()
        
        // Set up table view
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableView.automaticDimension
        
        // Add bottom padding
        tableView.contentInset.bottom = 60.0

        // Always create profile section first (with default state)
        createDefaultProfileSection()
        
        // Load data
        loadProfile()     // Load Profile
        loadCampaigns()   // Load campaigns
        loadCouponSets()  // Load couponsets
    }

    // NEW: Safe XIB registration method
    private func registerTableViewCells() {
        let cellConfigs = [
            ("MyRewardsProfileInfoTableViewCell", "MyRewardsProfileInfoTableViewCell"),
            ("MyRewardsBannerOffersScrollTableViewCell", "MyRewardsBannerOffersScrollTableViewCell"),
            ("MyRewardsOffersScrollTableViewCell", "MyRewardsOffersScrollTableViewCell")
        ]
        
        for (nibName, identifier) in cellConfigs {
            XIBLoader.registerTableViewCell(
                tableView,
                cellClass: UITableViewCell.self,
                nibName: nibName,
                identifier: identifier
            )
        }
        
    }

    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // Hide navigation bar when this view appears
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    public override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // Show navigation bar when leaving this view (for other screens)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }

    
    // MARK: - Campaign Loading
    private func loadCampaigns() {
        // Load campaigns from WarplySDK
        WarplySDK.shared.getCampaigns { [weak self] campaigns in
            guard let self = self, let campaigns = campaigns else { return }
            
            // Filter campaigns for banner display (contest campaigns) if needed
            self.bannerCampaigns = campaigns
            // .filter { campaign in
            //     // Filter by category "contest" or campaign_type "contest"
            //     return campaign._category == "contest" || campaign._campaign_type == "contest"
            // }
            
            // Create banner section with real campaign data
            if !self.bannerCampaigns.isEmpty {
                let bannerSection = SectionModel(
                    sectionType: .myRewardsBannerOffers,
                    title: "Διαγωνισμός",
                    items: self.bannerCampaigns,
                    itemType: .campaigns
                )
                self.sections.append(bannerSection)
            }
            
            // Reload table view with new sections
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        } failureCallback: { [weak self] errorCode in
            print("Failed to load campaigns: \(errorCode)")
            // No sections added on failure - table will be empty
        }
    }
    
    // MARK: - Coupon Sets Loading
    private func loadCouponSets() {
        // Load coupon sets from WarplySDK
        WarplySDK.shared.getCouponSets { [weak self] couponSets in
            guard let self = self, let couponSets = couponSets else { return }
            
            self.couponSets = couponSets
            
            // Load merchants after getting coupon sets
            self.loadMerchants()
            
        } failureCallback: { [weak self] errorCode in
            print("Failed to load coupon sets: \(errorCode)")
            // No sections added on failure - table will be empty
        }
    }
    
    // MARK: - Merchants Loading
    private func loadMerchants() {
        // Load merchants from WarplySDK (using enhanced getMerchants method)
        WarplySDK.shared.getMerchants { [weak self] merchants in
            guard let self = self, let merchants = merchants else { 
                // If merchants fail to load, still create coupon sets section without filtering
                self?.createCouponSetsSection()
                return 
            }
            
            self.merchants = merchants
            print("✅ [MyRewardsViewController] Loaded \(merchants.count) merchants")
            
            // Load merchant categories after merchants success
            self.loadMerchantCategories()
            
        } failureCallback: { [weak self] errorCode in
            print("Failed to load merchants: \(errorCode)")
            // If merchants fail, still show coupon sets without filtering
            self?.createCouponSetsSection()
        }
    }
    
    // MARK: - Merchant Categories Loading
    private func loadMerchantCategories() {
        // Load merchant categories from WarplySDK
        WarplySDK.shared.getMerchantCategories { [weak self] categories in
            guard let self = self, let categories = categories else {
                // If categories fail to load, still create coupon sets section without filtering
                self?.createCouponSetsSection()
                return
            }
            
            self.merchantCategories = categories
            print("✅ [MyRewardsViewController] Loaded \(categories.count) merchant categories")
            
            // TODO: Implement category-based filtering for coupon sets sections
            // For now, create the standard coupon sets section
            self.createCouponSetsSection()
            
        } failureCallback: { [weak self] errorCode in
            print("Failed to load merchant categories: \(errorCode)")
            // If categories fail, still show coupon sets without filtering
            self?.createCouponSetsSection()
        }
    }
    
    private func createCouponSetsSection() {
        // TODO: IMPLEMENT CATEGORY-BASED FILTERING
        // 
        // Current logic: Creates one section with all coupon sets
        // 
        // Future enhancement: Filter coupon sets into different sections based on categories
        // Logic:
        // 1. For each couponset, get its merchant_uuid
        // 2. Find the merchant with that merchant_uuid in self.merchants
        // 3. Get the merchant's category_uuid 
        // 4. Find the category with that category_uuid in self.merchantCategories
        // 5. Group coupon sets by category
        // 6. Create separate sections for each category
        //
        // Example structure after filtering:
        // - Section: "Εκπαίδευση" (Education) - coupon sets from education merchants
        // - Section: "Ψυχαγωγία" (Entertainment) - coupon sets from entertainment merchants
        // - etc.
        //
        // Implementation steps:
        // 1. Create a dictionary to group coupon sets by category: [String: [CouponSetItemModel]]
        // 2. Iterate through self.couponSets
        // 3. For each coupon set, find its merchant and category
        // 4. Add coupon set to the appropriate category group
        // 5. Create a SectionModel for each category group
        // 6. Sort sections by category name or priority
        
        // Current implementation (temporary):
        if !self.couponSets.isEmpty {
            let couponSetsSection = SectionModel(
                sectionType: .myRewardsHorizontalCouponsets,
                title: "Προσφορές",
                items: self.couponSets,
                itemType: .couponSets
            )
            self.sections.append(couponSetsSection)
        }
        
        // Reload table view with new sections
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
    
    // MARK: - Profile Loading
    public func loadProfile() {
        // Always attempt to load profile, regardless of authentication status
        // If not authenticated, the API call will fail gracefully and we keep the default state
        
        WarplySDK.shared.getProfile { [weak self] profile in
            guard let self = self else { return }
            
            if let profile = profile {
                // Success: Update with real profile data
                self.profileModel = profile
                self.updateProfileSectionWithData(profile)
                print("✅ [MyRewardsViewController] Profile loaded successfully")
            } else {
                // No profile data: Keep default state
                print("ℹ️ [MyRewardsViewController] No profile data received - keeping default state")
            }
            
        } failureCallback: { [weak self] errorCode in
            print("⚠️ [MyRewardsViewController] Profile loading failed with error: \(errorCode) - keeping default state")
            // Don't remove section - just keep the default state
            // The profile section remains visible with default profile pic
        }
    }
    
    private func createDefaultProfileSection() {
        // Create profile section with default/empty state
        let defaultProfileSection = SectionModel(
            sectionType: .myRewardsProfileInfo,
            title: nil,
            count: 1,
            metadata: ["profile": nil] // nil profile = default state
        )
        
        // Always insert at index 0 (top of the list)
        sections.insert(defaultProfileSection, at: 0)
        profileSection = defaultProfileSection
    }
    
    private func updateProfileSectionWithData(_ profile: ProfileModel) {
        // Create updated profile section with real data
        let updatedProfileSection = SectionModel(
            sectionType: .myRewardsProfileInfo,
            title: nil,
            count: 1,
            metadata: ["profile": profile]
        )
        
        // Find and update the profile section
        if let profileIndex = sections.firstIndex(where: { $0.sectionType == .myRewardsProfileInfo }) {
            sections[profileIndex] = updatedProfileSection
            profileSection = updatedProfileSection
            
            // Reload only the profile section
            DispatchQueue.main.async {
                self.tableView.reloadSections(IndexSet(integer: profileIndex), with: .none)
            }
        }
    }
    
    private func openCampaignViewController(with index: Int) {
        // Validate index bounds
        guard index < bannerCampaigns.count else { 
            print("Invalid campaign index: \(index)")
            return 
        }
        
        let campaign = bannerCampaigns[index]
        let campaignUrl = campaign._campaign_url ?? campaign.index_url
        
        // Check if URL is not empty before proceeding
        guard let url = campaignUrl, !url.isEmpty else {
            print("Campaign URL is empty, cannot open CampaignViewController for campaign: \(campaign._title ?? "Unknown")")
            return
        }
        
        // Proceed with navigation only if we have a valid URL
        let vc = SwiftWarplyFramework.CampaignViewController(nibName: "CampaignViewController", bundle: Bundle.frameworkBundle)
        vc.campaignUrl = url
        vc.showHeader = false
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    private func openCouponViewController(with offer: OfferModel) {
        // let vc = SwiftWarplyFramework.CouponViewController(nibName: "CouponViewController", bundle: Bundle.frameworkBundle)
        // vc.coupon = offer
        // self.navigationController?.pushViewController(vc, animated: true)
        print("CouponViewController navigation commented out - will handle later")
    }
    
    private func openProfileViewController() {
        let vc = SwiftWarplyFramework.ProfileViewController(nibName: "ProfileViewController", bundle: Bundle.frameworkBundle)
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - TableView
extension MyRewardsViewController: UITableViewDelegate, UITableViewDataSource{
    
    public func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }

    public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.0
    }

    public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.0
    }

    public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard indexPath.section < sections.count else {
            return UITableViewCell() // Return empty cell if section doesn't exist
        }
        
        let sectionModel = sections[indexPath.section]
        
        switch sectionModel.sectionType {
        case .myRewardsProfileInfo:
            let cell = tableView.dequeueReusableCell(withIdentifier: "MyRewardsProfileInfoTableViewCell", for: indexPath) as! MyRewardsProfileInfoTableViewCell
            cell.delegate = self
            cell.configureCell(data: sectionModel)
            return cell
            
        case .myRewardsBannerOffers:
            let cell = tableView.dequeueReusableCell(withIdentifier: "MyRewardsBannerOffersScrollTableViewCell", for: indexPath) as! MyRewardsBannerOffersScrollTableViewCell
            cell.delegate = self
            cell.configureCell(data: sectionModel)
            return cell
            
        case .myRewardsHorizontalCouponsets:
            let cell = tableView.dequeueReusableCell(withIdentifier: "MyRewardsOffersScrollTableViewCell", for: indexPath) as! MyRewardsOffersScrollTableViewCell
            cell.delegate = self
            cell.configureCell(data: sectionModel)
            return cell
            
        case .profileHeader, .profileQuestionnaire, .profileCouponFilters, .profileCoupon, .staticContent:
            // These sections don't belong in MyRewardsViewController - return empty cell
            // This should not happen in normal operation since MyRewardsViewController
            // should only contain MyRewards-specific sections
            let cell = UITableViewCell()
            cell.isHidden = true
            return cell
        }
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // Handle selection if needed - currently no action required
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

// Add delegate conformance
extension MyRewardsViewController: MyRewardsProfileInfoTableViewCellDelegate {
    func didTapProfileButton() {
        // Navigate to ProfileViewController
        openProfileViewController()
    }
}

// Add delegate conformance
extension MyRewardsViewController: MyRewardsBannerOffersScrollTableViewCellDelegate {
    func didSelectBannerOffer(_ index: Int) {
        // Navigate to CampaignViewController
        openCampaignViewController(with: index)
    }
    
//    func didTapProfileButton() {
//        // Navigate to ProfileViewController
//        openProfileViewController()
//    }
}

// Add delegate conformance
extension MyRewardsViewController: MyRewardsOffersScrollTableViewCellDelegate {
    func didSelectOffer(_ offer: OfferModel) {
        // Navigate to CouponViewController
        openCouponViewController(with: offer)
    }
    
    func didSelectCouponSet(_ couponSet: CouponSetItemModel) {
        // New logic for CouponSetItemModel - will handle navigation later
        print("CouponSet selected: \(couponSet._name)")
    }
}