<?php

////////////////////////////////////////////////////////////////////////
// CLIENTS /////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////

// LIST

$allowClientsListOrder = array(
    'ref' => "réf.",
    'nom' => "nom",
    'prenom' => "prénom",
    'tel' => "téléphone",
    'email' => "email"
);

function getNbClientsInList($search=false) {
    $sql = getCountClientsListSelectBaseSQL()." WHERE ".CLIENTS_TABLE.".`del`=0";
    $sql = buildSqlSearch($sql, $search, buildClientsListSearchSQL);
    $r = $GLOBALS['db_admin']['man']->select($sql, 1);
    if(!$r['erreur']) return intval($r['datas']['nb']);
    else {
        $er = "</br>sql: ".$sql."</br>error: ".getReadableVar($r['erreur']);
        return "Une erreur est survenue durant du nombre d'item dans la liste !".$er;
    }
}

function getClientsList($order='nom',$sens='ASC',$simple=false,$search=false,$limits=false) {
    $list = array();
    
    $sql = getClientsTableSelectBaseSQL()." WHERE ".CLIENTS_TABLE.".`del`=0";
    
    // SEARCH
    $sql = buildSqlSearch($sql, $search, buildClientsListSearchSQL);
    
    // ORDRE
    $sql.=" ORDER BY ";
    
    if($order=='ref') $sql .= CLIENTS_TABLE.".`ref`";
    else if($order=='nom') $sql .= CLIENTS_TABLE.".`nom`";
    else if($order=='prenom') $sql .= CLIENTS_TABLE.".`prenom`";
    else if($order=='tel') $sql .= CLIENTS_TABLE.".`tel`";
    else if($order=='email') $sql .= CLIENTS_TABLE.".`email`";
    else $sql .= CLIENTS_TABLE.".`nom`";
    
    // SENS
    if($sens=='DESC') $sql .= ' DESC';
    else $sql .= ' ASC';
    
    // LIMITS
    if(is_array($limits)) $sql .= " LIMIT ".$limits['start'].", ".$limits['nbItemsByPage'];
    
    $r = $GLOBALS['db_admin']['man']->select($sql);

    if(!$r['erreur']) {
        foreach($r['datas'] as $i) {
            if($simple) $list[$i['ref']] = $i['prenom']." ".$i['nom'];
            else $list[$i['ref']] = $i;
        }
    }
    else {
        $er = "</br>sql: ".$sql."</br>error: ".getReadableVar($r['erreur']);
        $GLOBALS['errors'][] = "Une erreur est survenue durant la récupération de la liste des clients dans le base de données !".$er;
    }
    
    return $list;
}

function getClientsAutocompleteList() {
    $sql = getClientsTableSelectBaseSQL()." WHERE ".CLIENTS_TABLE.".`del`=0";
    
    // get what user typed in autocomplete input
    $term = trim($_REQUEST['search']);

    $a_json = array();
    $a_json_row = array();
    $a_json_invalid = array(array("id" => "#", "value" => $term, "label" => "Only letters and digits are permitted..."));

    // replace multiple spaces with one
    $term = preg_replace('/\s+/', ' ', $term);

    $parts = explode(' ', $term);
    $p = count($parts);

    for($i = 0; $i < $p; $i++) {
        $sql .= ' AND ('.CLIENTS_TABLE.'.`nom` LIKE "%'.$parts[$i].'%" OR '.CLIENTS_TABLE.'.`prenom` LIKE "%'.$parts[$i].'%")';
    }
    
    $r = $GLOBALS['db_admin']['man']->select($sql);
    
    if(!$r['erreur']) {
        foreach($r['datas'] as $c) {
            $a_json_row["id"] = $c['ref'];
            $a_json_row["ref"] = $c['ref'];
            $value = $c['prenom']." ".$c['nom'];
            $a_json_row["value"] = $value;
            $a_json_row["label"] = $value;
            
            array_push($a_json, $a_json_row);
        }
        
        // highlight search results
        $a_json = apply_highlight($a_json, $parts);
    }
    else {
        $er = "</br>sql: ".$sql."</br>error: ".getReadableVar($r['erreur']);
        $GLOBALS['errors'][] = "Une erreur est survenue durant la récupération de la liste des client !".$er;
    }
    return $a_json;
}

// GET DATAS

