<?php

error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('html_errors', '0');

mysqli_report(MYSQLI_REPORT_OFF);

header('Content-Type: text/plain; charset=utf-8');


/* ============================================================
   SOSELEC81
   ENREGISTREMENT DES INFORMATIONS DU COMMERCIAL

   Le commercial est identifié uniquement par :
   - machine_id
   - machine_fingerprint

   Le commercial_id est retrouvé côté serveur.
   ============================================================ */


/* ============================================================
   FONCTIONS
   ============================================================ */

function valeurPost($nom)
{
    if (isset($_POST[$nom])) {
        return trim((string)$_POST[$nom]);
    }

    return '';
}


function nettoyerValeur($texte)
{
    $texte = trim((string)$texte);

    return str_replace(
        array('|', "\r", "\n"),
        array(' ', ' ', ' '),
        $texte
    );
}


/* ============================================================
   CONNEXION MYSQL
   ============================================================ */

$conn = new mysqli(
    "localhost",
    "root",
    "",
    "sos_elec_db"
);


if ($conn->connect_errno) {

    exit(
        "ERREUR|MYSQL_CONNEXION"
    );
}


$conn->set_charset(
    "utf8mb4"
);


/* ============================================================
   DONNEES RECUES
   ============================================================ */

$machine_id =
    valeurPost(
        'machine_id'
    );


$machine_fingerprint =
    valeurPost(
        'machine_fingerprint'
    );


$nom =
    nettoyerValeur(
        valeurPost(
            'nom'
        )
    );


$prenom =
    nettoyerValeur(
        valeurPost(
            'prenom'
        )
    );


$telephone =
    nettoyerValeur(
        valeurPost(
            'telephone'
        )
    );


$email =
    nettoyerValeur(
        valeurPost(
            'email'
        )
    );


$agence =
    nettoyerValeur(
        valeurPost(
            'agence'
        )
    );


/* ============================================================
   VERIFICATIONS
   ============================================================ */

if ($machine_id === '') {

    $conn->close();

    exit(
        "ERREUR|MACHINE_ID_VIDE"
    );
}


if ($machine_fingerprint === '') {

    $conn->close();

    exit(
        "ERREUR|FINGERPRINT_VIDE"
    );
}


if (
    !preg_match(
        '/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/',
        $machine_id
    )
) {

    $conn->close();

    exit(
        "ERREUR|FORMAT_MACHINE_ID"
    );
}


if (
    !preg_match(
        '/^[a-fA-F0-9]{64}$/',
        $machine_fingerprint
    )
) {

    $conn->close();

    exit(
        "ERREUR|FORMAT_FINGERPRINT"
    );
}


/* ============================================================
   RECHERCHE DE LA LICENCE
   ============================================================ */

