<?php
// get all product by webservice and save to db 

// ================== CONFIG ==================
$baseUrl  = "http://tebpars.eyebackteb.com:80/";
$username = "admin";
$password = "987321654" ;
$db = 'hoyairan_bot';
$DBuser = 'hoyairan_tlgbot';
$DBpassword = '2G=ca,1,ncn}!XNX';
$host = 'localhost';
$charset = 'utf8mb4';


// ================== CURL HELPER ==================
function curlRequest($url, $method = "GET", $data = null, $headers = [], &$cookies = null)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_HEADER, true);

    if ($cookies) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookies);
    }

    if ($data) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    if ($headers) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    $response = curl_exec($ch);

    if ($response === false) {
        die("❌ cURL Error: " . curl_error($ch));
    }

    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $headerSize);
    $body   = substr($response, $headerSize);

    if (preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches)) {
        $cookies = implode("; ", $matches[1]);
    }

    curl_close($ch);
    return $body;
}

// ================== ASN.1 FUNCTIONS ==================
function asn1EncodeLength($length)
{
    if ($length <= 0x7F) return chr($length);
    $temp = ltrim(pack('N', $length), "\x00");
    return chr(0x80 | strlen($temp)) . $temp;
}

function asn1EncodeInteger($data)
{
    if (ord($data[0]) > 0x7F) $data = "\x00" . $data;
    return "\x02" . asn1EncodeLength(strlen($data)) . $data;
}

function asn1EncodeSequence($data)
{
    return "\x30" . asn1EncodeLength(strlen($data)) . $data;
}

function asn1EncodeBitString($data)
{
    return "\x03" . asn1EncodeLength(strlen($data)) . $data;
}

function asn1EncodeNull()
{
    return "\x05\x00";
}

function asn1EncodeObjectIdentifier($oid)
{
    return "\x06" . asn1EncodeLength(strlen($oid)) . $oid;
}

// ================== RSA KEY BUILDER ==================
function buildRsaPublicKeyPem($modulusHex, $exponentHex)
{
    $modulus  = ltrim(hex2bin($modulusHex), "\x00");
    $exponent = ltrim(hex2bin($exponentHex), "\x00");

    $rsaKey = asn1EncodeSequence(
        asn1EncodeInteger($modulus) .
        asn1EncodeInteger($exponent)
    );

    $bitString = "\x00" . $rsaKey;

    $spki = asn1EncodeSequence(
        asn1EncodeSequence(
            asn1EncodeObjectIdentifier("\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01") .
            asn1EncodeNull()
        ) .
        asn1EncodeBitString($bitString)
    );

    return "-----BEGIN PUBLIC KEY-----\n"
        . chunk_split(base64_encode($spki), 64, "\n")
        . "-----END PUBLIC KEY-----\n";
}

// ================== RSA ENCRYPT ==================
function rsaEncrypt($sessionId, $password, $modulusHex, $exponentHex)
{
    $pem = buildRsaPublicKeyPem($modulusHex, $exponentHex);
    $pubKey = openssl_pkey_get_public($pem);

    if (!$pubKey) {
        die("❌ ERROR: Invalid RSA Public Key");
    }

    $plain = $sessionId . "**" . $password;

    openssl_public_encrypt($plain, $encrypted, $pubKey, OPENSSL_PKCS1_PADDING);
    return bin2hex($encrypted);
}

