<?php

require_once 'cartable.civix.php';
// phpcs:disable
use CRM_Cartable_ExtensionUtil as E;
// phpcs:enable

/**
 * Implements hook_civicrm_config().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_config/
 */
function cartable_civicrm_config(&$config) {
  _cartable_civix_civicrm_config($config);
}

/**
 * Implements hook_civicrm_xmlMenu().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_xmlMenu
 */
function cartable_civicrm_xmlMenu(&$files) {
  _cartable_civix_civicrm_xmlMenu($files);
}

/**
 * Implements hook_civicrm_install().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_install
 */
function cartable_civicrm_install() {
  _cartable_civix_civicrm_install();
}

/**
 * Implements hook_civicrm_postInstall().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_postInstall
 */
function cartable_civicrm_postInstall() {
  _cartable_civix_civicrm_postInstall();
}

/**
 * Implements hook_civicrm_uninstall().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_uninstall
 */
function cartable_civicrm_uninstall() {
  _cartable_civix_civicrm_uninstall();
}

/**
 * Implements hook_civicrm_enable().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_enable
 */
function cartable_civicrm_enable() {
  _cartable_civix_civicrm_enable();
}

/**
 * Implements hook_civicrm_disable().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_disable
 */
function cartable_civicrm_disable() {
  _cartable_civix_civicrm_disable();
}

/**
 * Implements hook_civicrm_upgrade().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_upgrade
 */
function cartable_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
  return _cartable_civix_civicrm_upgrade($op, $queue);
}

/**
 * Implements hook_civicrm_managed().
 *
 * Generate a list of entities to create/deactivate/delete when this module
 * is installed, disabled, uninstalled.
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_managed
 */
function cartable_civicrm_managed(&$entities) {
  _cartable_civix_civicrm_managed($entities);
}

/**
 * Implements hook_civicrm_caseTypes().
 *
 * Add CiviCase types provided by this extension.
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_caseTypes
 */
function cartable_civicrm_caseTypes(&$caseTypes) {
  _cartable_civix_civicrm_caseTypes($caseTypes);
}

/**
 * Implements hook_civicrm_angularModules().
 *
 * Add Angular modules provided by this extension.
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_angularModules
 */
function cartable_civicrm_angularModules(&$angularModules) {
  // Auto-add module files from ./ang/*.ang.php
  _cartable_civix_civicrm_angularModules($angularModules);
}

/**
 * Implements hook_civicrm_alterSettingsFolders().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_alterSettingsFolders
 */
function cartable_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) {
  _cartable_civix_civicrm_alterSettingsFolders($metaDataFolders);
}

/**
 * Implements hook_civicrm_entityTypes().
 *
 * Declare entity types provided by this module.
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_entityTypes
 */
function cartable_civicrm_entityTypes(&$entityTypes) {
  _cartable_civix_civicrm_entityTypes($entityTypes);
}

/**
 * Implements hook_civicrm_themes().
 */
function cartable_civicrm_themes(&$themes) {
  _cartable_civix_civicrm_themes($themes);
}

// --- Functions below this ship commented out. Uncomment as required. ---

/**
 * Implements hook_civicrm_preProcess().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_preProcess
 */
//function cartable_civicrm_preProcess($formName, &$form) {
//
//}

function cartable_civicrm_pageRun(  &$page ) {
  if($page instanceof CRM_Cartable_Page_GenerateMembershipTypes){
    CRM_Core_Resources::singleton()->addScriptFile('cartable', 'assets/built/membership-types.js', 110, 'html-header', FALSE);
  }
}

/**
 * Implements hook_civicrm_navigationMenu().
 *
 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_navigationMenu
 */
function cartable_civicrm_navigationMenu(&$menu) {
 _cartable_civix_insert_navigation_menu($menu, 'Administer/CiviMember', [
   'label' => 'Générer des types d’adhésion',
   'name' => 'GenerateMembershipTypes',
   'url' => 'civicrm/cartable/generate-membership-types',
   'permission' => 'access CiviCRM',
   'operator' => 'OR',
   'separator' => 1,
 ]);
 _cartable_civix_navigationMenu($menu);
}

function cartable_include($path){
    $complete_path = __DIR__.'/'.$path;
    if(file_exists($complete_path)){
        include($complete_path);
        return $complete_path;
    }
    return false;
}

function cartable_civicrm_buildForm($formName, &$form) {
  header('FormName:'.$formName);
  $templatePath = realpath(dirname(__FILE__)."/templates");

  if ($formName == 'CRM_Contribute_Form_Contribution_Main') {
    CRM_Core_Resources::singleton()->addScriptFile('cartable', 'vendor/bastienho/jquery-tabs/jquery-tabs.js');
    CRM_Core_Resources::singleton()->addScriptFile('cartable', 'assets/built/academies.js');
    CRM_Core_Resources::singleton()->addStyleFile('cartable', 'vendor/bastienho/jquery-tabs/jquery-tabs.css');
    CRM_Core_Resources::singleton()->addStyleFile('cartable', 'assets/built/academies.css');
  }
  if ($formName == 'CRM_Contribute_Form_Contribution_Main' || $formName == 'CRM_Contact_Form_Contact') {
    CRM_Core_Resources::singleton()->addScriptFile('cartable', 'assets/built/donnees-particulier.js');
  }
}

function cartable_get_values($dataset, $sort=true){
    $maybe_file = __DIR__."/inc/values/{$dataset}.php";
    if(file_exists($maybe_file)){
        $array = include $maybe_file;
        if($sort){
            asort($array,  SORT_NATURAL);
        }
        return $array;
    }
    return [];
}

