<?php
/**
 * @author Pratik Dev <webmaster.pratik@gmail.com>
 */
header('Content-Type: application/json');
require_once '../config/init.php';
if (Input('submit') == 'list') {
    $db->join('users u', 'reports.user_id=u.id', "LEFT");
    $searchValue = dtsValue();
    if ($searchValue) {
        $db->where('id', $searchValue . '%', 'LIKE');
        $db->orWhere('user_id', '' . $searchValue . '%', 'LIKE');
    }
    if (Input('order')) {
        $column = dtOrderby();
        if ($column == 1) {
            $db->orderBy('user_id', dtOrderby(false));
        } elseif ($column == 4) {
            $db->orderBy('created_at', dtOrderby(false));
        } else
            $db->orderBy('id', dtOrderby(false));
    } else {
        $db->orderBy('id');
    }
    if (Input('length') != -1) {
        $reports = $db->withTotalCount()->get("reports", array(dtlimit(), dtlimit(false)),'reports.*,u.user_name');
    } else {
        $reports = $db->withTotalCount()->get("reports",null,'reports.*,u.user_name');
    }

    $numRows = $db->totalCount;
    $data = array();
    $extraText = '';
    foreach ($reports as $report) {
        $actionButton = '<div class="dropdown">
		<button class="btn btn-danger btn-sm dropdown-toggle" type="button" id="dropdownDelete" data-toggle="dropdown" aria-expanded="false">
			...
		</button>
		<div class="dropdown-menu" aria-labelledby="dropdownDelete">';
           $actionButton .= '<a id="' . $report['id'] . '" class="text-danger delete dropdown-item" href="#">Delete</a>';
            $actionButton .=		'</div>';
        $row = array();
        $row[] = $report['id'];
        $row[] = ($report['user_name']) ? '<a href="../user/show.php?id=' . $report['user_id'] . '">' . $report['user_name'] . '</a>' : "Admin";
        $row[] = $report['subject'];
        $row[] = $report['body'];
        $row[] = date('d M, y', strtotime($report['created_at']));
        $row[] = $actionButton;
        $data[] = $row;
    }
    $output = array(
        "draw"                =>    intval(Input('draw')),
        "recordsTotal"      =>  $numRows,
        "recordsFiltered"     =>     $numRows,
        "data"                =>   $data
    );
    echo json_encode($output);
} else if(Input('submit')=="delete"){
 
    $id = Input('id');
    $db->where('id',$id)->delete('reports');

  echo json_encode(['status'=>1,'message'=>'Delete Succesfuly']);
}
else if(Input('submit')== "multipledelete"){
    $ids = InputArray('ids');
    $cnt = 0;
    foreach ($ids as $id) {
        if ($id) {
            $report = $db->where('id', $id)->getOne('reports');
            if (!$report) {
               continue;
            }
            if ($db->where('id', $id)->delete('reports')) {
                $cnt++;
            }
        }
    }

    echo json_encode(['status'=>1,'message'=>'Deleted Total: '.$cnt.' Items']);
    
}

?>