// ================== LOGIN & SESION ==================
function loginAndGetAuthCookie($baseUrl, $username, $password)
{
    $cookie = null;

    // ---------- STEP 1: GET SESSION ----------
    $sessionJson = curlRequest(
        "$baseUrl/TebPars/Services/Framework/AuthenticationService.svc/session",
        "GET",
        null,
        ["Accept: application/json"],
        $cookie
    );

    $session = json_decode($sessionJson, true);
    if (!$session || !isset($session['id'])) {
        return [
            'success' => false,
            'message' => 'Failed to get session'
        ];
    }

    // ---------- STEP 2: RSA ENCRYPT PASSWORD ----------
    $encryptedPassword = rsaEncrypt(
        $session['id'],
        $password,
        $session['rsa']['M'],
        $session['rsa']['E']
    );

    $loginPayload = json_encode([
        "sessionId" => $session['id'],
        "username"  => $username,
        "password"  => $encryptedPassword
    ]);

    // ---------- STEP 3: LOGIN ----------
    curlRequest(
        "$baseUrl/TebPars/Services/Framework/AuthenticationService.svc/login",
        "POST",
        $loginPayload,
        ["Content-Type: application/json"],
        $cookie
    );

    // ---------- STEP 4: EXTRACT sg-auth-TebPars VALUE ----------
    if (!preg_match('/sg-auth-TebPars=([^;]+)/', $cookie, $matches)) {
        return [
            'success' => false,
            'message' => 'sg-auth-TebPars cookie not found',
            'raw_cookie' => $cookie
        ];
    }

    return [
        'success'     => true,
        'session_id'  => $session['id'],
        'cookie_raw'  => $cookie,
        'cookie_value'=> $matches[1] // فقط مقدار
    ];
}




// ================== STEP 3: call webservice ==================
function getCustomers($baseUrl, $authCookie)
{
    $url = $baseUrl . "/TebPars3g/x50d59620/Sales/PartyManagement/Services/PartyManagementService.svc/GetCustomers" ;

    $ch = curl_init($url);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => [
            "Cookie: $authCookie"
        ]
    ]);

    $response = curl_exec($ch);

    if ($response === false) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new Exception("cURL Error: " . $error);
    }

    curl_close($ch);
    return $response;
}



// ================== get all products ==================
function getProducts($baseUrl, $cookieValue) {
    $url = $baseUrl . 'TebPars3g/x50d59620/Sales/ProductManagement/Services/ProductManagementService.svc/GetProducts' ;

    $jsonData = '{
        "FromDate":"\\/Date(928133400000+0330)\\/",
        "InventoryID":7,
        "PageIndex":1,
        "PageSize":2147483647
    }';

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $jsonData,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Cookie: sg-auth-TebPars=' . $cookieValue
        ]
    ]);

    $response = curl_exec($ch);
    if ($response === false) {
        throw new Exception('cURL Error: ' . curl_error($ch));
    }
    curl_close($ch);
    return $response;
}

// ================== get all products new with additional filelds ==================
function getProductsfields($baseUrl, $cookieValue) {
    $url = $baseUrl . 'TebPars3g/x50d59620/System/BusinessRuleEngine/Service.svc/Call' ;

    $jsonData = '{
	"Name":"EyeBak_PartList",
	"Parameters":"{}"
    }';

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $jsonData,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Cookie: sg-auth-TebPars=' . $cookieValue
        ]
    ]);

    $response = curl_exec($ch);
    if ($response === false) {
        throw new Exception('cURL Error: ' . curl_error($ch));
    }
    curl_close($ch);
    return $response;
}


// ================== check a product value ==================
function getProductRemainingValue($baseUrl, $cookieValue,$productID) {
    $url = $baseUrl . 'TebPars3g/x50d59620/Sales/SalesDocument/Services/SalesDocumentService.svc/productInventoryRemainingValue' ;

    $jsonData = '{"InventoryID":7,"PlantID":1,"ProductID":'.$productID.'}';

    // $ch = curl_init($url);
    // curl_setopt_array($ch, [
    //     CURLOPT_RETURNTRANSFER => true,
    //     CURLOPT_POST => true,
    //     CURLOPT_POSTFIELDS => $jsonData,
    //     CURLOPT_HTTPHEADER => [
    //         'Content-Type: application/json',
    //         'Cookie: sg-auth-TebPars=' . $cookieValue
    //     ]
    // ]);

    // $response = curl_exec($ch);
    // if ($response === false) {
    //     throw new Exception('cURL Error: ' . curl_error($ch));
    // }
    // curl_close($ch);
    // return $response;
    
    
    $curl = curl_init();
    
    curl_setopt_array($curl, array(
      CURLOPT_URL =>  $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS => $jsonData ,
      CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json',
        "Cookie: sg-auth-TebPars=$cookieValue"
      ),
    ));
    
    $response = curl_exec($curl);
    
    curl_close($curl);
    return $response;

}



