<?php
/**
 * Includes: Shared

 */
if (! defined('ABSPATH')) {
    die('Sorry, you cannot access this page.');
}
function chama_is_live_mode()
{
    $is_live_enabled = (int) ('disabled' === get_option('chama_test_mode'));
    return $is_live_enabled;
}

function chama_get_stripe_currencies()
{
    return [
        'AED' => esc_html__('United Arab Emirates Dirham', 'chama'),
        'AFN' => esc_html__('Afghan Afghani', 'chama'),
        'ALL' => esc_html__('Albanian Lek', 'chama'),
        'AMD' => esc_html__('Armenian Dram', 'chama'),
        'ANG' => esc_html__('Netherlands Antillean Gulden', 'chama'),
        'AOA' => esc_html__('Angolan Kwanza', 'chama'),
        'ARS' => esc_html__('Argentine Peso', 'chama'),
        'AUD' => esc_html__('Australian Dollar', 'chama'),
        'AWG' => esc_html__('Aruban Florin', 'chama'),
        'AZN' => esc_html__('Azerbaijani Manat', 'chama'),
        'BAM' => esc_html__('Bosnia & Herzegovina Convertible Mark', 'chama'),
        'BBD' => esc_html__('Barbadian Dollar', 'chama'),
        'BDT' => esc_html__('Bangladeshi Taka', 'chama'),
        'BIF' => esc_html__('Burundian Franc', 'chama'),
        'BGN' => esc_html__('Bulgarian Lev', 'chama'),
        'BMD' => esc_html__('Bermudian Dollar', 'chama'),
        'BND' => esc_html__('Brunei Dollar', 'chama'),
        'BOB' => esc_html__('Bolivian Boliviano', 'chama'),
        'BRL' => esc_html__('Brazilian Real', 'chama'),
        'BSD' => esc_html__('Bahamian Dollar', 'chama'),
        'BWP' => esc_html__('Botswana Pula', 'chama'),
        'BYR' => esc_html__('Belarusian Ruble', 'chama'),
        'BZD' => esc_html__('Belize Dollar', 'chama'),
        'CAD' => esc_html__('Canadian Dollar', 'chama'),
        'CDF' => esc_html__('Congolese Franc', 'chama'),
        'CHF' => esc_html__('Swiss Franc', 'chama'),
        'CLP' => esc_html__('Chilean Peso', 'chama'),
        'CNY' => esc_html__('Chinese Renminbi Yuan', 'chama'),
        'COP' => esc_html__('Colombian Peso', 'chama'),
        'CRC' => esc_html__('Costa Rican Colón', 'chama'),
        'CVE' => esc_html__('Cape Verdean Escudo', 'chama'),
        'CZK' => esc_html__('Czech Koruna', 'chama'),
        'DJF' => esc_html__('Djiboutian Franc', 'chama'),
        'DKK' => esc_html__('Danish Krone', 'chama'),
        'DOP' => esc_html__('Dominican Peso', 'chama'),
        'DZD' => esc_html__('Algerian Dinar', 'chama'),
        'EGP' => esc_html__('Egyptian Pound', 'chama'),
        'ETB' => esc_html__('Ethiopian Birr', 'chama'),
        'EUR' => esc_html__('Euro', 'chama'),
        'FJD' => esc_html__('Fijian Dollar', 'chama'),
        'FKP' => esc_html__('Falkland Islands Pound', 'chama'),
        'GBP' => esc_html__('British Pound', 'chama'),
        'GEL' => esc_html__('Georgian Lari', 'chama'),
        'GIP' => esc_html__('Gibraltar Pound', 'chama'),
        'GMD' => esc_html__('Gambian Dalasi', 'chama'),
        'GNF' => esc_html__('Guinean Franc', 'chama'),
        'GTQ' => esc_html__('Guatemalan Quetzal', 'chama'),
        'GYD' => esc_html__('Guyanese Dollar', 'chama'),
        'HKD' => esc_html__('Hong Kong Dollar', 'chama'),
        'HNL' => esc_html__('Honduran Lempira', 'chama'),
        'HRK' => esc_html__('Croatian Kuna', 'chama'),
        'HTG' => esc_html__('Haitian Gourde', 'chama'),
        'HUF' => esc_html__('Hungarian Forint', 'chama'),
        'IDR' => esc_html__('Indonesian Rupiah', 'chama'),
        'ILS' => esc_html__('Israeli New Sheqel', 'chama'),
        'INR' => esc_html__('Indian Rupee', 'chama'),
        'ISK' => esc_html__('Icelandic Króna', 'chama'),
        'JMD' => esc_html__('Jamaican Dollar', 'chama'),
        'JPY' => esc_html__('Japanese Yen', 'chama'),
        'KES' => esc_html__('Kenyan Shilling', 'chama'),
        'KGS' => esc_html__('Kyrgyzstani Som', 'chama'),
        'KHR' => esc_html__('Cambodian Riel', 'chama'),
        'KMF' => esc_html__('Comorian Franc', 'chama'),
        'KRW' => esc_html__('South Korean Won', 'chama'),
        'KYD' => esc_html__('Cayman Islands Dollar', 'chama'),
        'KZT' => esc_html__('Kazakhstani Tenge', 'chama'),
        'LAK' => esc_html__('Lao Kip', 'chama'),
        'LBP' => esc_html__('Lebanese Pound', 'chama'),
        'LKR' => esc_html__('Sri Lankan Rupee', 'chama'),
        'LRD' => esc_html__('Liberian Dollar', 'chama'),
        'LSL' => esc_html__('Lesotho Loti', 'chama'),
        'MAD' => esc_html__('Moroccan Dirham', 'chama'),
        'MDL' => esc_html__('Moldovan Leu', 'chama'),
        'MGA' => esc_html__('Malagasy Ariary', 'chama'),
        'MKD' => esc_html__('Macedonian Denar', 'chama'),
        'MMK' => esc_html__('Myanmar Kyat', 'chama'),
        'MNT' => esc_html__('Mongolian Tögrög', 'chama'),
        'MOP' => esc_html__('Macanese Pataca', 'chama'),
        'MRO' => esc_html__('Mauritanian Ouguiya', 'chama'),
        'MUR' => esc_html__('Mauritian Rupee', 'chama'),
        'MVR' => esc_html__('Maldivian Rufiyaa', 'chama'),
        'MWK' => esc_html__('Malawian Kwacha', 'chama'),
        'MXN' => esc_html__('Mexican Peso', 'chama'),
        'MYR' => esc_html__('Malaysian Ringgit', 'chama'),
        'MZN' => esc_html__('Mozambican Metical', 'chama'),
        'NAD' => esc_html__('Namibian Dollar', 'chama'),
        'NGN' => esc_html__('Nigerian Naira', 'chama'),
        'NIO' => esc_html__('Nicaraguan Córdoba', 'chama'),
        'NOK' => esc_html__('Norwegian Krone', 'chama'),
        'NPR' => esc_html__('Nepalese Rupee', 'chama'),
        'NZD' => esc_html__('New Zealand Dollar', 'chama'),
        'PAB' => esc_html__('Panamanian Balboa', 'chama'),
        'PEN' => esc_html__('Peruvian Nuevo Sol', 'chama'),
        'PGK' => esc_html__('Papua New Guinean Kina', 'chama'),
        'PHP' => esc_html__('Philippine Peso', 'chama'),
        'PKR' => esc_html__('Pakistani Rupee', 'chama'),
        'PLN' => esc_html__('Polish Złoty', 'chama'),
        'PYG' => esc_html__('Paraguayan Guaraní', 'chama'),
        'QAR' => esc_html__('Qatari Riyal', 'chama'),
        'RON' => esc_html__('Romanian Leu', 'chama'),
        'RSD' => esc_html__('Serbian Dinar', 'chama'),
        'RUB' => esc_html__('Russian Ruble', 'chama'),
        'RWF' => esc_html__('Rwandan Franc', 'chama'),
        'SAR' => esc_html__('Saudi Riyal', 'chama'),
        'SBD' => esc_html__('Solomon Islands Dollar', 'chama'),
        'SCR' => esc_html__('Seychellois Rupee', 'chama'),
        'SEK' => esc_html__('Swedish Krona', 'chama'),
        'SGD' => esc_html__('Singapore Dollar', 'chama'),
        'SHP' => esc_html__('Saint Helenian Pound', 'chama'),
        'SLL' => esc_html__('Sierra Leonean Leone', 'chama'),
        'SOS' => esc_html__('Somali Shilling', 'chama'),
        'SRD' => esc_html__('Surinamese Dollar', 'chama'),
        'STD' => esc_html__('São Tomé and Príncipe Dobra', 'chama'),
        'SZL' => esc_html__('Swazi Lilangeni', 'chama'),
        'THB' => esc_html__('Thai Baht', 'chama'),
        'TJS' => esc_html__('Tajikistani Somoni', 'chama'),
        'TOP' => esc_html__('Tongan Paʻanga', 'chama'),
        'TRY' => esc_html__('Turkish Lira', 'chama'),
        'TTD' => esc_html__('Trinidad and Tobago Dollar', 'chama'),
        'TWD' => esc_html__('New Taiwan Dollar', 'chama'),
        'TZS' => esc_html__('Tanzanian Shilling', 'chama'),
        'UAH' => esc_html__('Ukrainian Hryvnia', 'chama'),
        'UGX' => esc_html__('Ugandan Shilling', 'chama'),
        'USD' => esc_html__('United States Dollar', 'chama'),
        'UYU' => esc_html__('Uruguayan Peso', 'chama'),
        'UZS' => esc_html__('Uzbekistani Som', 'chama'),
        'VND' => esc_html__('Vietnamese Đồng', 'chama'),
        'VUV' => esc_html__('Vanuatu Vatu', 'chama'),
        'WST' => esc_html__('Samoan Tala', 'chama'),
        'XAF' => esc_html__('Central African Cfa Franc', 'chama'),
        'XCD' => esc_html__('East Caribbean Dollar', 'chama'),
        'XOF' => esc_html__('West African Cfa Franc', 'chama'),
        'XPF' => esc_html__('Cfp Franc', 'chama'),
        'YER' => esc_html__('Yemeni Rial', 'chama'),
        'ZAR' => esc_html__('South African Rand', 'chama'),
        'ZMW' => esc_html__('Zambian Kwacha', 'chama'),
    ];
}

