<?php
    /*
        *****************************************************************************
        * MEGA Digital Space - by MEGA Digital Studio                               *
        * ------------------------------------------------------------------------- *
        * CMS Website:  https://megadigital.space                                   *
        * License:  https://megadigital.space/license                               *
        * Owner:  Giorgi Basharuli                                                  *
        * Contact:  online@megadigital.studio                                       *
        * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
        * Website:  https://megadigital.studio                                      *
        * ------------------------------------------------------------------------- *
        * Description: This file is a part of the MEGA Digital Space CMS system.    *
        * Unauthorized distribution, modification, or commercial use is strictly -  *
        * prohibited without prior written permission.                              *
        * ------------------------------------------------------------------------- *
        * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
        * All rights reserved.                                                      *
        *****************************************************************************
    */

    require_once(ENGINE_DIR . '/data/config.php');
    use Twilio\Rest\Client;

    global $db_connect, $lang;
    date_default_timezone_set('UTC');

    try {
        $twilio = new Client(
            $config["twilio_provider"]["username"],
            $config["twilio_provider"]["password"]
        );
        $twilioFrom = $config["twilio_provider"]["twilio_phone_number"];
        $balance = $twilio->api->v2010->balance->fetch();
    } catch (Exception $e) {
        $balance = 0;
    }


    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['action'] == "add_to_schedule") {

        $title = trim($_POST['title'] ?? '');
        $type = $_POST['type'] ?? '';
        $content_text = trim($_POST['content_text'] ?? '');
        $scheduled_at = $_POST['scheduled_at'] ?: null;
        $role_id = $_POST['role_id'] ?: null;
        $class_id = $_POST['class_id'] ?: null;
        $action = $_POST['action'] ?? 'save';
        $created_by = $_SESSION['user_id'];
        $userIds = $_POST['user_ids'] ?? [];

        if (!$title || !$type) {
            exit('TITLE_OR_TYPE_EMPTY');
        }
        $status = $action === 'add_to_schedule' ? 'queued' : 'sending';

        $dt = new DateTime($scheduled_at, new DateTimeZone('Asia/Yerevan')); // подставь нужную

        $dt->setTimezone(new DateTimeZone('UTC'));

        $utc_scheduled_at = $dt->format('Y-m-d H:i:s');

        $db_connect->insert('mailings', [
            'title'        => $title,
            'type'         => $type,
            'status'       => $status,
            'created_by'   => $created_by,
            'scheduled_at' => $utc_scheduled_at,
            'created_at'   => gmdate('Y-m-d H:i:s')
        ]);
        $mailing_id = $db_connect->id();
        if (!$mailing_id) exit('INSERT_FAILED');

        $content_media_path = null;

        if (!empty($_POST['content_audio'])) {
            $audioData = $_POST['content_audio'];

            // Убираем префикс base64
            if (preg_match('/^data:audio\/\w+;base64,/', $audioData)) {
                $audioData = preg_replace('/^data:audio\/\w+;base64,/', '', $audioData);
            }

            $audioData = base64_decode($audioData);

            if (!is_dir('uploads/audios')) mkdir('uploads/audios', 0777, true);
            $tmpWebm = 'uploads/audios/tmp_' . $mailing_id . '_' . time() . '.webm';
            file_put_contents($tmpWebm, $audioData);

            $filename = 'uploads/audios/audio_' . $mailing_id . '_' . time() . '.wav';
            exec(
                "ffmpeg -y -i " . escapeshellarg($tmpWebm) .
                " -ar 8000 -ac 1 -c:a pcm_mulaw " .
                escapeshellarg($filename)
            );

            unlink($tmpWebm);

            $content_media_path = $filename;
        }

        $content_image_path = null;
        if ($type === 'text_graphic_sms' && !empty($_FILES['content_image']) && $_FILES['content_image']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = 'uploads/images/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
            $ext = pathinfo($_FILES['content_image']['name'], PATHINFO_EXTENSION);
            $filename = $uploadDir . 'img_' . $mailing_id . '_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['content_image']['tmp_name'], $filename)) {
                $content_media_path = $filename;
            }
        }

        $baseUrl = $_SERVER["HTTP_ORIGIN"] ?? "https://".$_SERVER["HTTP_HOST"];
        $content_media_path = $baseUrl . '/uploads/' . ($type === 'text_graphic_sms' ? 'images/' : 'audios/') . basename($content_media_path);

        $db_connect->insert('mailing_contents', [
            'mailing_id' => $mailing_id,
            'channel' => $type,
            'text' => $content_text ?: null,
            'media_url' => $content_media_path,
        ]);

        $users = [];
        if ($role_id && $class_id) {
            $role = $db_connect->get('roles', '*', ['id' => $role_id]);
            if ($role['name'] === 'Parent') {
                $users = $db_connect->select('users', [
                    "[>]users_roles" => ["users.id" => "user_id"],
                    "[>]parents_students(ps)" => ["users.id" => "parent_id"],
                    "[>]class_students(cs)" => ["ps.student_id" => "student_id"]
                ], ["users.id"], [
                    "users_roles.role_id" => $role_id,
                    "cs.class_id" => $class_id,
                    "GROUP" => "users.id"
                ]);
            } elseif ($role['name'] === 'Teacher') {
                $users = $db_connect->select('users', [
                    "[>]users_roles" => ["users.id" => "user_id"],
                    "[>]teacher_classes(tc)" => ["users.id" => "teacher_id"]
                ], ["users.id"], [
                    "users_roles.role_id" => $role_id,
                    "tc.class_id" => $class_id,
                    "GROUP" => "users.id"
                ]);
            } else {
                $users = $db_connect->select('users', [
                    "[>]users_roles" => ["users.id" => "user_id"]
                ], ["users.id"], [
                    "users_roles.role_id" => $role_id
                ]);
            }
        } elseif ($role_id) {
            $users = $db_connect->select('users', [
                "[>]users_roles" => ["users.id" => "user_id"]
            ], ["users.id"], [
                "users_roles.role_id" => $role_id
            ]);
        } elseif ($class_id) {
            $users = $db_connect->select('users', [
                "[>]class_students(cs)" => ["users.id" => "cs.student_id"]
            ], ["users.id"], [
                "cs.class_id" => $class_id
            ]);
        }

        $queueData = [];
        if (!empty($userIds)) {
            foreach ($userIds as $userId) {
                $queueData[] = [
                    'mailing_id' => $mailing_id,
                    'user_id' => $userId,
                    'channel' => $type,
                    'status' => 'pending'
                ];
            }
        } else {
            if (!empty($users) && $status === 'queued') {
                foreach ($users as $user) {
                    $queueData[] = [
                        'mailing_id' => $mailing_id,
                        'user_id' => $user["id"],
                        'channel' => $type,
                        'status' => 'pending'
                    ];
                }
            }
        }

        if ($queueData) $db_connect->insert('mailing_queue', $queueData);

        header("Location: ".$_SERVER['HTTP_REFERER']);
        exit;
    }


    if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['delete_mailing_id'])) {
        $mailing_id = $_POST['delete_mailing_id'];

        $db_connect->delete('mailings', ['id' => $mailing_id]);
        $db_connect->delete('mailing_contents', ['mailing_id' => $mailing_id]);
        $db_connect->delete('mailing_queue', ['mailing_id' => $mailing_id]);
    }

    $where = ['ORDER' => ['created_at' => 'DESC']];

    if (!empty($_GET["status"])) {
        $where["status"] = $_GET["status"];
    }
    $smarty->assign('filter_status', $_GET['status']);

    $mailings = $db_connect->select('mailings', [
        'id',
        'title',
        'type',
        'status',
        'created_by',
        'created_at',
        'scheduled_at'
    ], $where);

    if (!empty($mailings)) {
        foreach ($mailings as &$m) {
            $m['creator_name'] = $db_connect->get('users', 'name', ['id' => $m['created_by']]);

            $m[$lang["datatable"]["type"]] = $lang["datatable"][$m["type"]];
            $m[$lang["datatable"]["scheduled_at"]] = $m["scheduled_at"];
            $m[$lang["datatable"]["creator_name"]] = $m["creator_name"];
            $m[$lang["datatable"]["title"]] = $m["title"];

            if ($m["status"] == "draft") {
                $m[$lang["datatable"]["status"]] = '<span class="badge bg-secondary">Черновик</span>';
            } else if ($m["status"] == "queued") {
                $m[$lang["datatable"]["status"]] = '<span class="badge bg-warning text-dark">В очереди</span>';
            } else if ($m["status"] == "sending") {
                $m[$lang["datatable"]["status"]] = '<span class="badge bg-info text-dark">Отправляется</span>';
            } else if ($m["status"] == "done") {
                $m[$lang["datatable"]["status"]] = '<span class="badge bg-success">Завершено</span>';
            } else if ($m["status"] == "failed") {
                $m[$lang["datatable"]["status"]] = '<span class="badge bg-danger">Ошибка</span>';
            }

            $m[$lang["datatable"]["actions"]] = "
                                <form method='POST' action='/admin?action=message-distribution-managing' style='display:inline;'>
                                    <input type='hidden' name='delete_mailing_id' value='{$m['id']}'>
                                    <button type='submit' class='no-b mx-1' onclick='return confirm(`Вы уверены, что хотите удалить?`);'>
                                        <i class='fa fa-trash'></i>
                                    </button>
                                </form>";
        }
        unset($m);
    }


    $roles = $db_connect->select("roles", "*");

    $classes = [];
    if ($config["extensions"]["education"]["enabled"] === true) {
        $classes = $db_connect->select("classes", "*");
    }

    // Передаем данные в Smarty
    $smarty->registerPlugin('modifier', 'json_encode', function($value) {
        return json_encode($value);
    });
    $smarty->assign('mailings', $mailings);
    $smarty->assign('roles', $roles);
    $smarty->assign('classes', $classes);
    $smarty->assign('twilio_balance', $balance->balance);
    $smarty->assign('twilio_currency', $balance->currency);

    $yourData = array('title' => $lang['nav']['messagedistributionmanaging'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active">' . $lang['nav']['messagedistributionmanaging'] . '</li>
    ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);