<?php
include('usersession.php');

$uid = $_SESSION['ecimsuser'];
$sqlu = "SELECT * FROM users WHERE uid='$uid'";
$queryu = $conn->query($sqlu);
$ecimsuser = $queryu->fetch_assoc();

$msg = '';
$err = '';

if(isset($_POST['submit'])) {

    $date = date("d/m/Y");
    $d = date("dmy");
    $time = date("g:i a");
    $curtime = date("H:i");

    $uid = $_POST['uid'];
    $b_list = $_POST['b_list'];
    $details = mysqli_real_escape_string($conn, $_POST['details']);
    $c_list = $_POST['c_list'];

    $complaint = $conn->query("SELECT * FROM complaint_list WHERE cid='$c_list'")->fetch_assoc();

    $priority = $complaint['priority'];
    $subdivision = $complaint['subdivision'];

    $todaycompcount = $conn->query("SELECT ucid FROM users_complaint WHERE date='$date'")->num_rows;
    $thiscount = $todaycompcount + 1;
    $docketNumber = $d.sprintf("%02d", $thiscount);

    $c_status = '0';

    if($curtime >= '21:30' && $priority != '1') {
        $c_status = '4';
    }

    $newQ = "INSERT INTO users_complaint
    (date, b_list, uid, details, c_list, time, priority, subdivision, docketNumber, c_status)
    VALUES
    ('$date', '$b_list', '$uid', '$details', '$c_list', '$time', '$priority', '$subdivision', '$docketNumber', '$c_status')";

    $result = $conn->query($newQ);

    if($result) {
        $ucid = $conn->insert_id;

        if(!empty($_FILES['files']['name'][0])) {
            $targetDir = "Images/";
            $allowTypes = array('jpg','png','jpeg','gif');

            foreach($_FILES['files']['name'] as $key=>$val) {
                $fileName = basename($_FILES['files']['name'][$key]);
                $targetFilePath = $targetDir . $fileName;
                $fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));

                if(in_array($fileType, $allowTypes)) {
                    if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)) {
                        $conn->query("INSERT INTO users_complaint_images (img, uid, ucid) VALUES ('$fileName', '$uid', '$ucid')");
                    }
                }
            }
        }

        $msg = "Complaint added successfully. <br>Your complaint number is <b>$docketNumber</b>";
    } else {
        $err = "Error: ".$conn->error;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
	<title>ECIMS USER | NEW COMPLAINT</title>
    <?php include('includes/head.php'); ?>
    <style>
        .alert-success {
            color: #000; 
        }
    </style>
  </head>
  <body>
    <div class="container-scroller">
      <div class="horizontal-menu">
        <?php $activePage = basename($_SERVER['PHP_SELF'], ".php"); ?>
<nav class="navbar top-navbar col-lg-12 col-12 p-0">
  <div class="container-fluid">
	<div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-start">
	  <a class="navbar-brand brand-logo" href="index.php"><img style="width: 115px;height:auto;" src="assets/images/logo.png" alt="logo" /></a>
	  <a class="navbar-brand brand-logo-mini" href="index.php"><img style="width: 115px;height:auto;" src="assets/images/logo.png" alt="logo" /></a>
	</div>
	<div class="text-center navbar-menu-wrapper d-none d-lg-block d-flex align-items-center justify-content-center">
	  <span style="text-transform:uppercase;font-size: 30px;font-weight: bold;color: #000;">military engineer services <br> HISAR/ALWAR</span>
	</div>
	<div class="navbar-brand-wrapper d-flex align-items-center justify-content-end">
	  <a class="navbar-brand brand-logo d-none d-lg-block" href="index.php"><img style="width: 115px;height:auto;" src="assets/images/logo-right.png" alt="logo" /></a>
	  <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="horizontal-menu-toggle">
		<i class="fa fa-bars text-white"></i>
	  </button>
	</div>
  </div>
</nav>
<p class="text-center p-0 m-1 fw-bolder"> Login Date : <?php echo date('d/m/Y'); ?> </p>
<nav class="bottom-navbar">
  <div class="container-fluid">
	<?php include('includes/nav.php');  ?>
  </div>
</nav>
      </div>

<div class="container-fluid page-body-wrapper">
<div class="main-panel">
<div class="content-wrapper">

<h3 class="page-title mb-4">Register New Complaint</h3>
<a href="user-dashboard.php" class="btn btn-secondary btn-sm mb-3">Back</a>

<?php if($msg){ ?>
<div class="alert alert-success"><?= $msg ?></div>
<?php } ?>

<?php if($err){ ?>
<div class="alert alert-danger"><?= $err ?></div>
<?php } ?>

<div class="card">
<div class="card-body">

<form method="POST" enctype="multipart/form-data">

<input type="hidden" name="uid" value="<?= $ecimsuser['uid']; ?>">

<div class="form-group">
<label>Select Complaint</label>
<select class="form-control" name="c_list" required>
<option value="">Type / Select Complaint</option>
<?php
$comp = $conn->query("SELECT * FROM complaint_list ORDER BY details ASC");
while($fetchcomp = $comp->fetch_assoc()) {
?>
<option value="<?= $fetchcomp['cid']; ?>"><?= htmlspecialchars($fetchcomp['details']); ?></option>
<?php } ?>
</select>
</div>

<div class="form-group">
<label>Building / Address</label>
<select class="form-control" name="b_list" required>
<?php
$buil = $conn->query("SELECT * FROM building_list WHERE isDeleted='0'");
while($fetchbuild = $buil->fetch_assoc()) {
    $selected = '';
    if(isset($ecimsuser['b_list']) && $ecimsuser['b_list'] == $fetchbuild['bid']) {
        $selected = 'selected';
    }
?>
<option value="<?= $fetchbuild['bid']; ?>" <?= $selected; ?>>
<?= htmlspecialchars($fetchbuild['bNo'].', '.$fetchbuild['bName']); ?>
</option>
<?php } ?>
</select>
</div>

<div class="form-group">
<label>Brief Description</label>
<textarea class="form-control" name="details" required rows="4" placeholder="Write about your complaint."></textarea>
</div>

<div class="form-group">
<label>Attach Images Optional</label>
<input type="file" name="files[]" class="form-control" multiple>
</div>

<button type="submit" name="submit" class="btn btn-primary">Submit</button>

</form>

</div>
</div>

</div>
<?php include('includes/footer.php'); ?>
</div>
</div>
</div>
<?php include('includes/foot.php'); ?>
</body>
</html>