function chama_get_stripe_locations()
{
    return [
        'AFRICA'        => esc_html__('Africa', 'chama'),
        'ANTARCTICA'    => esc_html__('Antarctica', 'chama'),
        'ASIA'          => esc_html__('Asia', 'chama'),
        'EUROPE'        => esc_html__('Europe', 'chama'),
        'NORTH-AMERICA' => esc_html__('North America', 'chama'),
        'OCEANIA'       => esc_html__('Oceania', 'chama'),
        'SOUTH-AMERICA' => esc_html__('South America', 'chama'),
        'AF'            => esc_html__('Afghanistan', 'chama'),
        'AX'            => esc_html__('Åland Islands', 'chama'),
        'AL'            => esc_html__('Albania', 'chama'),
        'DZ'            => esc_html__('Algeria', 'chama'),
        'AS'            => esc_html__('American Samoa', 'chama'),
        'AD'            => esc_html__('Andorra', 'chama'),
        'AO'            => esc_html__('Angola', 'chama'),
        'AI'            => esc_html__('Anguilla', 'chama'),
        'AQ'            => esc_html__('Antarctica', 'chama'),
        'AG'            => esc_html__('Antigua and Barbuda', 'chama'),
        'AR'            => esc_html__('Argentina', 'chama'),
        'AM'            => esc_html__('Armenia', 'chama'),
        'AW'            => esc_html__('Aruba', 'chama'),
        'AU'            => esc_html__('Australia', 'chama'),
        'AT'            => esc_html__('Austria', 'chama'),
        'AZ'            => esc_html__('Azerbaijan', 'chama'),
        'BS'            => esc_html__('Bahamas', 'chama'),
        'BH'            => esc_html__('Bahrain', 'chama'),
        'BD'            => esc_html__('Bangladesh', 'chama'),
        'BB'            => esc_html__('Barbados', 'chama'),
        'BY'            => esc_html__('Belarus', 'chama'),
        'BE'            => esc_html__('Belgium', 'chama'),
        'BZ'            => esc_html__('Belize', 'chama'),
        'BJ'            => esc_html__('Benin', 'chama'),
        'BM'            => esc_html__('Bermuda', 'chama'),
        'BT'            => esc_html__('Bhutan', 'chama'),
        'BO'            => esc_html__('Bolivia', 'chama'),
        'BA'            => esc_html__('Bosnia and Herzegovina', 'chama'),
        'BW'            => esc_html__('Botswana', 'chama'),
        'BV'            => esc_html__('Bouvet Island', 'chama'),
        'BR'            => esc_html__('Brazil', 'chama'),
        'BQ'            => esc_html__('British Antarctic Territory', 'chama'),
        'IO'            => esc_html__('British Indian Ocean Territory', 'chama'),
        'VG'            => esc_html__('British Virgin Islands', 'chama'),
        'BN'            => esc_html__('Brunei', 'chama'),
        'BG'            => esc_html__('Bulgaria', 'chama'),
        'BF'            => esc_html__('Burkina Faso', 'chama'),
        'BI'            => esc_html__('Burundi', 'chama'),
        'KH'            => esc_html__('Cambodia', 'chama'),
        'CM'            => esc_html__('Cameroon', 'chama'),
        'CA'            => esc_html__('Canada', 'chama'),
        'CT'            => esc_html__('Canton and Enderbury Islands', 'chama'),
        'CV'            => esc_html__('Cape Verde', 'chama'),
        'KY'            => esc_html__('Cayman Islands', 'chama'),
        'CF'            => esc_html__('Central African Republic', 'chama'),
        'TD'            => esc_html__('Chad', 'chama'),
        'CL'            => esc_html__('Chile', 'chama'),
        'CN'            => esc_html__('China', 'chama'),
        'CX'            => esc_html__('Christmas Island', 'chama'),
        'CC'            => esc_html__('Cocos [Keeling] Islands', 'chama'),
        'CO'            => esc_html__('Colombia', 'chama'),
        'KM'            => esc_html__('Comoros', 'chama'),
        'CG'            => esc_html__('Congo - Brazzaville', 'chama'),
        'CD'            => esc_html__('Congo - Kinshasa', 'chama'),
        'CK'            => esc_html__('Cook Islands', 'chama'),
        'CR'            => esc_html__('Costa Rica', 'chama'),
        'HR'            => esc_html__('Croatia', 'chama'),
        'CU'            => esc_html__('Cuba', 'chama'),
        'CY'            => esc_html__('Cyprus', 'chama'),
        'CZ'            => esc_html__('Czech Republic', 'chama'),
        'CI'            => esc_html__('Côte d’Ivoire', 'chama'),
        'DK'            => esc_html__('Denmark', 'chama'),
        'DJ'            => esc_html__('Djibouti', 'chama'),
        'DM'            => esc_html__('Dominica', 'chama'),
        'DO'            => esc_html__('Dominican Republic', 'chama'),
        'NQ'            => esc_html__('Dronning Maud Land', 'chama'),
        'DD'            => esc_html__('East Germany', 'chama'),
        'EC'            => esc_html__('Ecuador', 'chama'),
        'EG'            => esc_html__('Egypt', 'chama'),
        'SV'            => esc_html__('El Salvador', 'chama'),
        'GQ'            => esc_html__('Equatorial Guinea', 'chama'),
        'ER'            => esc_html__('Eritrea', 'chama'),
        'EE'            => esc_html__('Estonia', 'chama'),
        'ET'            => esc_html__('Ethiopia', 'chama'),
        'FK'            => esc_html__('Falkland Islands', 'chama'),
        'FO'            => esc_html__('Faroe Islands', 'chama'),
        'FJ'            => esc_html__('Fiji', 'chama'),
        'FI'            => esc_html__('Finland', 'chama'),
        'FR'            => esc_html__('France', 'chama'),
        'GF'            => esc_html__('French Guiana', 'chama'),
        'PF'            => esc_html__('French Polynesia', 'chama'),
        'TF'            => esc_html__('French Southern Territories', 'chama'),
        'FQ'            => esc_html__('French Southern and Antarctic Territories', 'chama'),
        'GA'            => esc_html__('Gabon', 'chama'),
        'GM'            => esc_html__('Gambia', 'chama'),
        'GE'            => esc_html__('Georgia', 'chama'),
        'DE'            => esc_html__('Germany', 'chama'),
        'GH'            => esc_html__('Ghana', 'chama'),
        'GI'            => esc_html__('Gibraltar', 'chama'),
        'GR'            => esc_html__('Greece', 'chama'),
        'GL'            => esc_html__('Greenland', 'chama'),
        'GD'            => esc_html__('Grenada', 'chama'),
        'GP'            => esc_html__('Guadeloupe', 'chama'),
        'GU'            => esc_html__('Guam', 'chama'),
        'GT'            => esc_html__('Guatemala', 'chama'),
        'GG'            => esc_html__('Guernsey', 'chama'),
        'GN'            => esc_html__('Guinea', 'chama'),
        'GW'            => esc_html__('Guinea-Bissau', 'chama'),
        'GY'            => esc_html__('Guyana', 'chama'),
        'HT'            => esc_html__('Haiti', 'chama'),
        'HM'            => esc_html__('Heard Island and McDonald Islands', 'chama'),
        'HN'            => esc_html__('Honduras', 'chama'),
        'HK'            => esc_html__('Hong Kong SAR China', 'chama'),
        'HU'            => esc_html__('Hungary', 'chama'),
        'IS'            => esc_html__('Iceland', 'chama'),
        'IN'            => esc_html__('India', 'chama'),
        'ID'            => esc_html__('Indonesia', 'chama'),
        'IR'            => esc_html__('Iran', 'chama'),
        'IQ'            => esc_html__('Iraq', 'chama'),
        'IE'            => esc_html__('Ireland', 'chama'),
        'IM'            => esc_html__('Isle of Man', 'chama'),
        'IL'            => esc_html__('Israel', 'chama'),
        'IT'            => esc_html__('Italy', 'chama'),
        'JM'            => esc_html__('Jamaica', 'chama'),
        'JP'            => esc_html__('Japan', 'chama'),
        'JE'            => esc_html__('Jersey', 'chama'),
        'JT'            => esc_html__('Johnston Island', 'chama'),
        'JO'            => esc_html__('Jordan', 'chama'),
        'KZ'            => esc_html__('Kazakhstan', 'chama'),
        'KE'            => esc_html__('Kenya', 'chama'),
        'KI'            => esc_html__('Kiribati', 'chama'),
        'KW'            => esc_html__('Kuwait', 'chama'),
        'KG'            => esc_html__('Kyrgyzstan', 'chama'),
        'LA'            => esc_html__('Laos', 'chama'),
        'LV'            => esc_html__('Latvia', 'chama'),
        'LB'            => esc_html__('Lebanon', 'chama'),
        'LS'            => esc_html__('Lesotho', 'chama'),
        'LR'            => esc_html__('Liberia', 'chama'),
        'LY'            => esc_html__('Libya', 'chama'),
        'LI'            => esc_html__('Liechtenstein', 'chama'),
        'LT'            => esc_html__('Lithuania', 'chama'),
        'LU'            => esc_html__('Luxembourg', 'chama'),
        'MO'            => esc_html__('Macau SAR China', 'chama'),
        'MK'            => esc_html__('Macedonia', 'chama'),
        'MG'            => esc_html__('Madagascar', 'chama'),
        'MW'            => esc_html__('Malawi', 'chama'),
        'MY'            => esc_html__('Malaysia', 'chama'),
        'MV'            => esc_html__('Maldives', 'chama'),
        'ML'            => esc_html__('Mali', 'chama'),
        'MT'            => esc_html__('Malta', 'chama'),
        'MH'            => esc_html__('Marshall Islands', 'chama'),
        'MQ'            => esc_html__('Martinique', 'chama'),
        'MR'            => esc_html__('Mauritania', 'chama'),
        'MU'            => esc_html__('Mauritius', 'chama'),
        'YT'            => esc_html__('Mayotte', 'chama'),
        'FX'            => esc_html__('Metropolitan France', 'chama'),
        'MX'            => esc_html__('Mexico', 'chama'),
        'FM'            => esc_html__('Micronesia', 'chama'),
        'MI'            => esc_html__('Midway Islands', 'chama'),
        'MD'            => esc_html__('Moldova', 'chama'),
        'MC'            => esc_html__('Monaco', 'chama'),
        'MN'            => esc_html__('Mongolia', 'chama'),
        'ME'            => esc_html__('Montenegro', 'chama'),
        'MS'            => esc_html__('Montserrat', 'chama'),
        'MA'            => esc_html__('Morocco', 'chama'),
        'MZ'            => esc_html__('Mozambique', 'chama'),
        'MM'            => esc_html__('Myanmar [Burma]', 'chama'),
        'NA'            => esc_html__('Namibia', 'chama'),
        'NR'            => esc_html__('Nauru', 'chama'),
        'NP'            => esc_html__('Nepal', 'chama'),
        'NL'            => esc_html__('Netherlands', 'chama'),
        'AN'            => esc_html__('Netherlands Antilles', 'chama'),
        'NT'            => esc_html__('Neutral Zone', 'chama'),
        'NC'            => esc_html__('New Caledonia', 'chama'),
        'NZ'            => esc_html__('New Zealand', 'chama'),
        'NI'            => esc_html__('Nicaragua', 'chama'),
        'NE'            => esc_html__('Niger', 'chama'),
        'NG'            => esc_html__('Nigeria', 'chama'),
        'NU'            => esc_html__('Niue', 'chama'),
        'NF'            => esc_html__('Norfolk Island', 'chama'),
        'KP'            => esc_html__('North Korea', 'chama'),
        'VD'            => esc_html__('North Vietnam', 'chama'),
        'MP'            => esc_html__('Northern Mariana Islands', 'chama'),
        'NO'            => esc_html__('Norway', 'chama'),
        'OM'            => esc_html__('Oman', 'chama'),
        'PC'            => esc_html__('Pacific Islands Trust Territory', 'chama'),
        'PK'            => esc_html__('Pakistan', 'chama'),
        'PW'            => esc_html__('Palau', 'chama'),
        'PS'            => esc_html__('Palestinian Territories', 'chama'),
        'PA'            => esc_html__('Panama', 'chama'),
        'PZ'            => esc_html__('Panama Canal Zone', 'chama'),
        'PG'            => esc_html__('Papua New Guinea', 'chama'),
        'PY'            => esc_html__('Paraguay', 'chama'),
        'YD'            => esc_html__('People\'s Democratic Republic of Yemen', 'chama'),
        'PE'            => esc_html__('Peru', 'chama'),
        'PH'            => esc_html__('Philippines', 'chama'),
        'PN'            => esc_html__('Pitcairn Islands', 'chama'),
        'PL'            => esc_html__('Poland', 'chama'),
        'PT'            => esc_html__('Portugal', 'chama'),
        'PR'            => esc_html__('Puerto Rico', 'chama'),
        'QA'            => esc_html__('Qatar', 'chama'),
        'RO'            => esc_html__('Romania', 'chama'),
        'RU'            => esc_html__('Russia', 'chama'),
        'RW'            => esc_html__('Rwanda', 'chama'),
        'RE'            => esc_html__('Réunion', 'chama'),
        'BL'            => esc_html__('Saint Barthélemy', 'chama'),
        'SH'            => esc_html__('Saint Helena', 'chama'),
        'KN'            => esc_html__('Saint Kitts and Nevis', 'chama'),
        'LC'            => esc_html__('Saint Lucia', 'chama'),
        'MF'            => esc_html__('Saint Martin', 'chama'),
        'PM'            => esc_html__('Saint Pierre and Miquelon', 'chama'),
        'VC'            => esc_html__('Saint Vincent and the Grenadines', 'chama'),
        'WS'            => esc_html__('Samoa', 'chama'),
        'SM'            => esc_html__('San Marino', 'chama'),
        'SA'            => esc_html__('Saudi Arabia', 'chama'),
        'SN'            => esc_html__('Senegal', 'chama'),
        'RS'            => esc_html__('Serbia', 'chama'),
        'CS'            => esc_html__('Serbia and Montenegro', 'chama'),
        'SC'            => esc_html__('Seychelles', 'chama'),
        'SL'            => esc_html__('Sierra Leone', 'chama'),
        'SG'            => esc_html__('Singapore', 'chama'),
        'SK'            => esc_html__('Slovakia', 'chama'),
        'SI'            => esc_html__('Slovenia', 'chama'),
        'SB'            => esc_html__('Solomon Islands', 'chama'),
        'SO'            => esc_html__('Somalia', 'chama'),
        'ZA'            => esc_html__('South Africa', 'chama'),
        'GS'            => esc_html__('South Georgia and the South Sandwich Islands', 'chama'),
        'KR'            => esc_html__('South Korea', 'chama'),
        'ES'            => esc_html__('Spain', 'chama'),
        'LK'            => esc_html__('Sri Lanka', 'chama'),
        'SD'            => esc_html__('Sudan', 'chama'),
        'SR'            => esc_html__('Suriname', 'chama'),
        'SJ'            => esc_html__('Svalbard and Jan Mayen', 'chama'),
        'SZ'            => esc_html__('Swaziland', 'chama'),
        'SE'            => esc_html__('Sweden', 'chama'),
        'CH'            => esc_html__('Switzerland', 'chama'),
        'SY'            => esc_html__('Syria', 'chama'),
        'ST'            => esc_html__('São Tomé and Príncipe', 'chama'),
        'TW'            => esc_html__('Taiwan', 'chama'),
        'TJ'            => esc_html__('Tajikistan', 'chama'),
        'TZ'            => esc_html__('Tanzania', 'chama'),
        'TH'            => esc_html__('Thailand', 'chama'),
        'TL'            => esc_html__('Timor-Leste', 'chama'),
        'TG'            => esc_html__('Togo', 'chama'),
        'TK'            => esc_html__('Tokelau', 'chama'),
        'TO'            => esc_html__('Tonga', 'chama'),
        'TT'            => esc_html__('Trinidad and Tobago', 'chama'),
        'TN'            => esc_html__('Tunisia', 'chama'),
        'TR'            => esc_html__('Turkey', 'chama'),
        'TM'            => esc_html__('Turkmenistan', 'chama'),
        'TC'            => esc_html__('Turks and Caicos Islands', 'chama'),
        'TV'            => esc_html__('Tuvalu', 'chama'),
        'UM'            => esc_html__('U.S. Minor Outlying Islands', 'chama'),
        'PU'            => esc_html__('U.S. Miscellaneous Pacific Islands', 'chama'),
        'VI'            => esc_html__('U.S. Virgin Islands', 'chama'),
        'UG'            => esc_html__('Uganda', 'chama'),
        'UA'            => esc_html__('Ukraine', 'chama'),
        'SU'            => esc_html__('Union of Soviet Socialist Republics', 'chama'),
        'AE'            => esc_html__('United Arab Emirates', 'chama'),
        'GB'            => esc_html__('United Kingdom', 'chama'),
        'US'            => esc_html__('United States', 'chama'),
        'ZZ'            => esc_html__('Unknown or Invalid Region', 'chama'),
        'UY'            => esc_html__('Uruguay', 'chama'),
        'UZ'            => esc_html__('Uzbekistan', 'chama'),
        'VU'            => esc_html__('Vanuatu', 'chama'),
        'VA'            => esc_html__('Vatican City', 'chama'),
        'VE'            => esc_html__('Venezuela', 'chama'),
        'VN'            => esc_html__('Vietnam', 'chama'),
        'WK'            => esc_html__('Wake Island', 'chama'),
        'WF'            => esc_html__('Wallis and Futuna', 'chama'),
        'EH'            => esc_html__('Western Sahara', 'chama'),
        'YE'            => esc_html__('Yemen', 'chama'),
        'ZM'            => esc_html__('Zambia', 'chama'),
        'ZW'            => esc_html__('Zimbabwe', 'chama'),
    ];
}
function chama_get_continent_countries()
{
    return [
        'AFRICA'        => 'DZ,AO,BJ,BW,BF,BI,CM,CV,CF,TD,KM,CG,CD,CI,DJ,EG,GQ,ER,ET,GA,GM,GH,GN,GW,KE,LS,LR,LY,MG,MW,ML,MR,MU,YT,MA,MZ,NA,NE,NG,RE,RW,SH,ST,SN,SC,SL,SO,ZA,SD,SZ,TZ,TG,TN,UG,EH,ZM,ZW',
        'ANTARCTICA'    => 'AQ,BV,TF,HM,GS',
        'ASIA'          => 'AF,AM,AZ,BH,BD,BT,IO,BN,KH,CN,CX,CC,CY,GE,HK,IN,ID,IR,IQ,IL,JP,JO,KZ,KP,KR,KW,KG,LA,LB,MO,MY,MV,MN,MM,NP,OM,PK,PS,PH,QA,SA,SG,LK,SY,TW,TJ,TH,TL,TR,TM,AE,UZ,VN,YE',
        'EUROPE'        => 'AX,AL,AD,AT,BY,BE,BA,BG,HR,CZ,DK,EE,FO,FI,FR,DE,GI,GR,GG,VA,HU,IS,IE,IM,IT,JE,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB',
        'NORTH-AMERICA' => 'AI,AG,AW,BS,BB,BZ,BM,CA,KY,CR,CU,DM,DO,SV,GL,GD,GP,GT,HT,HN,JM,MQ,MX,MS,AN,NI,PA,PR,KN,LC,PM,VC,TT,TC,US,VG,VI',
        'OCEANIA'       => 'AS,AU,CK,FJ,PF,GU,KI,MH,FM,NR,NC,NZ,NU,NF,MP,PW,PG,PN,WS,SB,TK,TO,TV,UM,VU,WF',
        'SOUTH-AMERICA' => 'AR,BO,BR,CL,CO,EC,FK,GF,GY,PY,PE,SR,UY,VE',
    ];
}
function chama_get_country_from_code($code = '')
{

    if (! $code) {

        // If no code is passed then default it to US.
        $code = 'US';
    }

    $code      = strtoupper($code);
    $countries = chama_get_stripe_locations();

    $labels = apply_filters('chama_country_labels', $countries);

    $code_label = isset($labels[$code]) ? $labels[$code] : '';

    return apply_filters('chama_country_label', $code_label, $code);
}
function chama_get_coutries_list_by_continent($continent = '')
{

    if (! $continent) {

        // If no code is passed then default it to US.
        $continent = 'NORTH-AMERICA';
    }

    $continent  = strtoupper($continent);
    $continents = chama_get_continent_countries();

    $country_lists = apply_filters('chama_country_lists', $continents);

    $list = isset($country_lists[$continent]) ? $country_lists[$continent] : '';

    return apply_filters('chama_country_list', $list, $continent);
}
function chama_get_currencies()
{
    $currencies = [
        'AED' => '&#x62f;.&#x625;',
        'AFN' => '&#x60b;',
        'ALL' => 'L',
        'AMD' => 'AMD',
        'ANG' => '&fnof;',
        'AOA' => 'Kz',
        'ARS' => '&#36;',
        'AUD' => '&#36;',
        'AWG' => '&fnof;',
        'AZN' => 'AZN',
        'BAM' => 'KM',
        'BBD' => '&#36;',
        'BDT' => '&#2547;&nbsp;',
        'BGN' => '&#1083;&#1074;.',
        'BIF' => 'Fr',
        'BMD' => '&#36;',
        'BND' => '&#36;',
        'BOB' => 'Bs.',
        'BRL' => '&#82;&#36;',
        'BSD' => '&#36;',
        'BWP' => 'P',
        'BYR' => 'Br',
        'BZD' => '&#36;',
        'CAD' => '&#36;',
        'CDF' => 'Fr',
        'CHF' => '&#67;&#72;&#70;',
        'CLP' => '&#36;',
        'CNY' => '&yen;',
        'COP' => '&#36;',
        'CRC' => '&#x20a1;',
        'CVE' => '&#36;',
        'CZK' => '&#75;&#269;',
        'DJF' => 'Fr',
        'DKK' => 'DKK',
        'DOP' => 'RD&#36;',
        'DZD' => '&#x62f;.&#x62c;',
        'EGP' => 'EGP',
        'ETB' => 'Br',
        'EUR' => '&euro;',
        'FJD' => '&#36;',
        'FKP' => '&pound;',
        'GBP' => '&pound;',
        'GEL' => '&#x10da;',
        'GIP' => '&pound;',
        'GMD' => 'D',
        'GNF' => 'Fr',
        'GTQ' => 'Q',
        'GYD' => '&#36;',
        'HKD' => '&#36;',
        'HNL' => 'L',
        'HRK' => 'Kn',
        'HTG' => 'G',
        'HUF' => '&#70;&#116;',
        'IDR' => 'Rp',
        'ILS' => '&#8362;',
        'INR' => '&#8377;',
        'ISK' => 'Kr.',
        'JMD' => '&#36;',
        'JPY' => '&yen;',
        'KES' => 'KSh',
        'KGS' => '&#x43b;&#x432;',
        'KHR' => '&#x17db;',
        'KMF' => 'Fr',
        'KRW' => '&#8361;',
        'KYD' => '&#36;',
        'KZT' => 'KZT',
        'LAK' => '&#8365;',
        'LBP' => '&#x644;.&#x644;',
        'LKR' => '&#xdbb;&#xdd4;',
        'LRD' => '&#36;',
        'LSL' => 'L',
        'MAD' => '&#x62f;. &#x645;.',
        'MDL' => 'L',
        'MGA' => 'Ar',
        'MKD' => '&#x434;&#x435;&#x43d;',
        'MMK' => 'Ks',
        'MNT' => '&#x20ae;',
        'MOP' => 'P',
        'MRO' => 'UM',
        'MUR' => '&#x20a8;',
        'MVR' => '.&#x783;',
        'MWK' => 'MK',
        'MXN' => 'MXN',
        'MYR' => '&#82;&#77;',
        'MZN' => 'MT',
        'NAD' => '&#36;',
        'NGN' => '&#8358;',
        'NIO' => 'C&#36;',
        'NOK' => '&#107;&#114;',
        'NPR' => '&#8360;',
        'NZD' => '&#36;',
        'PAB' => 'B/.',
        'PEN' => 'S/.',
        'PGK' => 'K',
        'PHP' => '&#8369;',
        'PKR' => '&#8360;',
        'PLN' => '&#122;&#322;',
        'PYG' => '&#8370;',
        'QAR' => '&#x631;.&#x642;',
        'RON' => 'lei',
        'RSD' => '&#x434;&#x438;&#x43d;.',
        'RUB' => '&#8381;',
        'RWF' => 'Fr',
        'SAR' => '&#x631;.&#x633;',
        'SBD' => '&#36;',
        'SCR' => '&#x20a8;',
        'SEK' => '&#107;&#114;',
        'SGD' => 'S&#36;',
        'SHP' => '&pound;',
        'SLL' => 'Le',
        'SOS' => 'Sh',
        'SRD' => '&#36;',
        'STD' => 'Db',
        'SZL' => 'L',
        'THB' => '&#3647;',
        'TJS' => '&#x405;&#x41c;',
        'TOP' => 'T&#36;',
        'TRY' => '&#8378;',
        'TTD' => '&#36;',
        'TWD' => '&#78;&#84;&#36;',
        'TZS' => 'Sh',
        'UAH' => '&#8372;',
        'UGX' => 'UGX',
        'USD' => '&#36;',
        'UYU' => '&#36;',
        'UZS' => 'UZS',
        'VND' => '&#8363;',
        'VUV' => 'Vt',
        'WST' => 'T',
        'XAF' => 'Fr',
        'XCD' => '&#36;',
        'XOF' => 'Fr',
        'XPF' => 'Fr',
        'YER' => '&#xfdfc;',
        'ZAR' => '&#82;',
        'ZMW' => 'ZK',
    ];

    $currencies = apply_filters('chama_get_currencies', $currencies);

    return $currencies;
}
function chama_get_currency_symbol($currency = '')
{

    if (! $currency) {

        // If no currency is passed then default it to USD.
        $currency = 'USD';
    }

    $currency   = strtoupper($currency);
    $currencies = chama_get_currencies();

    $symbols = apply_filters('chama_currency_symbols', $currencies);

    $currency_symbol = isset($symbols[$currency]) ? $symbols[$currency] : '';

    return apply_filters('chama_currency_symbol', $currency_symbol, $currency);
}

