<?php
error_reporting(E_ALL & ~E_NOTICE);
define('_PROJECT_DIR', getcwd() . '/../../../');
require_once(_PROJECT_DIR . 'engine/bootstrap.php');

// -------------------------------------------------
// CONFIG
// -------------------------------------------------
$DRY_RUN = false; // ← поставить true для тестового запуска

// Источник (старая МИС)
$src = new db();
$src->connect("192.168.0.2", "root", "Xx29Pz33", "pnd8");

// Приёмник (новая база)
$dst = $core_db->new_db();


// =====================================================================
// 1. СОЗДАЁМ ВРЕМЕННЫЕ ТАБЛИЦЫ С ИДЕНТИЧНОЙ СТРУКТУРОЙ
// =====================================================================
function recreateTmpTables($dst, $DRY_RUN)
{
    $sql = [

        "DROP TABLE IF EXISTS pnd_zones_tmp",
        "DROP TABLE IF EXISTS pnd_doctors_tmp",

        "CREATE TABLE pnd_zones_tmp LIKE pnd_zones",
        "CREATE TABLE pnd_doctors_tmp LIKE pnd_doctors",
    ];

    foreach ($sql as $q) {
        echo "[INIT] $q\n";
        if (!$DRY_RUN) $dst->q($q);
    }
}

recreateTmpTables($dst, $DRY_RUN);


// =====================================================================
// 2. ПЕРЕНОСИМ УЧАСТКИ (ID = внешний ID)
// =====================================================================
$sqlZones = "
    SELECT id, name
    FROM OrgStructure
    WHERE deleted = 0 and parent_id = 45
";

$zones = $src->q($sqlZones)->fetchAll();
echo "Loaded zones: " . count($zones) . "\n";

foreach ($zones as $z) {

    $id    = (int)$z['id'];
    $title = db_escape_string($z['name']);

    echo "[TMP ZONE] INSERT id={$id}, title={$title}\n";

    if (!$DRY_RUN) {
        $dst->q("
            INSERT INTO pnd_zones_tmp (id, title)
            VALUES ({$id}, '{$title}')
        ");
    }
}


// =====================================================================
// 3. ПЕРЕНОСИМ ВРАЧЕЙ (ID = внешний id, zone_id = внешний id участка)
// =====================================================================
$sqlDoctors = "
    SELECT 
        p.id AS external_id,
        CONCAT(p.lastName, ' ', p.firstName, ' ', p.patrName) AS full_name,
        rp.name AS post_name,
        rs.name AS speciality_name,
        p.office,
        p.orgStructure_id
    FROM Person p
    LEFT JOIN rbPost rp ON rp.id = p.post_id
    LEFT JOIN rbSpeciality rs ON rs.id = p.speciality_id
    WHERE p.deleted = 0 
        AND p.orgStructure_id > 0 
        AND `retireDate` IS NULL 
        AND speciality_id = 127 
";

$docs = $src->q($sqlDoctors)->fetchAll();
echo "Loaded doctors: " . count($docs) . "\n";

foreach ($docs as $d) {

    $id      = (int)$d['external_id'];
    $name    = db_escape_string($d['full_name']);
    $post    = db_escape_string($d['post_name']);
    $spec    = db_escape_string($d['speciality_name']);
    $office  = db_escape_string($d['office']);
    $zoneId  = (int)$d['orgStructure_id'];

    // Получаем JSON расписания
    $scheduleJson = db_escape_string(getDoctorSchedule($src, $id));

    echo "[TMP DOC] INSERT id={$id}, name={$name}\n";

    if (!$DRY_RUN) {
        $dst->q("
            INSERT INTO pnd_doctors_tmp
            (id, name, post_name, speciality_name, office, zone_id, schedule)
            VALUES (
                {$id}, '{$name}', '{$post}', '{$spec}', '{$office}', {$zoneId}, '{$scheduleJson}'
            )
        ");
    }
}


// =====================================================================
// 4. ЧИСТАЯ ПОДМЕНА ДАННЫХ БЕЗ RENAME TABLE
// =====================================================================
function replaceTables($dst, $DRY_RUN)
{
    $ops = [

        // очищаем основные таблицы
        "TRUNCATE TABLE pnd_zones",
        "TRUNCATE TABLE pnd_doctors",

        // переносим обновлённые данные из временных таблиц
        "INSERT INTO pnd_zones SELECT * FROM pnd_zones_tmp",
        "INSERT INTO pnd_doctors SELECT * FROM pnd_doctors_tmp",

        // удаляем временные таблицы
        "DROP TABLE pnd_zones_tmp",
        "DROP TABLE pnd_doctors_tmp",
    ];

    foreach ($ops as $q) {
        echo "[REPLACE] $q\n";
        if (!$DRY_RUN) $dst->q($q);
    }
}

replaceTables($dst, $DRY_RUN);


function getDoctorSchedule($src, $doctorId) {

    // Генерируем диапазон дат: -3 дня назад и +4 вперёд
    $startDate = date('Y-m-d', strtotime('-3 days'));
    $endDate   = date('Y-m-d', strtotime('+4 days'));

    $sql = "
        SELECT 
            DATE(e.execDate) AS day,
            MIN(apt.value) AS work_start,
            ADDTIME(MAX(apt.value), '00:20:00') AS work_end
        FROM Event e
            JOIN Action a ON e.id = a.event_id
            JOIN ActionType at ON a.actionType_id = at.id
            JOIN ActionPropertyType apT1 
                ON a.actionType_id = apT1.actionType_id AND apT1.name LIKE '%times%'
            JOIN ActionProperty ap1 
                ON a.id = ap1.action_id AND ap1.type_id = apT1.id
            JOIN ActionProperty_Time apt ON ap1.id = apt.id
        WHERE e.deleted = 0
          AND a.deleted = 0
          AND ap1.deleted = 0
          AND at.code = 'amb'
          AND e.eventType_id = 5
          AND e.execPerson_id = {$doctorId}
          AND DATE(e.execDate) BETWEEN '{$startDate}' AND '{$endDate}'
        GROUP BY DATE(e.execDate)
    ";

    $rows = $src->q($sql)->fetchAll();

    // Подготовка недели: day1..day7 = Пн..Вс
    $week = [
        1 => 'day1',
        2 => 'day2',
        3 => 'day3',
        4 => 'day4',
        5 => 'day5',
        6 => 'day6',
        7 => 'day7',
    ];

    // Заполняем пустыми днями
    $result = [
        'day1' => null,
        'day2' => null,
        'day3' => null,
        'day4' => null,
        'day5' => null,
        'day6' => null,
        'day7' => null,
    ];

    foreach ($rows as $r) {

        // 1 – воскресенье, нам нужно 1=Пн → 7=Вс
        $dayNum = date('N', strtotime($r['day'])); 

        $key = $week[$dayNum];

        $result[$key] = [
            'start' => $r['work_start'] ?: null,
            'end'   => $r['work_end'] ?: null,
        ];
    }

    return json_encode($result, JSON_UNESCAPED_UNICODE);
}


echo "\n--- DONE (DRY_RUN = " . ($DRY_RUN ? "YES" : "NO") . ") ---\n";
