<?php
require_once("../layouts/members/head.php");

function sanitize_input($input) {
    $input = str_replace(["\r", "\n"], ' ', $input);
    return trim($input);
}
?>
<div class="row">
<?php
if(in_array($user_data['usertype'], ['White Label','Master Distributor','Distributor','Retailer'])){ 
?>   
<?php
if(isset($_POST['complaint']) && $user_data['user_id']>0){
$complaint_type = safe_str($_POST['complaint_type']);
$message = isset($_POST['message']) ? sanitize_input($_POST['message']) : '';
$utr_number = safe_str($_POST['utr_number'] ?? '');
if(!empty($complaint_type) && !empty($message) ){
$txn_countmobi = !empty($user_data['username']) ? db_count("complaints", "username='" . $user_data['username'] . "' AND status='Open'") : 0;  
$txn_count = !empty($utr_number) ? db_count("complaints", "utrnumber='" . $utr_number . "'") : 0;
if ($txn_countmobi < 5) {
if ($txn_count == 0) {
$insData = array();
$insData['site_id'] = $site_data['site_id'];
$insData['user_id'] = $user_data['user_id'];
$insData['username'] = $user_data['username'];
$insData['complaint_type'] = $complaint_type;
$insData['utrnumber'] = $utr_number ?? '';
$insData['message'] = $message;
$insData['remark'] = "";
$insData['date_time'] = current_timestamp();;
$insData['status'] = "Open";
$complaint_id = db_insert("complaints", $insData);
if($complaint_id){
$emailmessage = "Dear {$user_data['name']}, Your Complaint Message : <strong>{$message}</strong>.";    
                    
$whamessage = "Dear {$user_data['name']},\n" .
"Your Complaint for *{$complaint_type}* has been successfully Raised.\n" .
"*Message*: {$message}\n\n" .
"Note: _*Your Problem Solve Under 3 Hours.*_\n\n" .
"Best Regards,\n" .
"_*{$site_data['brand']}.*_";

//admin alert message on whatsaapp
send_sms_credentials($site_data['username'],$whamessage);

// users message 
send_sms_credentials($user_data['mobile'],$whamessage);
send_email($user_data['email'],"Complaint For $complaint_type",$emailmessage);
awal_alert_msg("Complaint Submit Successfully!<br>Complaint ID : #{$complaint_id}",'success','');  
}else{
awal_alert_msg("Server Error!",'info');  
}
}else{
awal_alert_msg("Your Request Now Under Process Please Be Patient!",'error');
}
}else{
awal_alert_msg("You Reach Maximum Complaint!",'error');
}
}else{
awal_alert_msg("Please Fill All Valid Details!",'error');
}

}
?>

  <div class="col-md-12 mb-2">
    <div class="card text-dark">
      <div class="card-header bg-primary text-white py-2">
        <div class="d-flex align-items-center">
          <span class="mr-auto"><?=file_name()?></span>
        </div>
      </div>
      <div class="p-3">
      <form class="row text-dark" method="POST" action="">
        <div class="col-md-12 mb-3">
          <label for="complaintType">Select Service</label>
          <select class="form-control" id="complaintType" name="complaint_type" required>
            <option value="" disabled selected>--Select--</option>
          </select>
        </div>
        <div class="col-md-12 mb-3" id="utrNumberField" style="display: none;">
          <label>UTR Number</label>
          <input type="text" class="form-control" name="utr_number" id="utrNumber" placeholder="Enter UTR Number">
        </div>
        <div class="col-md-12 mb-3">
          <label>Complaint</label>
          <textarea class="form-control" name="message" placeholder="Enter Complaint" required></textarea>
        </div>
        <div class="col-md-12 mb-3">
          <button type="submit" class="btn btn-primary btn-block" name="complaint">Submit</button>
        </div>
      </form>
     </div>
    </div>
  </div>

   <div class="col-md-12 mb-2">
    <div class="card text-dark">
      <div class="card-header bg-primary text-white py-2">
        <div class="d-flex align-items-center">
          <span class="mr-auto">List Of Complaint</span>
        </div>
      </div>
      <div class="card-body p-0">
        <form class="row px-4 py-3" method="POST" action="">
          <div class="col-md-3 mb-2">
           <label>From Date</label>  
           <input type="date" name="fromDate" value="<?=date("Y-m-d")?>" class="form-control" required>
          </div>
          <div class="col-md-3 mb-2">
           <label>To Date</label>  
           <input type="date" name="toDate" value="<?=date("Y-m-d")?>" class="form-control" required>
          </div>
          <div class="col-md-3 mb-2">
           <label>Status</label>  
           <select name="status" class="form-control">
             <option value="">Select</option>
             <option value="Open">Open</option>
             <option value="Close">Close</option>
           </select>
          </div>
          <div class="col-md-3 mb-2">
           <label>&nbsp;</label>
           <button type="submit" name="search" class="btn btn-primary btn-block">Search</button>
          </div>
        </form>

       <div class="table-responsive scroll">
        <table class="table w-100" id="dataTable">
          <thead>
            <tr class="bg-secondary">
              <th class="d-none">SL No.</th>
              <th>Complaint ID</th>
              <th>Date Time</th>
              <th>Type</th>
              <th>Complaint</th>
              <th>Admin Remark</th>
              <th>Status</th>
              <th>UserID</th>
            </tr>
          </thead>
          <tbody>

<?php
$fromDate = date("Y-m-d"); 
$toDate = date("Y-m-d");
$status = false;
if(isset($_POST['search'])){
$fromDate = date("Y-m-d", strtotime($_POST['fromDate'])); 
$toDate = date("Y-m-d", strtotime($_POST['toDate']));
$status = safe_clean($_POST['status']);
}

$condition = "date_time>='".$fromDate." 00:00:00' AND date_time<='".$toDate." 23:59:59' ";


 if (in_array($user_data['user_id'], ['1']) && in_array($user_data['usertype'], ['Admin'])) { 
$condition .= '';
}else{
$condition .= " AND user_id='".$user_data['user_id']."'";  
}


if(!empty($status)){
$condition .= " AND status ='".$status."'";    
}

$response = db_fetch_all("complaints", "$condition ORDER BY complaint_id DESC");
$sl=1;
foreach ($response as $key => $value) {
$value['date_time'] = date("d-M-Y h:i:s A",strtotime($value['date_time']));

if(in_array($value['status'],['Close'])){
$status = '<span class="badge badge-success"><span class="oi oi-circle-check pulse mr-1"></span>'.$value['status'].'</span>';
}else if(in_array($value['status'],['Open'])){
$status = '<span class="badge badge-danger"><span class="oi oi-media-record pulse mr-1"></span>'.$value['status'].'</span>';
}

?>

            <tr>
              <td class="d-none"><?=$sl?></td>
              <td>#<?=$value['complaint_id']?></td>
              <td><?=$value['date_time']?></td>
              <td><?=$value['complaint_type'] . (!empty($value['utrnumber']) ? "<br><strong>UTR:</strong> {$value['utrnumber']}" : "")?></td>
              <td><textarea class="form-control form-control-sm" style="height:50px;" readonly><?=$value['message']?></textarea></td>
              <td><textarea class="form-control form-control-sm" style="height:50px;" readonly><?=$value['remark']?></textarea></td>
              <td><?=$status?></td>
              <td><?=$value['username']?></td>
            </tr>
<?php
$sl++;}
?>            
            
          </tbody>
        </table>
       </div>

     </div>
    </div>
  </div>
  <script>
  document.getElementById('complaintType').addEventListener('change', function() {
    const utrField = document.getElementById('utrNumberField');
    const utrInput = document.getElementById('utrNumber');

    if (this.value === 'ADD MONEY') {
      utrField.style.display = 'block';
      utrInput.setAttribute('required', 'required');
    } else {
      utrField.style.display = 'none';
      utrInput.removeAttribute('required');
    }
  });
</script>
<?php 
}
?>