function getClientDatas($id) {
    $i = array();
    
    $sql = getClientsTableSelectBaseSQL()." WHERE ".CLIENTS_TABLE.".`ref`=".intval($id);
    
    $r = $GLOBALS['db_admin']['man']->select($sql,1);

    if(!$r['erreur']) {
        $i = $r['datas'];
        
        // CONTRATS
        $i["contrats"] = getClientContrats($id);
        
        // ABSENCES
        $i["absences"] = getClientAbsences($id);
    }
    else {
        $er = "</br>sql: ".$sql."</br>error: ".getReadableVar($r['erreur']);
        $GLOBALS['errors'][] = "Une erreur est survenue durant la récupération des informations du client dans le base de données !".$er;
    }
    
    return $i;
}

function getClientContrats($id) { return getContratsList("date","DESC", array("client" => $id)); }
function getClientAbsences($id) { return getClientAbsencesList("fin", "DESC", $id); }

// ADD / UPDATE DATAS

function getClientDatasFromRequest() { return getRequestTableDatas(CLIENTS_TABLE_STRUCT); }

function addClient($datas) {
    return addDatasInTable(
        $GLOBALS['db_admin']['man'],    // DB MANAGER
        CLIENTS_TABLE,                  // TABLE NAME
        CLIENTS_TABLE_STRUCT,           // TABLE STRUCTURE
        $datas,                         // DATAS
        "du client"                     // ERROR STRING
    );
}

function updateClient($id, $datas) { 
    return updateDatasInTable(
        $GLOBALS['db_admin']['man'],    // DB MANAGER
        CLIENTS_TABLE,                  // TABLE NAME
        CLIENTS_TABLE_STRUCT,           // TABLE STRUCTURE
        $id,                            // ID
        $datas,                         // DATAS
        "au client",                    // NULL STRING
        "du client"                     // ERROR STRING
    );
}

function deleteClient($id) {
    $datas = array("del" => 1);
    return updateClient($id, $datas);
}

function eraseClient($id) {
    return deleteItemInTable(
        $GLOBALS['db_admin']['man'],    // DB MANAGER
        CLIENTS_TABLE,                  // TABLE NAME
        $id,                            // ID
        "du client"                     // ERROR STRING
    );
}

////////////////////////////////////////////////////////////////////////
// CLIENTS - ABSENCES //////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////

$allowClientsAbsencesListOrder = array(
    'ref' => "réf.",
    'nom' => "nom",
    'prenom' => "prénom",
    'debut' => "début",
    'fin' => "fin <small>(incluse)</small>"
);

function getClientAbsencesList($order='id',$sens='ASC',$client=0, $search=false) {
    $list = array();
    
    $sql = getClientsAbsencesTableSelectBaseSQL()." WHERE ".CLIENTS_ABSENCES_TABLE.".`del`=0";
    
    if($client>0) $sql .= " AND ".CLIENTS_ABSENCES_TABLE.".`client`=".intval($client);
    
    // SEARCH
    if($search && $search!="") {
        $parts = explode(" ", $search);
        if(is_array($parts) && count($parts>0)) {
            $search_sql = "";
            foreach($parts as $p) {
                if($p!="") $search_sql .= (($search_sql!="") ? " OR " : "").buildClientsAbsencesListSearchSQL($p);
            }
            if($search_sql!="") $sql .= " AND (".$search_sql.")";
        }
    }
    
    // ORDRE
    $sql.=" ORDER BY ";
    
    if($order=='ref') $sql .= CLIENTS_ABSENCES_TABLE.".`ref`";
    else if($order=='nom') $sql .= CLIENTS_TABLE.".`nom`";
    else if($order=='prenom') $sql .= CLIENTS_TABLE.".`prenom`";
    else if($order=='debut') $sql .= CLIENTS_ABSENCES_TABLE.".`debut`";
    else if($order=='fin') $sql .= CLIENTS_ABSENCES_TABLE.".`fin`";
    else $sql .= CLIENTS_TABLE.".`nom`";
    
    // SENS
    if($sens=='DESC') $sql .= ' DESC';
    else $sql .= ' ASC';
    
    $r = $GLOBALS['db_admin']['man']->select($sql);

    if(!$r['erreur']) {
        foreach($r['datas'] as $i) {
            $i["debut_print"] = formatDate($i["debut"], "mysql_date", "date");
            $i["fin_print"] = formatDate($i["fin"], "mysql_date", "date");
            $i["periode"] = formatPeriode($i["debut"], $i["fin"], "mysql_date");
            $list[$i["ref"]] = $i;
        }
    }
    else {
        $er = "</br>sql: ".$sql."</br>error: ".getReadableVar($r['erreur']);
        $GLOBALS['errors'][] = "Une erreur est survenue durant la récupération de la liste des absences clients dans le base de données !".$er;
    }
    
    return $list;
}

