<?php
require_once(dirname(__DIR__, 3) . '/init.php');

$type = m_u_p('type');
$slider_item_id = m_u_p('slider_item_id');
if ($type == 'data') {
    $item = slider_item($slider_item_id);
    $slider_Item = [
        'item_title' => $item['title'],
        'sub_title' => $item['subtitle'],
        'description' => $item['description'],
        'button_label_1' => $item['button1_label'],
        'button_link_1' => $item['button1_link'],
        'button_label_2' => $item['button2_label'],
        'button_link_2' => $item['button2_link'],
        'image' => $item['image'],
        'slider_item_id' => $item['id'],
        'short' => $item['short'],
    ];
    echo json_encode($slider_Item);
} else {
    $db = new DB();
    $slider_item_id = m_u_p('slider_item_id');
    $slider_id = m_u_p('slider_id');
    $image = m_u_p('image');
    $item_title = m_u_p('item_title');
    $subtitle = m_u_p('subtitle');
    $description = m_u_p('description');
    $button1_label = m_u_p('button1_label');
    $button1_link = m_u_p('button1_link');
    $button2_label = m_u_p('button2_label');
    $button2_link = m_u_p('button2_link');
    $short = m_u_p('short');
    if (!$short and $type == 'save'){
        $shortquery = $db->table('slideritems')->where('slider_id', '=', $slider_id)->order('id','desc')->get();
        $short = $shortquery['data'][0]['short']+1;
    }
    $data = [
        'slider_id' => $slider_id,
        'image' => $image,
        'title' => $item_title,
        'subtitle' => $subtitle,
        'description' => $description,
        'button1_label' => $button1_label,
        'button1_link' => $button1_link,
        'button2_label' => $button2_label,
        'button2_link' => $button2_link,
        'short' => $short,
    ];
    if ($type == 'save') {
        $query = $db->table('slideritems')->insert($data);
    }elseif ($type == 'delete'){
        $query = $db->table('slideritems')->where('id', '=', $slider_item_id)->delete();

        $query = $db->table('slideritems')->where('slider_id', '=', $slider_id)->order('short ','ASC')->get();

        $rows = $query['data'];
        $newOrder = 1;
        foreach ($rows as $row) {
            if ($row['id'] == $slider_item_id) {
                continue; // Silinen kaydı atla
            }

            $updateQuery = "UPDATE slideritems SET short = :newOrder WHERE id = :itemId";
            $updateStmt = $db->query($updateQuery , [':newOrder' => $newOrder, ':itemId' => $row['id']]);
            $newOrder++;
        }
    } else {
        $query = $db->table('slideritems')->where('id', '=', $slider_item_id)->update($data);
    }
    if ($query) {
        echo "Form başarıyla gönderildi!";
    } else {
        echo "Form başarıyla gönderilemedi!";

    }
}