// ================== save product to db ==================
function saveProductsToDb(PDO $pdo, string $productsJson): int
{
    // پاک‌سازی JSON
    $allProducts = trim($productsJson, "\"");
    $allProducts = stripcslashes($allProducts);

    $data = json_decode($allProducts, true);
    if (!isset($data['OutPartList']) || !is_array($data['OutPartList'])) {
        throw new Exception('Invalid products JSON structure');
    }

    $products = $data['OutPartList'];

    //  لیست مجاز PropertiesComment
    $allowedComments = [
        'Gemetric',
        'Gemetric plus',
        'Gemetric toric',
        'Gemetric plus toric',
        'Vivinex',
        'Vivinex Toric',
        'Vivinex Impress'
        
    ];

    // تبدیل همه به حروف کوچک برای مقایسه غیر حساس به حروف
    $allowedCommentsLower = array_map(fn($c) => mb_strtolower($c, 'UTF-8'), $allowedComments);

    // حذف داده‌های قبلی
    $pdo->exec("DELETE FROM hrp_products");

    $stmt = $pdo->prepare("
        INSERT INTO hrp_products 
        (id, number, name, PropertiesComment,
         AdditionalField1, AdditionalField2, part_technical_specification)
        VALUES 
        (:ID, :Code, :Name, :PropertiesComment, :AdditionalField1,
         :AdditionalField2, :TechnicalSpecification)
    ");

    $count = 0;

    foreach ($products as $p) {

        if (!isset($p['ID'], $p['Code'], $p['Name'], $p['State'])) {
            continue;
        }

        // فیلتر بر اساس PropertiesComment
        $comment = trim($p['PropertiesComment'] ?? '');
        $commentLower = mb_strtolower($comment, 'UTF-8');

        if ($comment === '' || !in_array($commentLower, $allowedCommentsLower, true)) {
            continue; // اگر جزو لیست نبود، ذخیره نشود
        }

        $stmt->execute([
            ':ID'                     => (int)$p['ID'],
            ':Code'                   => $p['Code'],
            ':Name'                   => $p['Name'],
            ':PropertiesComment'      => $p['PropertiesComment'] ?? null,
            ':AdditionalField1'       => $p['AdditionalField1'] ?? null,
            ':AdditionalField2'       => $p['AdditionalField2'] ?? null,
            ':TechnicalSpecification' => $p['TechnicalSpecification'] ?? null
        ]);

        $count++;
    }

    return $count;
}

/* ==========  log  ========== */
function logOrder($useid, $product, $availability_status) {
    try {
        global $host, $db, $DBuser, $DBpassword, $charset;
    
        $pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $DBuser, $DBpassword);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $pdo->prepare("
            INSERT INTO hrp_order_logs
            (username, product_name, product_id, availability_status)
            VALUES
            (:username, :product_name, :product_id, :availability_status)
        ");
        $stmt->execute([
            ':username' => $useid,
            ':product_name' => $product['name'] ?? 'نامعلوم',
            ':product_id' => $product['id'] ?? 0,
            ':availability_status' => $availability_status
        ]);

    } catch (PDOException $e) {
        echo "❌ خطا در ثبت لاگ: " . $e->getMessage() . "\n";
    } catch (Throwable $e) {
        echo "❌ خطای غیرمنتظره: " . $e->getMessage() . "\n";
    }
}

// ================== test ==================

///////login and cookie
$result = loginAndGetAuthCookie($baseUrl, $username, $password);
echo "<pre>";
if ($result['success']) {
    // echo "✅ LOGIN OK\n";
    // echo "🆔 Session ID: " . $result['session_id'] . "\n";
    // echo "🍪 Full Cookie: " . $result['cookie_raw'] . "\n";
    // echo "🎯 sg-auth-TebPars VALUE: " . $result['cookie_value'] . "\n";
} else {
    // echo "❌ LOGIN FAILED\n";
    print_r($result);
}
echo "</pre>";


// ================== conect to db ==================


try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $DBuser, $DBpassword);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    //echo "✅ اتصال به دیتابیس موفق بود!\n";

    // تست ساده: گرفتن تعداد رکوردها از یک جدول موجود
    $stmt = $pdo->query("SELECT COUNT(*) AS total FROM hrp_products");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    //echo "تعداد رکوردها در hrp_products: " . $row['total'] . "\n";

} catch (PDOException $e) {
    //echo "❌ خطا در اتصال به دیتابیس: " . $e->getMessage();
}



