<?php 
    if(!isset($_GET["id"]) || empty($_GET["id"])){
        header("Location: /admin/support-tickets/list");
        exit();
    }
    $ticket = $support->getTicket($_GET["id"]);
    $support_status = $support->getSupportStatus();
    if(empty($ticket)){
        header("Location: /admin/support-tickets/list");
        exit();
    }

    $data = array();
    $data['title'] = "Destek Talebi Detayları | ".$App->title;
    $data['links'] = [];
    $data['styles'] = [];
    $data['header']['scripts'] = [];
    $data['version'] = $App->version;
    $data['csrf_token'] = $csrf_generator->create();
    $data['sidebar_menu'] = $menu->get(array('position'=>'sidebar'));
    $data['sidebar_active_menu'] = $menu->getActiveMenuItemId(trim($_SERVER['REQUEST_URI']));
    $data['footer']['scripts'] = [];
    $menu_items = $menu->get(array('position'=>'footer'));
    foreach($menu_items as $item){
        if($item['col'] == "1"){
            $data['menu']['footer']["1"][] = $item;
        }
        if($item['col'] == "2"){
            $data['menu']['footer']["2"][] = $item;
        }
        if($item['col'] == "3"){
            $data['menu']['footer']["3"][] = $item;
        }
        if($item['col'] == "4"){
            $data['menu']['footer']["4"][] = $item;
        }
    }

    $data['breadcrumbs'] = array();
    $data['breadcrumbs'][] = array(
        'text' => "Pano",
        'href' => "/admin",
        'index' => 1
    );
    $data['breadcrumbs'][] = array(
        'text' => "Destek Talepleri",
        'href' => "/admin/support-tickets/list",
        'index' => 2
    );
    $data['breadcrumbs'][] = array(
        'text' => "Destek Talebi Detayları",
        'href' => "#",
        'index' => 3
    );

    $response = array();
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        $message            = $_POST['message'];
        $status             = $_POST['status'];

        $stmt = $db->query("UPDATE {$db->prefix}support_tickets SET `status`=:status, `date_updated`=NOW() WHERE id=:id",array(':status'=>$status, ':id'=>$_GET["id"]));
        if($stmt->error){
            $utils->errorLog("error", "Cannot update support ticket. Error: ".$stmt->error_info['message'], $session->data['user_id'], $_SERVER['REQUEST_URI']);
            $session->data['messageType'] = "error"; 
            $session->data['messageTitle'] = "Hata!"; 
            $session->data['message'] = "Bir hata oluştu ve talep güncellenemedi."; 
        }else{
            if(!empty($message)) {
                $db->query("INSERT INTO {$db->prefix}support_comments (`ticket_id`, `user_id`, is_agent, `user_name`, `content`, `date_added`) VALUES (:ticket_id, :user_id, 1, :user_name, :content, NOW())", array(':ticket_id'=>$ticket['id'], ':user_id'=>$session->data['user_id'], ':user_name'=>$session->data['user_name'], ':content'=>$message));
            }

            $user_email = $user->getUserEmail($ticket['user_id']);
            $email_template = file_get_contents(DIR_COMMON.'/email/templates/support-ticket-updated.html');
            $email_template = str_replace('%ticket_id%', $ticket['code'], $email_template);
            $email_template = str_replace('%base_url%', $App->url, $email_template);
            
            $email->send(
                array(
                    'to'                 => array(array('email'=>$user_email, 'name'=>$ticket['user_name'])),
                    'is_html'            => true,
                    'subject'            => "Destek talebiniz güncellendi.",
                    'body'               => $email_template
                )
            );

            $session->data['messageType'] = "success"; 
            $session->data['messageTitle'] = "Başarılı!"; 
            $session->data['message'] = "Destek talebi başarıyla güncellendi. Kullanıcı bilgilendirildi."; 
            
            $ticket = $support->getTicket($_GET["id"]);
        }
	}
?>
<?php include DIR_VIEWS."parts/header.php"; ?>
        <main class="content">
            <div class="container-fluid">
                <form action="" method="post">
                    <div class="row flex-column-reverse flex-md-row">
                        <div class="col-md-8">
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Cevaplar</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row my-3">
                                        <div class="col-12 text-center">
                                            <button type="button" class="btn btn-primary" data-bs-toggle="collapse" data-bs-target="#collapse-support" aria-expanded="false" aria-controls="collapse-support"><i class="bi bi-pencil me-2"></i> Cevap Yaz</button>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-12">
                                            <div class="collapse" id="collapse-support">
                                                <div class="row">
                                                    <div class="col-12 mb-3">
                                                        <textarea name="message" id="message" rows="5" class="form-control editor"></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row my-3">
                                        <div class="col-12">
                                            <?php if(!empty($ticket['comments'])): ?>
                                                <?php foreach($ticket['comments'] as $comment): ?>
                                                    <div class="card mb-3">
                                                        <div class="card-header <?php echo $comment['user_id'] != $session->data['user_id'] ? 'bg-light' : ''; ?>">
                                                            <span><?php echo $comment['is_agent'] == 0 ? '<i class="bi bi-person-fill me-1"></i>' : '<i class="bi bi-headset"></i>'; ?> <?php echo $comment['user_name']; ?></span>
                                                            <span><?php echo $comment['date_added']; ?></span>
                                                        </div>
                                                        <div class="card-body">
                                                            <?php echo $comment['content']; ?>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                            <div class="card mb-3">
                                                <div class="card-header bg-light">
                                                    <span><i class="bi bi-person-fill me-1"></i> <?php echo $ticket['user_name']; ?></span>
                                                    <span><?php echo $ticket['date_added']; ?></span>
                                                </div>
                                                <div class="card-body">
                                                    <?php echo $ticket['message']; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Talep Detayları</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-12">
                                            <div class="d-block mb-2">
                                                <span><strong>Kod:</strong> <?php echo $ticket['code']; ?></span>
                                            </div>
                                            <div class="d-block mb-2">
                                                <span><strong>Konu:</strong> <?php echo $ticket['subject']; ?></span>
                                            </div>
                                            <div class="d-block mb-2">
                                                <span><strong>Durum:</strong> <?php echo $ticket['status_text']; ?></span>
                                            </div>
                                            <div class="d-block mb-2">
                                                <span><strong>Öncelik:</strong> <?php echo $ticket['priority']; ?></span>
                                            </div>
                                            <div class="d-block mb-2">
                                                <span><strong>Talep Sahibi:</strong> <a href="/admin/users/edit?user_id=<?php echo $ticket['user_id']; ?>" target="_blank"><?php echo $ticket['user_name']; ?></a></span>
                                            </div>
                                            <div class="d-block mb-2">
                                                <span><strong>Gönderim Tarihi:</strong> <?php echo $ticket['date_added']; ?></span>
                                            </div>
                                            <div class="d-block">
                                                <span><strong>Son Güncelleme:</strong> <?php echo $ticket['date_updated']; ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer text-center">
                                    <a href="/admin/support-tickets/list" class="btn btn-sm btn-primary me-2"><i class="bi bi-reply"></i> Geri</a>
                                    <button type="submit" name="save" id="save" class="btn btn-sm btn-success px-3">Güncelle</button>
                                </div>
                            </div>
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Durum</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-12">
                                            <select name="status" id="status" class="form-control form-select">
                                                <option value="">Seçiniz</option>
                                                <?php foreach ($support_status as $s): ?>
                                                    <option value="<?php echo $s["id"]; ?>" <?php echo $s["id"] == $ticket['status'] ? 'selected' : ''; ?>><?php echo $s["title"]; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </main>
<?php include DIR_VIEWS."parts/footer.php"; ?>