function cartable_get_custom_field_id($fieldname, $groupname=null){
    $FieldId = civicrm_api3('CustomField', 'getvalue', ['return'=>"id", 'name'=>$fieldname, 'custom_group_id'=>$groupname]);
    if(!$FieldId){
        return false;
    }
    return "custom_{$FieldId}";
}

function cartable_get_donnees_particuliers_vars(){
    $CorpsField = cartable_get_custom_field_id('Corps', 'DonneesParticulier');
    $DisciplineField = cartable_get_custom_field_id('Discipline', 'DonneesParticulier');
    $AutreDisciplineField = cartable_get_custom_field_id('AutreDiscipline', 'DonneesParticulier');
    $StatutField = cartable_get_custom_field_id('Statut', 'DonneesParticulier');
    $TypeDePosteField = cartable_get_custom_field_id('TypeDePoste', 'DonneesParticulier');
    if(!$CorpsField || !$DisciplineField || !$AutreDisciplineField || !$StatutField || !$TypeDePosteField){
        return false;
    }
    return [
        'hide_if_not' => [
            $CorpsField => [
                $StatutField => [
                    'titulaire',
                    'stagiaire',
                ],
            ],
            $TypeDePosteField => [
                $StatutField => [
                    'cdd',
                    'cdi',
                ],
            ],
            $DisciplineField => [
                $CorpsField => [
                    'Certifié·e',
                    'Agrégé·e',
                    'PLP',
                ],
                $TypeDePosteField => [
                    'Enseignant·e',
                ],
            ],
            $AutreDisciplineField => [
                $CorpsField => [
                    'Autre',
                ],
                $TypeDePosteField => [
                    'Autre',
                ],
            ],
        ],
        'filter_options' => [
            $DisciplineField => [
                // Corps
                $CorpsField => [
                    'Certifié·e' => cartable_get_values('disciplines-fonctionnaires'),
                    'Agrégé·e' => cartable_get_values('disciplines-fonctionnaires'),
                    'PLP' => cartable_get_values('disciplines-non-titulaires'),
                ],
                // Type de post
                $TypeDePosteField => [
                    'Enseignant·e' => cartable_get_values('disciplines-non-titulaires'),
                ],
            ],
        ],
    ];
}

function get_indexed_syndicates_and_provinces($vars){
    $ProvinceField = cartable_get_custom_field_id('Departements', 'DonneesSyndicat');
    if(!$ProvinceField){
        return false;
    }
    // First get all needed values
    $CountryId = civicrm_api3('Country', 'getvalue', ['return'=>"id", 'name'=>"france"]);
    $Provinces = civicrm_api3('StateProvince', 'get', ['country_id'=>$CountryId, 'options'=>['limit'=>0], 'sequential'=>1]);
    $Syndicates = civicrm_api3('Contact', 'get', ['return'=>"id,display_name,{$ProvinceField}", 'contact_sub_type'=>"SyndicatSUD", 'options'=>['limit'=>-1], 'sequential'=>1 ]);
    $MembershipTypes = civicrm_api3('MembershipType', 'get', []);

    $membershipFieldID = $vars['membershipFieldID'];

    $IndexedSyndicates = [];
    $IndexedProvinces = [];
    $IndexedMembershipTypes = [];
    $IndexedMembershipFields = [];

    // Index values per relation
    foreach($Provinces['values'] as $province){
        $IndexedSyndicates[$province['abbreviation']] = [];
        $IndexedProvinces[$province['id']] = $province['abbreviation'];
    }
    foreach($MembershipTypes['values'] as $membershipType){
        $IndexedMembershipTypes[$membershipType['member_of_contact_id']] = $membershipType;
    }
    foreach($vars['priceSet']['fields'][$membershipFieldID]['options'] as $membershipField){
        $IndexedMembershipFields[$membershipField['membership_type_id']] = $membershipField;
    }

    // Aggregate syndicates per department, membership types per syndicate
    foreach($Syndicates['values'] as $syndicate){
        if(!isset($syndicate[$ProvinceField]) || empty($syndicate[$ProvinceField])){
            continue;
        }
        //CIVICRM_QFID_15_price_12
        //CIVICRM_QFID_{$membershipFieldOpeionId}_price_{$membershipFieldID}
        $syndicate['membership_field'] = isset($IndexedMembershipTypes[$syndicate['id']])
            ? 'CIVICRM_QFID_'.$IndexedMembershipFields[$IndexedMembershipTypes[$syndicate['id']]['id']]['id'].'_price_'.$IndexedMembershipFields[$IndexedMembershipTypes[$syndicate['id']]['id']]['price_field_id']
            : null;

        $syndicate_provinces = $syndicate[$ProvinceField];

        foreach($syndicate[$ProvinceField] as $province_id){
            $IndexedSyndicates[$IndexedProvinces[$province_id]][] = $syndicate;
        }
    }

    return [
        'IndexedSyndicates' => $IndexedSyndicates,
        'IndexedProvinces' => $IndexedProvinces,
        'debug' => [
            '_Provinces' => $Provinces['values'],
            '_Syndicates' => $Syndicates['values'],
            '_MembershipTypes' => $MembershipTypes['values'],
            '_PriceSet' => $vars['priceSet'],
            '_MembershipFields' => $vars['priceSet']['fields'][$membershipFieldID],
            '_Vars' => $vars,
        ]
    ];
}