function chama_format_currency(
    $amount,
    $currency = '',
    $show_symbol = true,
    $convert_zero_decimal = true
) {
    if (empty($currency)) {
        $currency = strtolower(get_option('chama_stripe_currency'));
    }

    $symbol          = chama_get_currency_symbol($currency);
    $position        = get_option('chama_currency_position');
    $is_zero_decimal = chama_is_zero_decimal($currency);

    if ($convert_zero_decimal) {
        $amount = $is_zero_decimal
        ? $amount
        : chama_convert_amount_to_dollars($amount);
    }

    $amount = number_format(
        floatval($amount),
        chama_get_decimal_places($currency),
        chama_get_decimal_separator(),
        chama_get_thousand_separator()
    );

    $amount = apply_filters('chama_formatted_amount', $amount);
    $amount = chama_trim_trailing_zeroes($amount);

    if ($show_symbol) {
        if ('left' === $position) {
            return $symbol . $amount;
        } elseif ('left_space' === $position) {
            return $symbol . ' ' . $amount;
        } elseif ('right' === $position) {
            return $amount . $symbol;
        } elseif ('right_space' === $position) {
            return $amount . ' ' . $symbol;
        }
    }

    return $amount;
}

function chama_is_zero_decimal($currency = '')
{
    $zero_decimal_currencies = chama_get_zero_decimal_currencies();

    if (empty($currency)) {
        $currency = get_option('chama_stripe_currency');
    }

    if (array_key_exists(strtolower($currency), $zero_decimal_currencies)) {
        return true;
    }

    return false;
}
function chama_get_zero_decimal_currencies()
{
    $currencies = [
        'bif' => esc_html__('Burundian Franc', 'chama'),
        'clp' => esc_html__('Chilean Peso', 'chama'),
        'djf' => esc_html__('Djiboutian Franc', 'chama'),
        'gnf' => esc_html__('Guinean Franc', 'chama'),
        'jpy' => esc_html__('Japanese Yen', 'chama'),
        'kmf' => esc_html__('Comorian Franc', 'chama'),
        'krw' => esc_html__('South Korean Won', 'chama'),
        'mga' => esc_html__('Malagasy Ariary', 'chama'),
        'pyg' => esc_html__('Paraguayan Guaraní', 'chama'),
        'rwf' => esc_html__('Rwandan Franc', 'chama'),
        'vnd' => esc_html__('Vietnamese Dong', 'chama'),
        'vuv' => esc_html__('Vanuatu Vatu', 'chama'),
        'xaf' => esc_html__('Central African Cfa Franc', 'chama'),
        'xof' => esc_html__('West African Cfa Franc', 'chama'),
        'xpf' => esc_html__('Cfp Franc', 'chama'),
    ];

    $currencies = apply_filters('chama_zero_decimal_currencies', $currencies);

    return $currencies;
}