// GET DATAS

function getClientAbsenceDatas($id) {
    $i = array();
    
    $sql = getClientsAbsencesTableSelectBaseSQL()." WHERE ".CLIENTS_ABSENCES_TABLE.".`ref`=".intval($id);
    
    $r = $GLOBALS['db_admin']['man']->select($sql,1);

    if(!$r['erreur']) {
        $i = $r['datas'];
        $i["debut_print"] = formatDate($i["debut"], "mysql_date", "date");
        $i["fin_print"] = formatDate($i["fin"], "mysql_date", "date");
        $i["periode"] = formatPeriode($i["debut"], $i["fin"], "mysql_date");
    }
    else {
        $er = "</br>sql: ".$sql."</br>error: ".getReadableVar($r['erreur']);
        $GLOBALS['errors'][] = "Une erreur est survenue durant la récupération des informations de l'absences client dans le base de données !".$er;
    }
    
    return $i;
}

function getClientAbsenceAtDate($client, $date) {
    $date_checked = checkDateFormat($date, 'mysql_date', NULL);
    if(is_null($date_checked)) {
        $GLOBALS['errors'][] = "Aucune date transmis !";
        return false;
    }
    
    $abs = false;
    
    $sql = getClientsAbsencesTableSelectBaseSQL()
        ." WHERE ".CLIENTS_ABSENCES_TABLE.".`client`=".intval($client)
        ." AND ".CLIENTS_ABSENCES_TABLE.".`debut`<='".$date_checked."'"
        ." AND ".CLIENTS_ABSENCES_TABLE.".`fin`>='".$date_checked."'"
        ." ORDER BY ".CLIENTS_ABSENCES_TABLE.".`fin` DESC LIMIT 0,1";
    
    $r = $GLOBALS['db_admin']['man']->select($sql);
    
    if(!$r['erreur']) {
        if(count($r['datas'])>0) {
            $abs = $r['datas'][0];
            $abs["debut_print"] = formatDate($abs["debut"], "mysql_date", "date");
            $abs["fin_print"] = formatDate($abs["fin"], "mysql_date", "date");
            $abs["periode"] = formatPeriode($abs["debut"], $abs["fin"], "mysql_date");
        }
    }
    else {
        $er = "</br>sql: ".$sql."</br>error: ".getReadableVar($r['erreur']);
        $GLOBALS['errors'][] = "Une erreur est survenue durant l'interogation date dans le base de données sur une éventuelle absence client !".$er;
    }
    
    return $abs;
}

// ADD / UPDATE DATAS

function getClientAbsenceDatasFromRequest() { return getRequestTableDatas(CLIENTS_ABSENCES_TABLE_STRUCT); }

function addClientAbsence($datas) {
    return addDatasInTable(
        $GLOBALS['db_admin']['man'],    // DB MANAGER
        CLIENTS_ABSENCES_TABLE,         // TABLE NAME
        CLIENTS_ABSENCES_TABLE_STRUCT,  // TABLE STRUCTURE
        $datas,                         // DATAS
        "de l'absence client"           // ERROR STRING
    );
}

function updateClientAbsence($id, $datas) { 
    return updateDatasInTable(
        $GLOBALS['db_admin']['man'],    // DB MANAGER
        CLIENTS_ABSENCES_TABLE,         // TABLE NAME
        CLIENTS_ABSENCES_TABLE_STRUCT,  // TABLE STRUCTURE
        $id,                            // ID
        $datas,                         // DATAS
        "à l'absence client",           // NULL STRING
        "de l'absence client"           // ERROR STRING
    );
}

function deleteClientAbsence($id) {
    return deleteItemInTable(
        $GLOBALS['db_admin']['man'],    // DB MANAGER
        CLIENTS_ABSENCES_TABLE,         // TABLE NAME
        $id,                            // ID
        "de l'absence client"           // ERROR STRING
    );
}

function eraseClientAbsence($id) {
    return eraseItemInTable(
        $GLOBALS['db_admin']['man'],    // DB MANAGER
        CLIENTS_ABSENCES_TABLE,         // TABLE NAME
        $id,                            // ID
        "de l'absence client"           // ERROR STRING
    );
}
