<?php 
include("../config.php");
if(!empty($_POST)){
    $per_date               = mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['per_date'])));
    $act_rec_date           = mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['act_rec_date'])));
    $status                 = mysqli_real_escape_string($conn, $_POST['status']);
    $created_datetime       = date('Y-m-d H:i:s');
    $created_id             = $_SESSION['user_detail']['id'];
    $updated_datetime       = date('Y-m-d H:i:s');
    $updated_id             = $_SESSION['user_detail']['id'];

if($_POST["id"] != ''){
    $type               = 'lr_permit_update';
    $user_id            = $_SESSION['user_detail']['id'];
    $data               = serialize($_POST);

    $targetDir = "../assets/upload/lr_permit/";
    $allowTypes = array('jpg','png','jpeg','gif');
    $errorUploadType = 0;
    if(!empty(array_filter($_FILES['product']['name']))){
        foreach($_FILES['product']['name'] as $key=>$val){
            $fileName       = rand(1,99999).'.'.basename($_FILES['product']['name'][$key]);
            $targetFilePath = $targetDir . $fileName;
            
            $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
            if(in_array($fileType, $allowTypes)) {
                if(move_uploaded_file($_FILES["product"]["tmp_name"][$key], $targetFilePath)){
                  $image = "INSERT INTO `image_master`(`ref_no`, `image`, `flag`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$_POST['id']."','".$targetFilePath."','LR_PERMIT','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
                  $img_res = mysqli_query($conn,$image) or die( mysqli_error($conn) );

                }else{
                    $errorUpload .= $_FILES['product']['name'][$key].', ';
                }
            } else {
                $errorUploadType .= $_FILES['product']['name'][$key].', ';
            }
        }
    }

    // update
    $user_query = "UPDATE `lr_mst` SET `per_date`='".$per_date."',`act_rec_date`='".$act_rec_date."',`status`='".$status."',`updated_id`='".$updated_id."',`updated_datetime`='".$updated_datetime."' WHERE `id`='".$_POST['id']."'";
    $user_result = mysqli_query($conn,$user_query) or die( mysqli_error($conn) );
    
    // activity
    $activiti = "INSERT INTO `activities`(`type`, `user_id`, `data`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$type."','".$user_id."','".$data."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
    $acttivity_res = mysqli_query($conn,$activiti);

  }

  echo json_encode( array('response' => 1, 'msg' => 'DATA SAVED SUCCESSFULLY....!!!', 'alert' => 1, 'redirect' => 'index.php?page=lr/list.php') );die();
}else{
  echo json_encode( array('response' => 2, 'msg' => 'Opps', 'alert' => 1, 'redirect' => BASE_URL . 'index.php?page=lr/add.php') );die();
}  
?>