function chama_convert_amount_to_dollars($amount)
{

    $amount = chama_unformat_currency($amount);

    if (! chama_is_zero_decimal()) {
        $amount = round(intval($amount) / 100, chama_get_decimal_places());
    }

    return $amount;
}

function chama_get_decimal_places($currency = '')
{

    $decimal_places = 2;

    if (empty($currency)) {
        $currency = strtolower(get_option('chama_stripe_currency'));
    }

    if (chama_is_zero_decimal($currency)) {
        $decimal_places = 0;
    }

    $decimal_places = apply_filters(
        'chama_decimal_places',
        $decimal_places,
        $currency
    );

    return intval($decimal_places);
}

function chama_unformat_currency($amount)
{

    // Nothing neesd to be replaced if we are using a number already.
    if (is_float($amount) || is_int($amount)) {
        return abs($amount);
    }

    // Remove thousand separator.
    $amount = str_replace(chama_get_thousand_separator(), '', $amount);

    // Replace decimal separator with an actual decimal point to allow converting to float.
    $amount = str_replace(chama_get_decimal_separator(), '.', $amount);

    return abs(floatval($amount));
}

function chama_get_decimal_separator()
{
    $separator = 'yes' === get_option('chama_separator')
    ? ','
    : '.';

    $separator = apply_filters('chama_decimal_separator', $separator);

    return $separator;
}

function chama_get_thousand_separator()
{
    $separator = 'yes' === get_option('chama_separator')
    ? '.'
    : ',';

    $separator = apply_filters('chama_thousand_separator', $separator);

    return $separator;
}

function chama_get_currency_minimum($currency)
{
    $minimum  = 100;
    $currency = strtolower($currency);

    $minimum = apply_filters('chama_get_currency_minimum', $minimum, $currency);

    return $minimum;
}

function chama_sanitize_date($date)
{

    // General sanitization, to get rid of malicious scripts or characters
    $date = sanitize_text_field($date);

    // Validation to see if it is the right format
    if (chama_validate_date($date)) {
        return $date;
    }

    // default value, to return if checks have failed
    return '1900-12-12';
}

/**
 * Validates that a date string is in the right format
 * default format is 'Y-m-d' to test for time only in this format '07/23/2024'
 * but you can pass a new format to test against other formats
 * other formats here https://www.lehelmatyus.com/1003/android-change-date-format-from-utc-to-local-time
 *
 * @return bool
 */

function chama_validate_date($date, $format = 'Y-m-d')
{
    // Create the format date
    $d = DateTime::createFromFormat($format, $date);

    // Return the comparison
    return $d && $d->format($format) === $date;
}

function chama_sanitize_money($value)
{
    $value = str_replace(',', '', number_format(floatval($value), 2));
    return $value;
}
function chama_sanitize_integer($value)
{
         // Convert to integer
    $value = intval( $value );

    // Optionally enforce a minimum or maximum
    if ( $value < 0 ) {
        $value = 0;
    }

    return $value;
}
function chama_user_register($user_id, $override = false)
{
    $optout_code = wp_generate_password(20, false); // Secure, random string
    update_user_meta($user_id, 'optout_code', $optout_code);
    update_user_meta($user_id, 'is_email_verified', 0);
    update_user_meta($user_id, 'newsletter_optin', 1);
    $user          = get_userdata($user_id);
    $require_login = get_option('chama_require_login');
    $require_email_verification = get_option('chama_require_email_verification');
    //send only to members
    if (in_array('chama_temp', (array) $user->roles) || $override || $require_login || $require_email_verification) {
        $email             = $user->user_email;
        $verification_code = wp_generate_password(20, false); // Secure, random string
        update_user_meta($user_id, 'email_verification_code', $verification_code);

        // Create the verification link
        $verification_link = add_query_arg(
            [
                'uid'  => $user_id,
                'code' => $verification_code,
            ],
            CHAMA_VERIFY_EMAIL_URL
        );

        // Send the email
        $from        = sprintf("%s <%s>", CHAMA_FROM_NAME, CHAMA_FROM_EMAIL);
        $from_header = 'From: ' . $from;
        $headers     = ['Content-Type: text/html; charset=UTF-8', $from_header];
        $subject     = 'Verify Your Email Address';
        $message     = 'Please click the following link to verify your email address: ' . "\r\n\r\n";
        $message .= '<a href="' . $verification_link . '">' . $verification_link . ' </a>' . "\r\n";
        chama_send_email($email, $subject, $message, $headers);
    }

}

function chama_get_active_pages()
{
    $display_hub_page          = get_option('chama_display_hub');
    $display_donate_page       = get_option('chama_display_donate');
    $display_membership_page   = get_option('chama_display_membership');
    $display_crowdfunding_page = get_option('chama_display_crowdfunding');
    $display_commissions_page  = get_option('chama_display_commissions');
    $pages_list                = [];
    if ($display_hub_page) {
        if (chama_get_page_data('chama_hub_page')) {
            $pages_list[] = chama_get_page_data('chama_hub_page');
        }
    }
    if ($display_donate_page) {
        if (chama_get_page_data('chama_donate_page')) {
            $pages_list[] = chama_get_page_data('chama_donate_page');
        }
    }
    if ($display_membership_page) {
        if (chama_get_page_data('chama_membership_page')) {
            $pages_list[] = chama_get_page_data('chama_membership_page');
        }
    }
    if ($display_crowdfunding_page) {
        if (chama_get_page_data('chama_crowdfunding_page')) {
            $pages_list[] = chama_get_page_data('chama_crowdfunding_page');
        }
    }
    if ($display_commissions_page) {
        if (chama_get_page_data('chama_commissions_page')) {
            $pages_list[] = chama_get_page_data('chama_commissions_page');
        }

    }
    return $pages_list;
}
function chama_get_page_data($option)
{
    $page_id = get_option($option);
    $page    = get_post($page_id);
    if ($page) {
        $slug      = $page->post_name;
        $permalink = get_permalink($page_id);
        //prevent caching
        $permalink = add_query_arg(
            [
                'uid' => uniqid(),
            ],
            $permalink
        );
        return ['id' => $page->ID, 'title' => $page->post_title, 'link' => $permalink, 'slug' => $slug];
    } else {
        return [];
    }

}
function chama_apply_seperator_rule($currency, $price)
{
    $currency = strtolower($currency);

    $price = apply_filters('chama_apply_seperator_rule', $price, $currency);

    return $price;
}
function chama_get_formatted_price($price)
{
    $currency             = get_option('chama_stripe_currency');
    $symbol               = chama_get_currency_symbol($currency);
    $currency_position    = get_option('chama_currency_position');
    $price_with_seperator = chama_apply_seperator_rule($currency, $price);
    $formatted_amount     = chama_format_currency(
        $price_with_seperator,
        $currency,
        false,
        true
    );
    $display_amount = '';
    switch ($currency_position) {
        case 'left':
            $display_amount = sprintf('%1$s%2$s', $symbol, $formatted_amount);
            break;
        case 'right':
            $display_amount = sprintf('%1$s%2$s', $formatted_amount, $symbol);
            break;
        case 'left_space':
            $display_amount = sprintf('%1$s %2$s', $symbol, $formatted_amount);
            break;
        case 'right_space':
            $display_amount = sprintf('%1$s %2$s', $formatted_amount, $symbol);
            break;
        default:
            break;
    }
    return $display_amount;
}
function chama_trim_trailing_zeroes($number)
{
    $separator = 'yes' === get_option('chama_separator')
    ? ','
    : '.';
    return strpos($number, $separator) !== false ? rtrim(rtrim($number, '0'), $separator) : $number;
}

