<?php
/**
 * @author Pratik Dev <webmaster.pratik@gmail.com>
 */
header('Content-Type: application/json');
require_once '../config/init.php';
use Intervention\Image\ImageManagerStatic as Image;
use Intervention\Image\Exception\NotReadableException;

if(Input('submit')=='change'){
    $id = $_SESSION['id'];
    $username = Input('username');
    $email = Input('email');
    $oldpass = Input('old_pass');
    $newpass = Input('new_pass');
    $confirm_pass = Input('confirm_pass');

    if ($oldpass == '' || $username =='' || $email=='') {

        echo  json_encode(['status' => '0', 'message' => 'Please Fill Details']);
        exit;
    }

    if($newpass!=$confirm_pass){

      echo  json_encode(['status'=>'0','message'=>'Confirm Password does not match']);
      exit;
    }

    if($db->where('id',$id)->where('password',md5($oldpass))->has(TABLE_ADMIN)){
 
        if($newpass){
      $db->where('id',$id)->update(TABLE_ADMIN,['username'=>$username,'email'=>$email,'password'=>md5($newpass)]);
        } else {
            $db->where('id', $id)->update(TABLE_ADMIN, ['username' => $username, 'email' => $email]);
        }
        echo  json_encode(['status' => '1', 'message' => 'Successfuly Changed']);
        exit;
    } else {
        echo  json_encode(['status' => '0', 'message' => 'Old Password does not match']);
        exit;
    }
} else if (Input('submit') == 'list') {
    $searchValue = dtsValue();
    if ($searchValue) {
        $db->where('id', $searchValue . '%', 'LIKE');
        $db->orWhere('user_name', '' . $searchValue . '%', 'LIKE');
        $db->orWhere('name', '' . $searchValue . '%', 'LIKE');
        $db->orWhere('email', '' . $searchValue . '%', 'LIKE');
        $db->orWhere('mobile', '' . $searchValue . '%', 'LIKE');
    }
    if (Input('order')) {
        $column = dtOrderby();
        if ($column == 1) {
            $db->orderBy('user_name', dtOrderby(false));
        } elseif ($column == 6) {
            $db->orderBy('created_at', dtOrderby(false));
        } else
            $db->orderBy('id', dtOrderby(false));
    } else {
        $db->orderBy('id');
    }
    if (Input('length') != -1) {
        $users = $db->withTotalCount()->get("users", array(dtlimit(), dtlimit(false)));
    } else {
        $users = $db->withTotalCount()->get("users");
    }

    $numRows = $db->totalCount;
    $data = array();
    $extraText = '';
    foreach ($users as $user) {
        $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 class="dropdown-item" href="../files/index.php?userid='.$user['id'].'">Uploaded Songs</a>';
           $actionButton .= '<a id="' . $user['id'] . '" class="edit text-info dropdown-item" href="#">Edit</a>
            <a id="' . $user['id'] . '" class="text-danger delete dropdown-item" href="#">Delete</a>';
            $actionButton .=		'</div>';
        $row = array();
        $row[] = $user['id'];
        $row[] = $user['user_name'];
        $row[] = $user['name'];
        $row[] = $user['email'];
        $row[] = $user['mobile'];
        $row[] = $user['user_type'];
        $row[] = date('d M, y', strtotime($user['created_at']));
        $row[] = ($user['status'] == true) ? '<span id="' . $user['id'] . '" class="status btn btn-success btn btn-sm">Active</span>' : '<span id="' . $user['id'] . '" class="status btn btn-warning btn-sm">Block</span>';
        $row[] = $actionButton;
        $data[] = $row;
    }
    $output = array(
        "draw"                =>    intval(Input('draw')),
        "recordsTotal"      =>  $numRows,
        "recordsFiltered"     =>     $numRows,
        "data"                =>   $data
    );
    echo json_encode($output);
} elseif (Input('submit') == "statusUpdater") {
    $id = Input('id');
    $status = $db->where('id', $id)->getValue("users", 'status');

    if ($status == 1) {
        $data = ['status' => 0];
    } else {
        $data = ['status' => 1];
    }
    if ($db->where('id', $id)->update("users", $data)) {
        echo json_encode([
            'status' => 1,
            'message' => 'Status Updated'

        ]);
    } else {
        echo json_encode([
            'status' => 0,
            'message' => 'Invalid Authencation User'

        ]);
    }
} else if (Input('submit') == 'delete') {
    if ($db->where('id', Input('id'))->delete("users")) {
        $data = [
            'status' => 1,
            'message' => 'User Delete Successfuly'

        ];
    } else {
        $data = [
            'status' => 0,
            'message' => 'User Delete Unsuccessfuly'

        ];
    }
    echo json_encode($data);
} else if (Input('submit') == 'getOne') {
    $db->where('id', Input('id'));
    $userinfo = $db->getOne("users");
    $data = [
        'id' => $userinfo['id'],
        'user_name'=> $userinfo['user_name'],
        'name' => $userinfo['name'],
        'email' => $userinfo['email'],
        'mobile' => $userinfo['mobile'],
        'status' => $userinfo['status'],
    ];

    echo json_encode($data);
}
 elseif (Input('submit') == "edit") {

    $id = Input('id');
    $username = Input('username');
    $name = Input('name');
    $email = trim(Input('email'));
    $mobile = Input('phone');

    if (empty($id) || empty($username) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['status' => 0, 'message' => 'Please fill details or Email Invalid']);
        exit;
    }

    if ($db->where('id', $id, '!=')->where('email', $email)->has("users")) {
        echo json_encode(['status' => 0, 'message' => 'Email Already Exists']);
        exit;
    }

    if ($db->where('id', $id, '!=')->where('user_name', $username)->has("users")) {
        echo json_encode(['status' => 0, 'message' => 'Username Already Exists']);
        exit;
    }

    $userData = $db->where('id',$id)->getOne('users');

    $username = $username?$username:$userData['user_name'];
    $name = $name?$name:$userData['name'];
    $email = $email?$email:$userData['email'];
    $mobile = $mobile?$mobile:$userData['mobile'];


    $user = [
        'user_name' => $username,
        'name' => $name,
        'email' => $email,
        'mobile' => $mobile,
        'status' => Input('status'),
    ];
    if ($db->where('id', $id)->update("users", $user)) {
        echo json_encode(['status' => 1, 'message' => 'User Updated Successfuly']);
        exit;
    } else {
        echo json_encode(['status' => 0, 'message' => 'User Updated Failed']);
        exit;
    }
} else if (Input('submit') == 'delete') {

   $userinfo = $db->where('id', Input('id'))->getOne("users");

   if($userinfo){

    $ImgDir1 = $RootPath . '/upload_file/userthumb/40x40/'.$userinfo['user_name'].'.jpg';
    $ImgDir2 = $RootPath . '/upload_file/userthumb/150x150/'.$userinfo['user_name'].'.jpg';
    if(file_exists($ImgDir1) || file_exists($ImgDir2)){
        @unlink($ImgDir1);
        @unlink($ImgDir2);
    }

   }


    if ($db->where('id', Input('id'))->delete("users")) {
        $data = [
            'status' => 1,
            'message' => 'Report Delete Successfuly'

        ];
    } else {
        $data = [
            'status' => 0,
            'message' => 'Report Delete Unsuccessfuly'

        ];
    }
    echo json_encode($data);
} else if(Input('submit')== "multipledelete"){
    $ids = InputArray('ids');
    $cnt = 0;
    foreach ($ids as $id) {
        if ($id) {
            $userinfo = $db->where('id', $id)->getOne('users');
            if (!$userinfo) {
               continue;
            }

            $ImgDir1 = $RootPath . '/upload_file/userthumb/40x40/'.$userinfo['user_name'].'.jpg';
            $ImgDir2 = $RootPath . '/upload_file/userthumb/150x150/'.$userinfo['user_name'].'.jpg';
            if(file_exists($ImgDir1) || file_exists($ImgDir2)){
                @unlink($ImgDir1);
                @unlink($ImgDir2);
            }

            if ($db->where('id', $id)->delete('users')) {
                $cnt++;
            }
        }
    }

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