<!--If admin then access this code -->
<?php if (in_array($user_data['user_id'], ['1']) && in_array($user_data['usertype'], ['Admin']) && in_array($user_data['user_id'], ['1'])) { ?>  

<?php

if(isset($_POST['close']) && $user_data['user_id']>0 && in_array($user_data['usertype'], ['Admin'])){
$complaint_id = safe_str($_POST['complaint_id']);
$remark = isset($_POST['remark']) ? sanitize_input($_POST['remark']) : '';
if(!empty($complaint_id) && !empty($remark) ){
$insData = array();
$insData['remark'] = $remark;
$insData['status'] = "Close";
if(db_update("complaints", $insData," complaint_id='".$complaint_id."' ")){
 $condition = "mobile='".$_POST['phonenumber']."' ";
$complaintuserss = db_fetch_all("members",$condition);
$emailmessage = "Dear {$complaintuserss['0']['name']},Message :{$remark}.";    
                    
$whamessage = "Dear {$complaintuserss['0']['name']},\n" .
"Your Complaint for *{$_POST['complaint_type']}* has been successfully Close.\n" .
"*Message*: {$remark}\n\n" .
"Best Regards,\n" .
"_*{$site_data['brand']}.*_";

//admin alert message on whatsaapp
send_sms_credentials($site_data['username'],$whamessage);

// users message 
send_sms_credentials($_POST['phonenumber'],$whamessage);
send_email($complaintuserss['0']['email'], "Complaint For " . htmlspecialchars($_POST['complaint_type']), htmlspecialchars($emailmessage));
awal_alert_msg("Complaint Close Successfully!<br>Complaint ID : #{$complaint_id}",'success','');  
}else{
awal_alert_msg("Server Error!",'info');  
}

}else{
awal_alert_msg("Please Enter Remark!",'error');
}

}

?>

   <div class="col-md-12 mb-2">
    <div class="card text-dark">
      <div class="card-header bg-primary text-white py-2">
        <div class="d-flex align-items-center">
          <span class="mr-auto"><?=file_name()?></span>
        </div>
      </div>
      <div class="card-body p-0">
       <div class="table-responsive scroll">
        <table class="table w-100" id="dataTable">
          <thead>
            <tr class="bg-secondary">
              <th class="d-none">SL No. </th>
              <th>UserID</th>
              <th>Complaint ID</th>
              <th>Date Time</th>
              <th>Service</th>
              <th>Complaint</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>

<?php
$response = db_fetch_all("complaints", "status ='Open' ORDER BY complaint_id ASC");
$sl=1;
foreach ($response as $key => $value) {
$value['date_time'] = date("d-M-Y h:i:s A",strtotime($value['date_time']));

if(in_array($value['status'],['Close'])){
$status = '<span class="badge badge-success"><span class="oi oi-circle-check pulse mr-1"></span>'.$value['status'].'</span>';
}else if(in_array($value['status'],['Open'])){
$status = '<span class="badge badge-danger"><span class="oi oi-media-record pulse mr-1"></span>'.$value['status'].'</span>';
}

?>

            <tr>
              <td class="d-none"><?=$sl?></td>
              <td><?=$value['username']?></td>
              <td>#<?=$value['complaint_id']?></td>
              <td><?=$value['date_time']?></td>
              <td><?=$value['complaint_type'] . (!empty($value['utrnumber']) ? "<br><strong>UTR:</strong> {$value['utrnumber']}" : "")?></td>
              <td><textarea class="form-control form-control-sm" style="height:100px;" readonly><?=$value['message']?></textarea></td>
              <td>
                <form method="POST" action="">
                  <input type="hidden" name="complaint_id" value="<?=$value['complaint_id']?>">
                  <input type="hidden" name="phonenumber" value="<?=$value['username']?>">
                  <input type="hidden" name="complaint_type" value="<?=$value['complaint_type']?>">
                  <textarea class="form-control form-control-sm mb-2" name="remark" placeholder="Enter Remark" style="height:100px;"><?= htmlspecialchars($value['remark'], ENT_QUOTES, 'UTF-8')?></textarea>
                  <button type="submit" class="btn btn-primary btn-sm btn-block" name="close">Submit</button>
                </form>
              </td>
            </tr>
<?php
$sl++;}
?>            
            
          </tbody>
        </table>
       </div>

     </div>
    </div>
  </div>
<?php 
}
?>
<script>
const serviceList = [
  "ADD MONEY",
  "AADHAAR FINGERPRINT",
  "AADHAAR NUMBER VERIFY",
  "UID TO FULL DETAILS",
  "AYUSHMAN CARD",
  "e-SHRAM CARD",
  "ENROLLMENT STATUS CHECK",
  "CHALLAN DETAIL",
  "DL PDF SERVER 1",
  "DL PDF SERVER 2",
  "LL EXAM",
  "RATION PDF",
  "RATION TO UID FIND",
  "AADHAAR TO RATION PDF",
  "AADHAAR TO PAN FIND",
  "PAN DETAILS",
  "PAN AADHAR LINK STATUS",
  "PAN TO MASK AADHAR",
  "IFSC CODE",
  "MOBILE NUMBER VERIFY",
  "PINCODE VERIFY",
  "RC PDF SERVER 1",
  "RC PDF SERVER 2",
  "VOTER ADVANCE",
  "VOTER MOBILE LINK",
  "VOTER PDF",
  "OTHER PROBLEM",
  "I WANT REFUND MY AMOUNT"
];

// On page load, populate the select
const selectBox = document.getElementById('complaintType');

// Now add all services
serviceList.forEach(service => {
  const option = document.createElement('option');
  option.value = service;
  option.text = service;
  selectBox.appendChild(option);
});

// optional: when click on select box, you can still console log JSON
selectBox.addEventListener('click', function() {
    console.log(JSON.stringify(serviceList, null, 2));
});
</script>
</div>
<?php
require_once("../layouts/members/foot.php");
data_table('#dataTable');
?>