function chama_send_email($to, $subject, $message, $headers)
{
    $template = chama_get_email_template();
    $body     = str_replace("[subject]", $subject, $template);
    $body     = str_replace("[message]", $message, $body);
    wp_mail($to, $subject, $body, $headers);
}
if (! function_exists('chama_add_application_fee')):
    function chama_add_application_fee($args, $is_subscription = false)
{
        $mode = chama_is_live_mode() ? 'live' : 'test';
        if (empty($args) || (empty($args['amount']) && empty($args['items']))) {
            return $args;
        }

        $account_country      = get_option('chama_stripe_' . $mode . '_account_country');
        $restricted_countries = [
            'AG', 'AL', 'AM', 'AO', 'AR', 'AZ', 'BA', 'BB', 'BD', 'BF', 'BH', 'BJ', 'BN', 'BO', 'BR', 'BS', 'BT', 'BW', 'BZ', 'CI',
            'CL', 'CO', 'CR', 'CV', 'DJ', 'DM', 'DO', 'DZ', 'EC', 'EG', 'ET', 'FJ', 'FM', 'GA', 'GD', 'GE', 'GH', 'GM', 'GN', 'GQ',
            'GT', 'GY', 'HN', 'ID', 'IL', 'IN', 'IS', 'JM', 'JO', 'KE', 'KG', 'KH', 'KI', 'KR', 'KW', 'KZ', 'LA', 'LC', 'LK', 'LS',
            'MA', 'MC', 'MD', 'ME', 'MG', 'MH', 'MK', 'MN', 'MO', 'MR', 'MU', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NE', 'NG', 'OM', 'PA',
            'PE', 'PG', 'PH', 'PK', 'PY', 'QA', 'RS', 'RW', 'SA', 'SB', 'SC', 'SL', 'SM', 'SN', 'SR', 'SV', 'TG', 'TH', 'TJ', 'TL',
            'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UY', 'UZ', 'VC', 'VN', 'WS', 'ZA', 'ZM'];

        if (in_array($account_country, $restricted_countries)) {
            return $args;
        }

        $fee_percentage = 3;
        if ($is_subscription) {
            $args['application_fee_percent'] = $fee_percentage;
        } else {
            $args['application_fee_amount'] = floor($args['amount'] * round(floatval($fee_percentage), 2) / 100);
        }

        return $args;

    }
endif;

function chama_get_email_template()
{
    $site_title = get_bloginfo('name');
    $branding   = get_option('chama_email_logo') ? '<img src="' . esc_attr(get_option('chama_email_logo')) . '" />' : '<h3 style="color: #000000;margin:0;padding: 28px 24px;text-align:center; font-family: \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;font-size:24px;font-weight: 500;line-height: 1.2">' . $site_title . '</h3>';
    $info       = '<html><head><title>' . $site_title . '</title></head>';
    $info .= '<body style="margin: 0; padding: 0px 0px 150px 0px; background-color:#e7e7e7;"><div style="width:100%;margin:0;padding: 84px 0 50px 0">';
    $info .= '<table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody>';
    $info .= '<tr><td align="center" valign="top">';
    $info .= $branding;
    $info .= '<table border="0" cellpadding="0" cellspacing="0" width="100%" style="box-shadow:0 0 0 1px #f3f3f3 !important;border-radius:7px !important;background-color: #ffffff;border: 1px solid #e9e9e9;border-radius:7px !important;padding: 20px; margin-top: 20px;"><tbody>';

    //start header row
    $info .= '<tr><td align="center" valign="top">';
    $info .= '<!-- Header -->';
    $info .= '<table border="0" cellpadding="0" cellspacing="0" width="600" id="template_header" style="color: #00000;border-top-left-radius:3px !important;border-top-right-radius:3px !important;border-bottom: 0;font-weight:bold;line-height:100%;text-align: center;vertical-align:middle" bgcolor="#ffffff">';
    $info .= '<tbody><tr>';
    $info .= '<td>';
    $info .= '<h1 style="color: #000000;margin:0;padding: 28px 24px;font-family: \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;font-size:32px;font-weight: 500;line-height: 1.2">[subject]</h1>';
    $info .= '</td></tr>';
    $info .= '</tbody></table>';
    $info .= '<!-- End Header -->';
    $info .= '</td></tr>';
    //end header row

    //start body row
    $info .= '<tr><td align="center" valign="top">';
    $info .= '<!-- Body -->';
    $info .= '<table border="0" cellpadding="0" cellspacing="0" width="600" id="template_body">';
    $info .= ' <tbody><tr>';
    $info .= '<td valign="top" style="border-radius:3px !important;font-family: \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif">';
    $info .= '<!-- Content -->';
    $info .= '<table border="0" cellpadding="20" cellspacing="0" width="100%">';
    $info .= '<tbody><tr>';
    $info .= '<td valign="top">';
    $info .= '<div style="color: #000000;font-size:14px;font-family: \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;line-height:150%;text-align:left">';
    $info .= '[message]';
    $info .= '</div>';
    $info .= '</td></tr>';
    $info .= '</tbody></table>';
    $info .= '<!-- End Content -->';
    $info .= '</td></tr>';
    $info .= '</tbody></table>';
    $info .= '<!-- End Body -->';
    $info .= '</td></tr>';
    //end body row

    //start footer row
    $info .= '<tr><td align="center" valign="top"><!-- Footer -->';

    $info .= '<table border="0" cellpadding="10" cellspacing="0" width="600"  style="border-top:0">';
    $info .= '<tbody><tr>';
    $info .= '<td valign="top">';
    $info .= '<table border="0" cellpadding="10" cellspacing="0" width="100%">';
    $info .= '<tbody><tr>';
    $info .= '<td align="center" style="color: #000000;font-family: \'Helvetica Neue\', Helvetica, Arial, \'Lucida Grande\', sans-serif;font-size:11px;padding:30px 0px 0px 0px;text-align:center">';
    $info .= '<p><a href="' . esc_url(home_url()) . '">Chama</a></p>';
    $info .= '</td>';
    $info .= '</tr>';
    $info .= '</tbody></table>';
    $info .= '</td>';
    $info .= '</tr>';
    $info .= '</tbody></table>';

    $info .= ' <!-- End Footer --></td></tr>';
    //end  footer row
    $info .= '</tbody></table>';
    $info .= '</td></tr>';

    $info .= '</tbody></table>';

    $info .= '</div></body></html>';

    return $info;
}
function chama_add_user_to_role($user, $role, $update_analytics = false, $tier_id = 0)
{
    if ($user && ! in_array($role, (array) $user->roles)) {
        $user->add_role($role);

        //update supporter analytics
        if ($update_analytics) {
            $current_analytics_total = 0;
            switch ($role) {
                case 'chama_donor':
                    $analytics_option = 'chama_total_donors';
                    break;
                case 'chama_member':
                    $analytics_option = 'chama_total_members';
                    break;
                case 'chama_funder':
                    $analytics_option = 'chama_total_funders';
                    break;
                case 'chama_comissioner':
                    $analytics_option = 'chama_total_commissioners';
                    break;
                default:
            }
            $current_analytics_total = get_option($analytics_option) ? get_option($analytics_option) : 0;
            $new_analytics_total     = $current_analytics_total + 1;
            update_option($analytics_option, $new_analytics_total);
        }

        //update tier totals
        if ($tier_id) {
            $current_total_subscribers = get_post_meta($tier_id, 'total_subscribers', true) ? get_post_meta($tier_id, 'total_subscribers', true) : 0;
            $new_total_subscribers     = $current_total_subscribers + 1;
            update_post_meta($tier_id, 'total_subscribers', $new_total_subscribers);
        }

    }
}
function chama_remove_user_from_role($user, $role, $update_analytics = false, $tier_id = 0)
{
    if ($user && in_array($role, (array) $user->roles)) {
        $user->remove_role($role);

        //update supporter analytics
        if ($update_analytics) {
            $current_analytics_total = 0;
            switch ($role) {
                case 'chama_donor':
                    $analytics_option = 'chama_total_donors';
                    break;
                case 'chama_member':
                    $analytics_option = 'chama_total_members';
                    break;
                case 'chama_funder':
                    $analytics_option = 'chama_total_funders';
                    break;
                case 'chama_comissioner':
                    $analytics_option = 'chama_total_commissioners';
                    break;
                default:
            }
            $current_analytics_total = get_option($analytics_option) ? get_option($analytics_option) : 0;
            $new_analytics_total     = $current_analytics_total - 1;
            update_option($analytics_option, $new_analytics_total);

            //update tier totals
            if ($tier_id) {
                $current_total_subscribers = get_post_meta($tier_id, 'total_subscribers', true) ? get_post_meta($tier_id, 'total_subscribers', true) : 0;
                $new_total_subscribers     = $current_total_subscribers - 1;
                update_post_meta($tier_id, 'total_subscribers', $new_total_subscribers);
            }
        }

    }
}

/**
 * Retrieves the serial number if available
 *
 * @since 1.7.8
 * @return string|bool
 */
function chama_get_serial_number()
{

    if (is_multisite()) {
        $serial_number = get_site_option('chama_serial_number');

        // fallback to regular option if this is empty
        if (empty($serial_number)) {
            $serial_number = get_option('chama_serial_number');
        }

    } else {
        $serial_number = get_option('chama_serial_number');
    }

    return $serial_number === false ? false : $serial_number;

}