$stmt = $conn->prepare("
    SELECT

        id,
        status,
        machine_fingerprint,
        distributeur_code,
        commercial_id

    FROM licences

    WHERE machine_id = ?

    LIMIT 1
");


if (!$stmt) {

    $conn->close();

    exit(
        "ERREUR|PREPARE_LICENCE"
    );
}


$stmt->bind_param(
    "s",
    $machine_id
);


if (!$stmt->execute()) {

    $stmt->close();
    $conn->close();

    exit(
        "ERREUR|EXECUTION_LICENCE"
    );
}


$result =
    $stmt->get_result();


if ($result->num_rows !== 1) {

    $stmt->close();
    $conn->close();

    exit(
        "NON|MACHINE_INCONNUE"
    );
}


$row =
    $result->fetch_assoc();


/* ============================================================
   VERIFICATION LICENCE ACTIVE
   ============================================================ */

$status =
    strtoupper(
        trim(
            (string)$row['status']
        )
    );


if ($status !== 'OUI') {

    $stmt->close();
    $conn->close();

    exit(
        "NON|LICENCE_BLOQUEE"
    );
}


/* ============================================================
   VERIFICATION EMPREINTE
   ============================================================ */

$empreinteServeur =
    strtolower(
        preg_replace(
            '/[^a-f0-9]/',
            '',
            trim(
                (string)$row['machine_fingerprint']
            )
        )
    );


$empreinteClient =
    strtolower(
        preg_replace(
            '/[^a-f0-9]/',
            '',
            $machine_fingerprint
        )
    );


if (
    strlen($empreinteServeur) !== 64 ||
    strlen($empreinteClient) !== 64 ||
    !hash_equals(
        $empreinteServeur,
        $empreinteClient
    )
) {

    $stmt->close();
    $conn->close();

    exit(
        "NON|MACHINE_REFUSEE"
    );
}


/* ============================================================
   COMMERCIAL ASSOCIE A LA LICENCE
   ============================================================ */

$commercialId = 0;


if (
    isset($row['commercial_id']) &&
    $row['commercial_id'] !== null &&
    $row['commercial_id'] !== ''
) {

    $commercialId =
        (int)$row['commercial_id'];

}


$distributeurCode =
    nettoyerValeur(
        $row['distributeur_code']
        ?? ''
    );


$stmt->close();


if ($commercialId <= 0) {

    $conn->close();

    exit(
        "NON|COMMERCIAL_NON_ASSOCIE"
    );
}


/* ============================================================
   VERIFICATION DU COMMERCIAL
   ============================================================ */

$stmtCommercial = $conn->prepare("
    SELECT

        id,
        distributeur_code,
        actif

    FROM commerciaux

    WHERE id = ?

    AND distributeur_code = ?

    LIMIT 1
");


if (!$stmtCommercial) {

    $conn->close();

    exit(
        "ERREUR|PREPARE_COMMERCIAL"
    );
}


$stmtCommercial->bind_param(
    "is",
    $commercialId,
    $distributeurCode
);


if (!$stmtCommercial->execute()) {

    $stmtCommercial->close();
    $conn->close();

    exit(
        "ERREUR|EXECUTION_COMMERCIAL"
    );
}


$resultCommercial =
    $stmtCommercial->get_result();


if ($resultCommercial->num_rows !== 1) {

    $stmtCommercial->close();
    $conn->close();

    exit(
        "NON|COMMERCIAL_INCONNU"
    );
}


$rowCommercial =
    $resultCommercial->fetch_assoc();


$actif =
    strtoupper(
        nettoyerValeur(
            $rowCommercial['actif']
            ?? 'NON'
        )
    );


$stmtCommercial->close();


if ($actif !== 'OUI') {

    $conn->close();

    exit(
        "NON|COMMERCIAL_INACTIF"
    );
}


/* ============================================================
   VALIDATION DES DONNEES
   ============================================================ */

if ($nom === '') {

    $conn->close();

    exit(
        "ERREUR|NOM_VIDE"
    );
}


if ($prenom === '') {

    $conn->close();

    exit(
        "ERREUR|PRENOM_VIDE"
    );
}


if (
    $email !== '' &&
    !filter_var(
        $email,
        FILTER_VALIDATE_EMAIL
    )
) {

    $conn->close();

    exit(
        "ERREUR|EMAIL_INVALIDE"
    );
}


/* ============================================================
   MISE A JOUR
   ============================================================ */

$stmtUpdate = $conn->prepare("
    UPDATE commerciaux

    SET
        nom = ?,
        prenom = ?,
        telephone = ?,
        email = ?,
        agence = ?

    WHERE id = ?

    AND distributeur_code = ?

    AND actif = 'OUI'
");


if (!$stmtUpdate) {

    $conn->close();

    exit(
        "ERREUR|PREPARE_UPDATE"
    );
}


$stmtUpdate->bind_param(
    "sssssis",
    $nom,
    $prenom,
    $telephone,
    $email,
    $agence,
    $commercialId,
    $distributeurCode
);


if (!$stmtUpdate->execute()) {

    $stmtUpdate->close();
    $conn->close();

    exit(
        "ERREUR|EXECUTION_UPDATE"
    );
}


if ($stmtUpdate->affected_rows < 0) {

    $stmtUpdate->close();
    $conn->close();

    exit(
        "ERREUR|MISE_A_JOUR"
    );
}


$stmtUpdate->close();

$conn->close();


/* ============================================================
   REPONSE
   ============================================================ */

echo
    "OK" .

    "|COMMERCIAL_ID=" .
    $commercialId .

    "|COMMERCIAL_NOM=" .
    $nom .

    "|COMMERCIAL_PRENOM=" .
    $prenom .

    "|COMMERCIAL_TELEPHONE=" .
    $telephone .

    "|COMMERCIAL_EMAIL=" .
    $email .

    "|COMMERCIAL_AGENCE=" .
    $agence;

?>