<?php
date_default_timezone_set("Etc/GMT-8");

$hostname = 'GMGIS\SQLEXPRESS';
$username = 'BIMuser';
$password = 'Component3444';
$db_name = "21000X";
$account = "maabim";

try {
    $pdo = new PDO('sqlsrv:Server=' . $hostname . ';Database=' . $db_name, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo $e;
    echo json_encode('Error connecting to the server.');
    die();
}

$root = '../../assets/建置資料/土地開發';
//$folder = $_GET["folder"];
$plan = '';
FindPath($root, '19004-菓林市地重劃設計', $plan, 1,$pdo);
function FindPath($root, $folder, $plan, $type,$pdo)
{
    $rootPath = $root . "/" . $folder;
    $paths = array_diff(scandir($rootPath), array('.', '..', 'Thumbs.db'));
    echo ("<ul>");
    $i = 1;
    foreach ($paths as $path) {        
        if (is_file($rootPath . '/' . $path)) {
            $original_name = $path;
            if(str_contains($original_name,'-')){
                $original_name = explode("-", $original_name,2)[1];
            }else if(str_contains($original_name,'_')){
                $original_name = explode("_", $original_name,2)[1];
            }
            $filename = $path;
            $plan = '19004';
            $href = substr($rootPath, 4) . "/" . $path;
            echo ("<li class='node-hidden' data-jstree='{ " . '"type" : "file"' . " }' >");
            $path = "<a typeId='".$type."' sn='".$i."' time='" . date("Y/m/d H:i:s", filemtime($rootPath . '/' . $path)) . "'plan='" . $plan . "' href='" . $href . "'>" . $original_name . "</a>";
            echo ($path);
            echo ("</li>");
            $sth = $pdo->prepare("INSERT INTO [21000X].[dbo].[File_Table]
                   ([project_id]
                   ,[SN]
                   ,[type_id]
                   ,[original_name]
                   ,[filename]
                   ,[keyword])
             VALUES
                   ('19004',
                   '" . $i . "',
                   '" . $type . "',
                   '" . $original_name . "',
                   '" . $filename . "',
                   '')");
                   $i++;
           //$sth->execute();

        } else {
            if (str_contains($path, '-')) {
                $plan = $path;
            }
            echo ("<li>");
            echo ($path);
            $type = explode('_', $path)[0];
            if ($path != "3_設計圖")
                FindPath($rootPath, $path, $plan, $type,$pdo);
            echo ("</li>");            
        }
    }
    echo ("</ul>");
}