function chama_get_serial_number_status()
{

    if (is_multisite()) {
        return get_site_option('chama_license_status');
    } else {
        return get_option('chama_license_status');
    }

}
function chama_allowed_tags()
{

    $allowed_tags = [
        'a'          => [
            'class' => [],
            'href'  => [],
            'rel'   => [],
            'title' => [],
        ],
        'abbr'       => [
            'title' => [],
        ],
        'b'          => [],
        'blockquote' => [
            'cite' => [],
        ],
        'cite'       => [
            'title' => [],
        ],
        'code'       => [],
        'del'        => [
            'datetime' => [],
            'title'    => [],
        ],
        'dd'         => [],
        'div'        => [
            'class' => [],
            'title' => [],
            'style' => [],
        ],
        'dl'         => [],
        'dt'         => [],
        'em'         => [],
        'h1'         => [],
        'h2'         => [],
        'h3'         => [],
        'h4'         => [],
        'h5'         => [],
        'h6'         => [],
        'i'          => [],
        'img'        => [
            'alt'    => [],
            'class'  => [],
            'height' => [],
            'src'    => [],
            'width'  => [],
        ],
        'li'         => [
            'class' => [],
        ],
        'ol'         => [
            'class' => [],
        ],
        'p'          => [
            'class' => [],
        ],
        'q'          => [
            'cite'  => [],
            'title' => [],
        ],
        'span'       => [
            'class' => [],
            'title' => [],
            'style' => [],
        ],
        'strike'     => [],
        'strong'     => [],
        'ul'         => [
            'class' => [],
        ],
    ];

    return $allowed_tags;
}
/*=============================================SUBSCRIPTION FUNCTIONS=============================================*/
function chama_handle_subscription_deactivation($stripe_subscription, $webhook_call = false, $status = 'canceled')
{
    try {
        $mode       = chama_is_live_mode() ? 'live' : 'test';
        $secret_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;
        if ($secret_key) {
            $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                $secret_key // API Secret here
            );
        }
        $user_id                     = 0;
        $stripe_subscription_id      = $stripe_subscription->id;
        $stripe_customer_id          = $stripe_subscription->customer;
        $tier_id                     = $stripe_subscription->metadata->tier_id;
        $stripe_current_period_start = $stripe_current_period_end = '';
        if ($stripe_subscription->current_period_start) {
            $stripe_current_period_start = gmdate("F, j, Y", $stripe_subscription->current_period_start);
        }
        if ($stripe_subscription->current_period_end) {
            $stripe_current_period_end = gmdate("F, j, Y", $stripe_subscription->current_period_end);
        }

        $role = 'chama_member';
        /*=============================================GET STRIPE CUSTOMER=============================================*/
        $stripe_customer = $stripe->customers->retrieve($stripe_customer_id, []);
        if ($stripe_customer && $stripe_customer->metadata->user_id) {
            $user_id = $stripe_customer->metadata->user_id;
        }

        /*=============================================UPDATE PERIODS=============================================*/
        if ($stripe_current_period_start) {
            update_user_meta($user_id, 'chama_subscription_current_period_start', $stripe_current_period_start);
        }
        if ($stripe_current_period_end) {
            update_user_meta($user_id, 'chama_subscription_current_period_end', $stripe_current_period_end);
        }

        chama_update_subscription_transactions($stripe_subscription_id, $status);

        /*=============================================REMOVE USER FROM MEMBERSHIP=============================================*/
        if ($user_id && $tier_id && $status == 'canceled') {
            chama_remove_user_membership($user_id, $tier_id);
        }

        if ($webhook_call) {
            die('Succesfully deactivated subscripition.');
        }
    } catch (Exception $e) {

        die(esc_html($e->getMessage()));
    }

}

function chama_handle_subscription_resumed($stripe_subscription, $webhook_call = false)
{
    try {
        $mode       = chama_is_live_mode() ? 'live' : 'test';
        $secret_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;

        if ($secret_key) {
            $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                $secret_key // API Secret here
            );
            $stripe_subscription_id      = $stripe_subscription->id;
            $stripe_subscription_status  = $stripe_subscription->status;
            $stripe_customer_id          = $stripe_subscription->customer;
            $stripe_current_period_start = $stripe_current_period_end = '';
            $tier_id                     = $stripe_subscription->metadata->tier_id;
            $subscription                = $subscription_args                = null;
            if ($stripe_subscription->current_period_start) {
                $stripe_current_period_start = gmdate("F, j, Y", $stripe_subscription->current_period_start);
            }
            if ($stripe_subscription->current_period_end) {
                $stripe_current_period_end = gmdate("F, j, Y", $stripe_subscription->current_period_end);
            }
            if ($stripe_subscription_status == 'active') {
                $role = 'chama_member';
                /*=============================================GET STRIPE CUSTOMER=============================================*/
                $stripe_customer = $stripe->customers->retrieve($stripe_customer_id, []);
                if ($stripe_customer && $stripe_customer->metadata->user_id) {
                    $user_id = $stripe_customer->metadata->user_id;
                }
                /*=============================================ADD USER TO ROLE=============================================*/
                if ($user_id) {
                    $user = $user_id ? get_user_by('id', $user_id) : false;
                    if ($user) {
                        chama_add_user_to_role($user, $role, $tier_id);
                    }
                }
                /*=============================================UPDATE PERIODS=============================================*/
                if ($stripe_current_period_start) {
                    update_user_meta($user_id, 'chama_subscription_current_period_start', $stripe_current_period_start);
                }
                if ($stripe_current_period_end) {
                    update_user_meta($user_id, 'chama_subscription_current_period_end', $stripe_current_period_end);
                }
                /*=============================================UPDATE SUBSCRIPTION STATUS=============================================*/
                update_user_meta($user_id, 'chama_subscription_status', 'active');
                chama_update_subscription_transactions($stripe_subscription_id, 'active');
            }
        }
        if ($webhook_call) {
            die('Succesfully reactivated subscripition.');
        }

    } catch (Exception $e) {

        die(esc_html($e->getMessage()));
    }
}

function chama_cancel_current_subscription($user_id, $switched_tier = false, $webhook_call = false)
{
    try {
        $mode       = chama_is_live_mode() ? 'live' : 'test';
        $secret_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;

        if ($secret_key) {
            $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                $secret_key // API Secret here
            );
            $user                      = $user_id ? get_user_by('id', $user_id) : false;
            $user_email                = $user ? $user->user_email : '';
            $stripe_subscription_id    = get_user_meta($user_id, 'chama_stripe_subscription_id', true);
            $stripe_current_period_end = get_user_meta($user_id, 'chama_subscription_current_period_end', true);
            $description               = '';
            $from                      = sprintf("%s <%s>", CHAMA_FROM_NAME, CHAMA_FROM_EMAIL);
            $from_header               = 'From: ' . $from;
            $headers                   = ['Content-Type: text/html; charset=UTF-8', $from_header];
            $supporter_message         = $admin_message         = $description         = '';
            $previously_cancelled      = false;
            /*=============================================CANCEL SUBSCRIPTION IN STRIPE=============================================*/
            if ($stripe_subscription_id) {
                $stripe_subscription = $stripe->subscriptions->retrieve($stripe_subscription_id, []);
                if ($stripe_subscription->status == 'active') {
                    $stripe->subscriptions->cancel($stripe_subscription_id, []);
                } else {
                    $previously_cancelled = true;
                }

            }
            /*=============================================CANCEL ALL DATABASE TRANSACTIONS=============================================*/
            if ($stripe_subscription_id) {
                chama_update_subscription_transactions($stripe_subscription_id, 'canceled');
            }
            /*=============================================SEND EMAIL=============================================*/
            if ($user_email && $stripe_subscription_id && $stripe_current_period_end && ! $previously_cancelled) {

                $description = $switched_tier ? '<strong>Reason for cancellation:</strong> Signed up for different membership' : sprintf('Your subscription will remain active until <strong>%s</strong>', $stripe_current_period_end);
                if (get_option('chama_supporter_enable_payment_notification')) {
                    if (get_option('chama_subscription_cancellation_template')) {
                        $supporter_message = get_option('chama_subscription_cancellation_template');
                        $supporter_message = wpautop($supporter_message);

                        //replace subscription email template variables
                        $today = gmdate('Y-m-d');
                        foreach ([
                            "{description}" => $description,
                        ] as $k => $v) {$supporter_message = str_replace($k, $v, $supporter_message);}

                        $supporter_subject = 'Your subscription has been cancelled';

                        if ($user_email && get_option('chama_supporter_enable_payment_notification')) {
                            chama_send_email($user_email, $supporter_subject, $supporter_message, $headers);
                        }

                    }
                }
            }
        }
        /*  if ($webhook_call) {
    die('Succesfully cancelled subscripition.');
    } */

    } catch (Exception $e) {

        die(esc_html($e->getMessage()));
    }
}

function chama_update_subscription_transactions($stripe_subscription_id, $status)
{
    try {
        global $wpdb;
        $result = $wpdb->query(
            $wpdb->prepare("
        UPDATE {$wpdb->postmeta}  pm
        SET pm.meta_value = %s
        WHERE pm.meta_key = 'chama_subscription_status' AND pm.post_id IN
        (
        SELECT post_id FROM
        (
        SELECT post_id
        FROM {$wpdb->postmeta}
        WHERE meta_key = 'chama_stripe_subscription_id' AND meta_value = %s
        ) as t
        )
        ",
                [$status, $stripe_subscription_id]
            )
        );
    } catch (Exception $e) {

        die(esc_html($e->getMessage()));
    }
}
function chama_delete_transactions($user_id)
{
    try {
        global $wpdb;
        // Delete all  posts and related meta data.
        $result = $wpdb->query(
            $wpdb->prepare("
        DELETE FROM {$wpdb->posts}
        WHERE post_type IN ('chama_donation','chama_subscription','chama_fund','chama_com_order')
        AND ID IN
        (SELECT post_id FROM {$wpdb->postmeta} where meta_key = 'chama_user_id' and meta_value = %d)
        ",
                $user_id
            )
        );
        $wpdb->query("DELETE meta FROM {$wpdb->postmeta} meta LEFT JOIN {$wpdb->posts} posts ON posts.ID = meta.post_id WHERE posts.ID IS NULL;");
    } catch (Exception $e) {

        die(esc_html($e->getMessage()));
    }
}
function chama_remove_user_membership($user_id, $tier_id)
{
    $role = 'chama_member';
    if ($user_id) {
        $user = $user_id ? get_user_by('id', $user_id) : false;
        if ($user) {
            chama_remove_user_from_role($user, $role, true, $tier_id);
            update_user_meta($user_id, 'chama_subscription_status', 'canceled');
            update_user_meta($user_id, 'chama_tier_id', false);
            update_user_meta($user_id, 'chama_tier_description', false);
            update_user_meta($user_id, 'chama_subscription_level', 0);
            update_user_meta($user_id, 'chama_stripe_subscription_id', false);
        }
    }
}

function chama_pause_user_membership($user_id)
{
    $role = 'chama_member';
    if ($user_id) {
        $user = $user_id ? get_user_by('id', $user_id) : false;
        if ($user) {
            if ($user && in_array($role, (array) $user->roles)) {
                $user->remove_role($role);
            }
            update_user_meta($user_id, 'chama_subscription_status', 'paused');
        }
    }
}
function chama_resume_user_membership($user_id)
{
    $role = 'chama_member';
    if ($user_id) {
        $user = $user_id ? get_user_by('id', $user_id) : false;
        if ($user) {
            if ($user && ! in_array($role, (array) $user->roles)) {
                $user->add_role($role);
            }
            update_user_meta($user_id, 'chama_subscription_status', 'active');
        }
    }
}

