MyRewardsViewController.swift 9.31 KB
//
//  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] = []
    
    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
        
        // Start with empty sections - will be populated dynamically by API calls
        loadCampaigns()
    }

    // NEW: Safe XIB registration method
    private func registerTableViewCells() {
        let cellConfigs = [
            ("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
        }
    }
    
    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)
    }
    
    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 .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: 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)
    }
}