<?php 
    if(!isset($_GET["id"]) || empty($_GET["id"])){
        header("Location: /admin/inbox/contactlist");
        exit();
    }
    $inboxApi  	          = new InboxApi($db, $utils);
    $contacts             = $inboxApi->getContacsOfList($_GET['id']);

    $data = array();
    $data['title'] = "INBOX Kişiler | ".$App->title;
    $data['links'] = [];
    $data['styles'] = ['/admin/public/assets/css/jstable.css'];
    $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'] = ['/admin/public/assets/js/pages/inbox/contactlist-edit.js', '/admin/public/assets/js/jstable.min.js'];
    $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' => "INBOX Kişi Listesi",
        'href' => "/admin/inbox/contactlist",
        'index' => 2
    );
    $data['breadcrumbs'][] = array(
        'text' => "Kişiler",
        'href' => "#",
        'index' => 3
    );

    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        if(isset($_POST['action']) && !empty($_POST['action'])) {
            switch($_POST['action']) {
                case 'single-contact':
                    $email_        = $_POST['email'];

                    $response = $inboxApi->createContact($email_, $_GET['id']);
                    if(!$response['status']){
                        $session->data['messageType'] = "error"; 
                        $session->data['messageTitle'] = "Hata!"; 
                        $session->data['message'] = $response['message'];
                        header("Refresh: 1;");
                        exit();
                    }else{
                        $session->data['messageType'] = "success"; 
                        $session->data['messageTitle'] = "Başarılı!"; 
                        $session->data['message'] = "Kişi başarıyla kaydedildi. Eposta: <b>".$email_."</b>"; 
                        header("Refresh: 1;");
                        exit();
                    }
                break;
                case 'import':
                    if(!isset($_FILES['contacts']) || !file_exists($_FILES['contacts']['tmp_name']) || !is_uploaded_file($_FILES['contacts']['tmp_name'])) {
                        $session->data['messageType'] = "error"; 
                        $session->data['messageTitle'] = "Hata!"; 
                        $session->data['message'] = "Lütfen bir dosya seçin";
                        header("Refresh: 1;");
                        exit();
                    }else{

                        $file = $_FILES['contacts']['name'];
                        $tmp = explode('.', $file);
                        $extension = strtolower(end($tmp));
                        $path_parts = pathinfo($file);
                        $filename = $path_parts['filename'];
            
                        if($extension == "xlsx"){
                            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
                        }else if($extension == "xls"){
                            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
                        }else if($extension == "csv"){
                            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
                        }else{
                            $session->data['messageType'] = "error"; 
                            $session->data['messageTitle'] = "Hata!"; 
                            $session->data['message'] = "Lütfen geçerli bir excel dosyası seçin.";
                            header("Refresh: 1;");
                            exit();
                        }

                        $spreadsheet    = $reader->load($_FILES['contacts']['tmp_name']);
                        $sheetData      = $spreadsheet->getActiveSheet()->toArray();
                        $count          = count($sheetData);

                        if($count <= 0) {
                            $session->data['messageType'] = "error"; 
                            $session->data['messageTitle'] = "Hata!"; 
                            $session->data['message'] = "Kayıt bulunamdı. Lütfen geçerli bir excel dosyası seçin."; 
                            header("Refresh: 1;");
                            exit();
                        }
                        $email_list = array();
                        for($i=1; $i<$count; $i++){
                            $email_list[] = array('email' => $sheetData[$i][0], 'customFields'=>array());
                        }

                        $response = $inboxApi->importContacts($email_list, $_GET['id']);
                        if(!$response['status']){
                            $session->data['messageType'] = "error"; 
                            $session->data['messageTitle'] = "Hata!"; 
                            $session->data['message'] = $response['message'];
                            header("Refresh: 1;");
                            exit();
                        }else{
                            $session->data['messageType'] = "success"; 
                            $session->data['messageTitle'] = "Başarılı!"; 
                            $session->data['message'] = "Kişi başarıyla kaydedildi."; 
                            header("Refresh: 1;");
                            exit();
                        }
                    }
                break;
            }
            
        }
	}