function chama_get_tier_levels()
{
    global $wpdb;
    $tiers = $wpdb->get_results("SELECT ID, post_title, meta_value FROM $wpdb->posts p INNER JOIN $wpdb->postmeta pm ON p.ID = pm.post_id WHERE p.post_type = 'chama_tier' AND p.post_status = 'publish' AND pm.meta_key = 'tier_price' ORDER BY pm.meta_value * 1");

    $tier_list         = [];
    $tier_list['']     = 'Everyone';
    $tier_list['0']    = 'Free - $0';
    $tier_list['0.01'] = 'Any paying member';
    foreach ($tiers as $tier) {
        $tier_list[$tier->meta_value] = $tier->post_title;
    }
    return $tier_list;
}
function chama_get_tier_level_from_amount($amount = '')
{

    $tier_list = chama_get_tier_levels();

    $labels = apply_filters('chama_tier_labels', $tier_list);

    $tier_label = isset($labels[$amount]) ? $labels[$amount] : 'Everyone';

    return apply_filters('chama_tier_label', $tier_label, $amount);
}

function chama_process_incomplete_payment($payment_id, $cpt, $payment_intent, $user_id, $show_notice)
{
    $role             = $commission_shipping_address             = '';
    $currency         = $payment_intent->currency;
    $currency_minimum = chama_get_currency_minimum($currency);
    $total_amount     = 0;

    if ($payment_intent->amount) {
        $total_amount_cents = sanitize_text_field($payment_intent->amount);
        $total_amount       = $total_amount_cents / $currency_minimum;
    }

    if ($payment_intent && $payment_intent->status === 'succeeded') {
        switch ($cpt) {
            case 'chama_donation':
                $role = 'chama_donor';
                /*=============================================ADD TO ACTIVE CAMPAIGN TOTAL=============================================*/
                chama_add_to_campaign($user_id, $payment_id, $total_amount, $cpt);
                break;
            case 'chama_subscription':
                /*=============================================UPDATE TIER SLOTS=============================================*/
                $subtract_from_tier_slots = ! get_post_meta($payment_id, $cpt . '_subtracted_from_slots', true);
                if ($subtract_from_tier_slots && $subtract_from_tier_slots > 0) {
                    $tier_id            = $payment_intent->metadata && $payment_intent->metadata->tier_id ? $payment_intent->metadata->tier_id : 0;
                    $current_tier_slots = 0;

                    if ($tier_id) {
                        if (get_post_meta($tier_id, 'member_limit', true)) {
                            $current_tier_slots = get_post_meta($tier_id, 'member_limit', true);
                            if ($current_tier_slots > 0) {
                                $new_tier_slots = $current_tier_slots - 1;
                                update_post_meta($tier_id, 'member_limit', $new_tier_slots);
                                update_post_meta($payment_id, $cpt . '_subtracted_from_slots', true);
                            }
                        }

                    }
                }
                /*=============================================ADD TO ACTIVE CAMPAIGN TOTAL=============================================*/
                chama_add_to_campaign($user_id, $payment_id, $total_amount, $cpt);
                break;
            case 'chama_fund':
                $role                  = 'chama_funder';
                $add_to_campaign_total = ! get_post_meta($payment_id, $cpt . '_included_in_total', true);
                /*=============================================ADD TO CAMPAIGN TOTAL=============================================*/
                $campaign_id = $payment_intent->metadata->campaign_id;
                chama_add_to_campaign($user_id, $payment_id, $total_amount, $cpt, $campaign_id);

                break;
            case 'chama_com_order':
                $role = 'chama_comissioner';
                /*=============================================SUBTRACT FROM SLOTS=============================================*/
                $subtract_from_commission_slots = ! get_post_meta($payment_id, $cpt . '_subtracted_from_slots', true);
                if ($subtract_from_commission_slots && $subtract_from_commission_slots > 0) {
                    $commission_id            = $payment_intent->metadata->commission_id;
                    $current_commission_slots = 0;

                    if ($commission_id) {
                        if (get_post_meta($commission_id, 'commission_limit', true)) {
                            $current_commission_slots = get_post_meta($commission_id, 'commission_limit', true);
                            $new_commission_slots     = $current_commission_slots - 1;
                            update_post_meta($commission_id, 'commission_limit', $new_commission_slots);
                            update_post_meta($payment_id, $cpt . '_subtracted_from_slots', true);
                        }

                    }
                }
                /*=============================================UPDATE SHIPPING ADDRESS=============================================*/
                if ($payment_intent->shipping) {

                    $commission_shipping_address                                         = [];
                    $commission_shipping_address[0]['commission_shipping_address_key']   = 'Name';
                    $commission_shipping_address[0]['commission_shipping_address_value'] = sanitize_text_field($payment_intent->shipping->name);
                    $commission_shipping_address[1]['commission_shipping_address_key']   = 'Address Line 1';
                    $commission_shipping_address[1]['commission_shipping_address_value'] = sanitize_text_field($payment_intent->shipping->address->line1);
                    $array_index                                                         = 2;
                    if ($payment_intent->shipping->address->line2) {
                        $commission_shipping_address[$array_index]['commission_shipping_address_key']   = 'Address Line 2';
                        $commission_shipping_address[$array_index]['commission_shipping_address_value'] = sanitize_text_field($payment_intent->shipping->address->line2);
                        $array_index++;
                    }
                    if ($payment_intent->shipping->address->state) {
                        $commission_shipping_address[$array_index]['commission_shipping_address_key']   = 'State';
                        $commission_shipping_address[$array_index]['commission_shipping_address_value'] = sanitize_text_field($payment_intent->shipping->address->state);
                        $array_index++;
                    }
                    $commission_shipping_address[$array_index]['commission_shipping_address_key']   = 'Postal Code';
                    $commission_shipping_address[$array_index]['commission_shipping_address_value'] = sanitize_text_field($payment_intent->shipping->address->postal_code);
                    $array_index++;

                    $country                                                                        = chama_get_country_from_code($payment_intent->shipping->address->country);
                    $commission_shipping_address[$array_index]['commission_shipping_address_key']   = 'Country';
                    $commission_shipping_address[$array_index]['commission_shipping_address_value'] = sanitize_text_field($country);
                    $array_index++;

                    update_post_meta($payment_id, $cpt . '_shipping_address', $commission_shipping_address);
                }
                break;
            default:
        }
        if ($role) {
            $user = $user_id ? get_user_by('id', $user_id) : false;
            chama_add_user_to_role($user, $role, false, 0);
        }

        update_post_meta($payment_id, 'chama_payment_status', 'complete');
        if ($show_notice) {
            $synced_label = '';
            switch ($cpt) {
                case 'chama_donation':
                    $synced_label = 'donation';
                    break;
                case 'chama_subscription':
                    $synced_label = 'subscription';
                    break;
                case 'chama_fund':
                    $synced_label = 'fund';

                    break;
                case 'chama_com_order':
                    $synced_label = 'commission order';
                    break;
                default:
            }

            $notification = 'The ' . $synced_label . ' has been synced with Stripe.';
            add_action('admin_notices', function () use ($notification) {
                echo '<div class="notice-success notice"><p>', esc_html($notification), '</p></div>';
            });
        }

    } else {
        if ($show_notice) {
            //show notice
            $notification = 'The ' . $cpt . ' has not yet been processed in Stripe. Login into your Stripe dashboard to confirm that the transaction was successfully processed and then try again.';
            add_action('admin_notices', function () use ($notification) {
                echo '<div class="notice-error notice"><p>', esc_html($notification), '</p></div>';
            });
        }
    }
}
function chama_process_incomplete_subscription($subscription_id, $cpt, $stripe_customer_id, $stripe_subscription_id, $tier_id, $tier_description, $subscription_level, $subscription, $user_id, $show_notice)
{
    $role = '';
    if ($subscription && $subscription->status === 'active') {
        $role = 'chama_member';

        $user = $user_id ? get_user_by('id', $user_id) : false;
        chama_add_user_to_role($user, $role, false, $tier_id);
        /*=============================================CANCEL PREVIOUS SUBSCRIPTION=============================================*/
        $current_user_stripe_subscription_id = get_user_meta($user_id, 'chama_stripe_subscription_id', true);
        $process_cancellation                = $stripe_subscription_id !== $current_user_stripe_subscription_id;
        if ($user_id && $process_cancellation) {
            chama_cancel_current_subscription($user_id, true, false);
        }

        /*=============================================UPDATE USER=============================================*/
        update_user_meta($user_id, 'chama_stripe_customer_id', $stripe_customer_id);
        update_user_meta($user_id, 'chama_stripe_subscription_id', $stripe_subscription_id);
        update_user_meta($user_id, 'chama_tier_id', $tier_id);
        update_user_meta($user_id, 'chama_tier_description', $tier_description);
        update_user_meta($user_id, 'chama_subscription_level', $subscription_level);
        update_user_meta($user_id, 'chama_subscription_status', 'active');
        update_post_meta($subscription_id, 'chama_subscription_status', 'active');

// Initialize timestamps
        $current_period_start_timestamp = null;
        $current_period_end_timestamp   = null;

// Old API properties
        if (! empty($subscription->current_period_start)) {
            $current_period_start_timestamp = $subscription->current_period_start;
        }
        if (! empty($subscription->current_period_end)) {
            $current_period_end_timestamp = $subscription->current_period_end;
        }

// New API properties fallback
        if (! $current_period_start_timestamp && ! empty($subscription->items->data[0]->current_period_start)) {
            $current_period_start_timestamp = $subscription->items->data[0]->current_period_start;
        }
        if (! $current_period_end_timestamp && ! empty($subscription->items->data[0]->current_period_end)) {
            $current_period_end_timestamp = $subscription->items->data[0]->current_period_end;
        }

        if ($current_period_start_timestamp) {
            $stripe_current_period_start = gmdate("F, j, Y", $current_period_start_timestamp);
            update_user_meta($user_id, 'chama_subscription_current_period_start', $stripe_current_period_start);
        }

        if ($current_period_end_timestamp) {
            $stripe_current_period_end = gmdate("F, j, Y", $current_period_end_timestamp);
            update_user_meta($user_id, 'chama_subscription_current_period_end', $stripe_current_period_end);
            update_post_meta($subscription_id, 'chama_subscription_renewal_date', $stripe_current_period_end);
        }

        //update payment method
        $secret_key = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;

        if ($secret_key) {
            $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
                $secret_key // API Secret here
            );
            $payment_methods = $stripe->paymentMethods->all([
                'type'     => 'card',
                'limit'    => 1,
                'customer' => $stripe_customer_id,
            ]);

            if ($payment_methods) {
                $latest_payment_method    = $payment_methods->data[0];
                $payment_method_id        = $latest_payment_method->id;
                $payment_method_brand     = $latest_payment_method->card->brand;
                $payment_method_exp_month = $latest_payment_method->card->exp_month;
                $payment_method_exp_year  = $latest_payment_method->card->exp_year;
                $payment_method_last4     = $latest_payment_method->card->last4;
                update_user_meta($user_id, 'chama_payment_method_id', $payment_method_id);
                update_user_meta($user_id, 'chama_payment_method_brand', ucfirst($payment_method_brand));
                update_user_meta($user_id, 'chama_payment_method_expiration', $payment_method_exp_month . '/' . $payment_method_exp_year);
                update_user_meta($user_id, 'chama_payment_method_last4', 'Last 4 digits:' . $payment_method_last4);
            }
        }

        //show notice
        if ($show_notice) {
            $notification = 'The subscription has been synced with Stripe.';
            add_action('admin_notices', function () use ($notification) {
                echo '<div class="notice-success notice"><p>', esc_html($notification), '</p></div>';
            });
        }
    } else {
        //show notice
        switch ($subscription->status) {
            case "incomplete":
                $notification = "Stripe has not completed the activation of this subscription. Login into your Stripe dashboard to confirm that the subscription has been activated and then try again.";
                break;
            case "canceled":
                update_post_meta($subscription_id, 'chama_subscription_status', 'canceled');
                chama_update_subscription_transactions($stripe_subscription_id, 'canceled');
                $notification = "This subscripiton has been canceled in Stripe";
                break;
            default:
                $notification = "This subscription is not active in Stripe. Login into your Stripe dashboard to confirm that the subscription is active and then try again.";
        }
        if ($show_notice) {
            add_action('admin_notices', function () use ($notification) {
                echo '<div class="notice-error notice"><p>', esc_html($notification), '</p></div>';
            });
        }
    }

}
/**
 * Update user with Stripe Customer ID
 */