///////////get produncts by webservice

$allProducts = getProductsfields($baseUrl, $result['cookie_value']) ;

try {
    $saved = saveProductsToDb($pdo, $allProducts);

    //echo "✅ تعداد ذخیره شده: $saved";
} catch (Exception $e) {
   // echo "❌ ERROR: " . $e->getMessage();
}


//////////////// check remainvalue 
 
// $getProductRemainingValue = getProductRemainingValue($baseUrl, $result['cookie_value'] ,505);
// var_dump($getProductRemainingValue);






// ================== CONNECT TO REMOTE SERVER  ==================\
// $REMOTE_DB_HOST = '192.168.1.25';  
// $REMOTE_DB_NAME = 'TebPars';
// $REMOTE_DB_USER = 'robot';
// $REMOTE_DB_PASS = '12082As!';
// $REMOTE_DB_CHARSET = 'utf8mb4';

// function remoteDb(): PDO
// {
//     static $pdo = null;
//     if ($pdo) return $pdo;

//     global $REMOTE_DB_HOST, $REMOTE_DB_NAME, $REMOTE_DB_USER, $REMOTE_DB_PASS, $REMOTE_DB_CHARSET;

//     $dsn = "mysql:host={$REMOTE_DB_HOST};dbname={$REMOTE_DB_NAME};charset={$REMOTE_DB_CHARSET}";

//     $pdo = new PDO($dsn, $REMOTE_DB_USER, $REMOTE_DB_PASS, [
//         PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
//         PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
//         PDO::ATTR_EMULATE_PREPARES   => false,
//         PDO::ATTR_TIMEOUT            => 5,   // مهم برای بات
//     ]);

//     return $pdo;
// }


// function getRemoteCategories(): array
// {
//     $sql = "
//         SELECT * from lgs3.Part
//     ";

//     return remoteDb()->query($sql)->fetchAll(PDO::FETCH_COLUMN);
// }



// try {
//     $cats = getRemoteCategories();
//     echo "OK - categories: " . count($cats);
// } catch (Throwable $e) {
//     echo "DB ERROR: " . $e->getMessage();
// }


// try {
//     $pdo = new PDO("mysql:host=$REMOTE_DB_HOST;dbname=$REMOTE_DB_NAME;charset=$REMOTE_DB_CHARSET", $REMOTE_DB_USER, $REMOTE_DB_PASS);
//     $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//     echo "✅ اتصال به دیتابیس موفق بود!\n";

//     // تست ساده: گرفتن تعداد رکوردها از یک جدول موجود
//     $stmt = $pdo->query("select partid, name, AdditionalField1,AdditionalField2 ,PropertiesComment from lgs3.Part");
//     $row = $stmt->fetch(PDO::FETCH_ASSOC);
//     var_dump($row);

// } catch (PDOException $e) {
//     echo "❌ خطا در اتصال به دیتابیس: " . $e->getMessage();
// }