?>
<?php include DIR_VIEWS."parts/header.php"; ?>
        <main class="content">
        <div class="container-fluid">
                <div class="row">
                    <div class="col-md-4 col-xl-3">
                        <div class="card">
                            <div class="list-group list-group-flush" id="profile-settings" role="tablist">
                                <a class="list-group-item list-group-item-action active" data-bs-toggle="tab" href="#contactsTab" aria-selected="true">Kişiler</a>
                                <a class="list-group-item list-group-item-action" data-bs-toggle="tab" href="#importTab" aria-selected="false">İçe Aktar</a>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-8 col-xl-9">
                        <div class="tab-content" id="tab-content">
                            <div class="tab-pane fade active show" id="contactsTab" role="tabpanel">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title">Kişiler</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row mb-2 d-none">
                                            <div class="col-12">
                                                <input type="search" id="search-input" class="form-control" value="">
                                            </div>
                                        </div>
                                        <div class="table-responsive">
                                            <table class="table table-striped table-hover table-bordered mb-0" id="contacts-table">
                                                <thead>
                                                    <tr>
                                                        <th>ID</th>
                                                        <th>Email</th>
                                                        <th>Rank</th>
                                                        <th style="width: 120px"></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                        if(count($contacts)>0) {
                                                            foreach($contacts as $row) {
                                                                echo "<tr>
                                                                            <td>".$row['id']."</td>
                                                                            <td>".$row['email']."</td>
                                                                            <td>".$row['rank']."</td>
                                                                            <td style=\"width: 150px;vertical-align: middle;\" class=\"text-center\">
                                                                                <button class=\"btn btn-sm btn-danger\" data-delete data-href=\"/admin/inbox/contacts/delete?contact_id=".$row['id']."\"><i class=\"bi bi-trash\"></i></button>
                                                                            </td>
                                                                        </tr>";
                                                            }
                                                        }else{
                                                            echo "<tr class=\"text-center\"><td colspan=\"6\">Hiçbir kayıt bulunamadı!</td></tr>";
                                                        }
                                                    ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="tab-pane fade" id="importTab" role="tabpanel">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title">İçe Aktar</h5>
                                    </div>
                                    <div class="card-body">
                                        <form action="" method="post">
                                            <div class="row mb-3">
                                                <div class="col-md-3">
                                                    <label for="email" class="col-form-lable fw-bold">Tek kişi</label>
                                                </div>
                                                <div class="col-md-9">
                                                    <div class="input-group mb-3">
                                                        <input type="email" name="email" id="email" class="form-control" placeholder="john@example.com" required>
                                                        <button type="submit" class="btn btn-primary">Kaydet</button>
                                                    </div>
                                                </div>
                                            </div>
                                            <input type="hidden" name="action" value="single-contact">
                                        </form>
                                        <hr>
                                        <form action="" method="post" enctype="multipart/form-data">
                                            <div class="row mb-3 mt-5">
                                                <div class="col-md-3">
                                                    <label for="contacts" class="col-form-lable fw-bold">Toplu Kişi Listesi</label>
                                                </div>
                                                <div class="col-md-9">
                                                    <div class="input-group mb-3">
                                                        <input type="file" name="contacts" id="contacts" class="form-control" accept="csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" required>
                                                        <button type="submit" class="btn btn-primary">Gönder</button>
                                                    </div>
                                                </div>
                                            </div>
                                            <input type="hidden" name="action" value="import">
                                        </form>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </main>
<?php include DIR_VIEWS."parts/footer.php"; ?>
<script>
    var table = new JSTable("#contacts-table", {
        serverSide : false,
        perPage : 15,
        labels: {
            placeholder: "Ara...",
            perPage: "sayfa başına kayıt",
            noRows: "Hiçbir kayıt bulunamadı!",
            info: "{rows} kayıttan {start} - {end} arası görüntüleniyor",
            loading: "Yükleniyor...",
            infoFiltered: "{rows} kayıttan {start} - {end} arası görüntüleniyor ({rowsTotal} kayıt arasından filtrelendi)"
        },
        layout: {
            top: "{search}",
            bottom: "{info}{pager}"
        }
    });
</script>