function chama_user_add_stripe_customer_id($user_id, $user_email, $user_full_name)
{
    $stripe_customer_id = false;
    $secret_key         = chama_is_live_mode() ? CHAMA_STRIPE_LIVE_SECRET_KEY : CHAMA_STRIPE_TEST_SECRET_KEY;

    if ($secret_key) {
        $stripe = new \ChamaWP\Vendor\Stripe\StripeClient(
            $secret_key // API Secret here
        );
        //first search for user on stripe with email
        $query = $stripe->customers->search([
            'query' => 'email:\'' . $user_email . '\'',
        ]);
        foreach ($query->data as $key) {
            if (strcmp($key->email, $user_email) == 0) {
                $stripe_customer_id = $key->id;
                update_user_meta($user_id, 'chama_stripe_customer_id', $stripe_customer_id);
                break;
            }
        }

        //could not find user on stripe by email. Proceed to create a new customer on Stripe
        if (! $stripe_customer_id) {
            $new_customer = ['email' => $user_email];
            if ($user_full_name) {
                $new_customer["name"] = $user_full_name;
            }
            $customer_response  = $stripe->customers->create($new_customer);
            $stripe_customer_id = $customer_response->id;
            if ($stripe_customer_id) {
                $stripe->customers->update(
                    $stripe_customer_id,
                    ['metadata' => ['user_id' => $user_id]]
                );
            }
            update_user_meta($user_id, 'chama_stripe_customer_id', $stripe_customer_id);
        }
    }

    return $stripe_customer_id;
}
/**
 * Add subscription/donation amount to active campaign
 */
function chama_add_to_campaign($user_id, $post_id, $total_amount, $cpt, $campaign_id = 0)
{
    $current_campaign_total_amount = $current_campaign_total_backers = 0;
    if (! $campaign_id) {
        $campaign_id = get_option('chama_active_crowdfunding_campaign');
    }
    $add_to_campaign_total = ! get_post_meta($post_id, $cpt . '_included_in_total', true);
    if ($campaign_id && $add_to_campaign_total) {
        if (get_post_meta($campaign_id, 'campaign_current_total_amount', true)) {
            $current_campaign_total_amount = get_post_meta($campaign_id, 'campaign_current_total_amount', true);
        }
        if (get_post_meta($campaign_id, 'campaign_current_total_backers', true)) {
            $current_campaign_total_backers = get_post_meta($campaign_id, 'campaign_current_total_backers', true);
        }

        //initialize total amount with starting amount if zero
        if (! $current_campaign_total_amount) {
            $current_campaign_total_amount = get_post_meta($campaign_id, 'campaign_starting_amount', true) ? get_post_meta($campaign_id, 'campaign_starting_amount', true) : 0;
        }
        $add_to_backer_total = ! get_user_meta($user_id, 'chama_' . $campaign_id . '_included_in_total', true);

        if ($total_amount) {
            $new_total_amount = $total_amount + $current_campaign_total_amount;
            if ($add_to_backer_total) {
                $new_total_backers = $current_campaign_total_backers + 1;
                update_post_meta($campaign_id, 'campaign_current_total_backers', $new_total_backers);
                update_user_meta($user_id, 'chama_' . $campaign_id . '_included_in_total', true);
            }
            update_post_meta($campaign_id, 'campaign_current_total_amount', $new_total_amount);

        }

        update_post_meta($post_id, $cpt . '_included_in_total', true);
    }
}
/**
 * Generate allowed html tags for wp_kses()
 */
function chama_allowed_html()
{

    $allowed_atts = [
        'align'      => [],
        'class'      => [],
        'type'       => [],
        'id'         => [],
        'dir'        => [],
        'lang'       => [],
        'style'      => [],
        'xml:lang'   => [],
        'src'        => [],
        'alt'        => [],
        'href'       => [],
        'rel'        => [],
        'rev'        => [],
        'target'     => [],
        'novalidate' => [],
        'type'       => [],
        'value'      => [],
        'name'       => [],
        'tabindex'   => [],
        'action'     => [],
        'method'     => [],
        'for'        => [],
        'width'      => [],
        'height'     => [],
        'data'       => [],
        'title'      => [],
        'selected'   => [],
        'disabled'   => [],
        'checked'    => [],
    ];
    $allowed_tags['form']     = $allowed_atts;
    $allowed_tags['label']    = $allowed_atts;
    $allowed_tags['select']   = $allowed_atts;
    $allowed_tags['option']   = $allowed_atts;
    $allowed_tags['input']    = $allowed_atts;
    $allowed_tags['textarea'] = $allowed_atts;
    $allowed_tags['iframe']   = $allowed_atts;
    $allowed_tags['script']   = $allowed_atts;
    $allowed_tags['style']    = $allowed_atts;
    $allowed_tags['strong']   = $allowed_atts;
    $allowed_tags['small']    = $allowed_atts;
    $allowed_tags['table']    = $allowed_atts;
    $allowed_tags['span']     = $allowed_atts;
    $allowed_tags['abbr']     = $allowed_atts;
    $allowed_tags['code']     = $allowed_atts;
    $allowed_tags['pre']      = $allowed_atts;
    $allowed_tags['div']      = $allowed_atts;
    $allowed_tags['img']      = $allowed_atts;
    $allowed_tags['h1']       = $allowed_atts;
    $allowed_tags['h2']       = $allowed_atts;
    $allowed_tags['h3']       = $allowed_atts;
    $allowed_tags['h4']       = $allowed_atts;
    $allowed_tags['h5']       = $allowed_atts;
    $allowed_tags['h6']       = $allowed_atts;
    $allowed_tags['ol']       = $allowed_atts;
    $allowed_tags['ul']       = $allowed_atts;
    $allowed_tags['li']       = $allowed_atts;
    $allowed_tags['em']       = $allowed_atts;
    $allowed_tags['hr']       = $allowed_atts;
    $allowed_tags['br']       = $allowed_atts;
    $allowed_tags['tr']       = $allowed_atts;
    $allowed_tags['td']       = $allowed_atts;
    $allowed_tags['p']        = $allowed_atts;
    $allowed_tags['a']        = $allowed_atts;
    $allowed_tags['b']        = $allowed_atts;
    $allowed_tags['i']        = $allowed_atts;

    return $allowed_tags;
}
/**
 * Custom styles
 */
function chama_register_protected_content_style()
{
    // Register the stylesheet
    wp_register_style('chama-protected-content', CHAMA_ASSETS_URL . 'css/protection.css', [], CHAMA_VERSION, 'all');

}
add_action('init', 'chama_register_protected_content_style');

/**
 * Redirect after onboardings
 */
add_action('admin_init', 'chama_stripe_redirect_after_onboarding');

function chama_stripe_redirect_after_onboarding()
{
    // Determine if the request is authorized via nonce
    $valid_nonce = isset($_GET['chama_nonce']) && is_string($_GET['chama_nonce']) && wp_verify_nonce(sanitize_key($_GET['chama_nonce']), 'chama_stripe_nonce');

    $mode = chama_is_live_mode() ? 'live' : 'test';

    $account_id      = get_option('chama_stripe_' . $mode . '_account_id');
    $account_country = get_option('chama_stripe_' . $mode . '_account_country');
    $publishable_key = get_option('chama_stripe_' . $mode . '_publishable_key');
    $secret_key      = get_option('chama_stripe_' . $mode . '_secret_key');

    // Handle authorized GET overrides
    if ($valid_nonce) {
        if (isset($_GET['id'])) {
            $account_id = sanitize_text_field(wp_unslash($_GET['id']));
        }
        if (isset($_GET['country'])) {
            $account_country = sanitize_text_field(wp_unslash($_GET['country']));
        }
        if (isset($_GET['pk'], $_GET['sk'])) {
            $publishable_key = sanitize_text_field(wp_unslash($_GET['pk']));
            $secret_key      = sanitize_text_field(wp_unslash($_GET['sk']));
        }
    }

    // Handle resolution of onboarding process
    if ($valid_nonce && (isset($_GET['complete']) || isset($_GET['incomplete']))) {

        $is_complete = isset($_GET['complete']);
        if ($account_id && $secret_key && $publishable_key) {
            update_option('chama_stripe_' . $mode . '_account_id', sanitize_text_field($account_id));
            update_option('chama_stripe_' . $mode . '_publishable_key', sanitize_text_field($publishable_key));
            update_option('chama_stripe_' . $mode . '_secret_key', sanitize_text_field($secret_key));
            update_option('chama_stripe_' . $mode . '_account_completed_onboarding', $is_complete);

            wp_safe_redirect(admin_url('admin.php?page=chama-settings&tab=stripe'));
            exit;

        }
        if ($account_country) {
            update_option('chama_stripe_' . $mode . '_account_country', sanitize_text_field($account_country));
        }

    }

    // Handle disconnection of account
    if ($valid_nonce && isset($_GET['disconnected'])) {
        update_option('chama_stripe_' . $mode . '_account_id', false);
        update_option('chama_stripe_' . $mode . '_account_country', false);
        update_option('chama_stripe_' . $mode . '_publishable_key', false);
        update_option('chama_stripe_' . $mode . '_secret_key', false);
        update_option('chama_stripe_' . $mode . '_account_completed_onboarding', false);
        $account_id      = false;
        $publishable_key = false;
        $secret_key      = false;
        $connected       = false;

    }

}
/**
 * Current URL
 */
function chama_get_current_request_uri()
{
    $request_uri = '';
    if (isset($_SERVER['REQUEST_URI'])) {
        // Sanitize
        $request_uri = esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']));
    }

    return $request_uri;
}
/**
 * Hide default login
 */
add_action('init', 'chama_hide_default_login');
function chama_hide_default_login()
{
    $uri      = chama_get_current_request_uri() ?? '';
    $basename = basename(wp_parse_url($uri, PHP_URL_PATH));

    if ($basename === 'wp-login.php') {

        // Allow logout and logged-out
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Not processing form data, just controlling access to wp-login.php
        if ((isset($_GET['action']) && $_GET['action'] === 'logout') || (isset($_GET['loggedout']) && $_GET['loggedout'] === 'true')) {
            return;
        }

        // ✅ PHPCS: check REQUEST_METHOD is defined before using
        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
            // ✅ PHPCS: we are not processing the POST, just allowing WP to
            return;
        }

        // Allow admin users to view wp-login.php (e.g. for login)
        if (is_user_logged_in() && current_user_can('administrator')) {
            return;
        }

        // Allow password reset flows
        $allowed_actions = ['rp', 'resetpass', 'lostpassword'];
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Safe use, not processing user-submitted form data
        if (isset($_GET['action']) && in_array($_GET['action'], $allowed_actions, true)) {
            return;
        }

        // Redirect all others
        wp_redirect(CHAMA_LOGIN_URL);
        exit;
    }
}
