<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

include_once("../../../../../lib/phpmailer/Exception.php");
include_once("../../../../../lib/phpmailer/PHPMailer.php");
include_once("../../../../../lib/phpmailer/SMTP.php");
session_start();
include_once("../../../../../lib/konfig.php");
include_once("../../../../../lib/function.php");
$MySQLi = new MySQLi($strDBHostName, $strDBUsername, $strDBPassword, $strDBName);

$stsEdit = 0;
// INPUT DETAIL LPBJ ========================================================================
if (isset($_POST['submit'])) {
	$strEmail = $_SESSION['strEmail'];

	for ($i = 1; $i <= $_POST['max_iCounter']; $i++) {
		if (isset($_FILES['strNmFile' . $i]) && $_FILES['strNmFile' . $i]['name'] <> "" && $_FILES['strNmFile' . $i]['error'] == UPLOAD_ERR_OK) {
			$errors = [];
			$allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/bmp'];
			$file_type = $_FILES['strNmFile' . $i]['type'];
			$file_size = $_FILES['strNmFile' . $i]['size'];
			$file_tmp = $_FILES['strNmFile' . $i]['tmp_name'];
			$file_ext = strtolower(pathinfo($_FILES['strNmFile' . $i]['name'], PATHINFO_EXTENSION));
			//die($file_type);
			if (!in_array($file_type, $allowed_types))
				$errors[] = "Only JPG, JPEG, PNG, dan BMP format that allowed.";
			if (empty($errors)) {
				$strNmFile = MD5(uniqid() . date("Y-m-d H:i:s")) . "." . $file_ext;
				$destination = '../../../assets/images/lpbj_pic/' . $strNmFile;
				$thumb_destination = '../../../assets/images/lpbj_pic/thumb_' . $strNmFile;
				$strNmFile = "strNmFile='" . $strNmFile . "', ";

				$quality = 90;
				while (true) {
					compressImage($file_tmp, $destination, $quality);
					if (filesize($destination) <= 200000 || $quality <= 10)
						break;
					$quality -= 10;
				}
				createThumbnail($destination, $thumb_destination, 200);
			} else {
				foreach ($errors as $error)
					echo $error . "<br>";
				die("<a href='../../../index.php?menu=edit-lpbj&lpbj=" . $_SESSION['strKdLPBJ'] . "'>back</a>");
			}
		} else {
			$strNmFile = "";
		}

		//die($_POST['strDeskripsi'.$i]); 
		$strUnit = "";
		if ($_POST['strUnit' . $i] == "")
			$strUnit = "PCS";
		else $strUnit = $_POST['strUnit' . $i];

		if (strpos($_POST['strDeskripsi' . $i], '_') !== false) {
			list($ID, $strDeskripsi) = explode("_", $_POST['strDeskripsi' . $i]);
		} else {
			$strDeskripsi = $_POST['strDeskripsi' . $i];
		}
		$query = "SELECT * 
				FROM item 
				WHERE strDeskripsi='" . $strDeskripsi . "' AND 
					  (stsAktif BETWEEN 1 AND 2)
				";
		$result = $MySQLi->query($query);
		if ($result->num_rows == 0) {
			$strKdItem = MD5(date('Y-m-d H:i:s') . $_POST['strDeskripsi' . $i]);
			$query = "INSERT INTO item 
					SET strKdItem='" . $strKdItem . "', 
						strDeskripsi='" . $_POST['strDeskripsi' . $i] . "', 
						strUnit='" . $strUnit . "', 
						dtCreate=NOW(),
						usrCreate='" . $strEmail . "'
					";
			$MySQLi->query($query);

			$query = "SELECT * 
					FROM item 
					WHERE strKdItem='" . $strKdItem . "' AND 
						  stsAktif=2
					";
			$result = $MySQLi->query($query);
		}
		$row = $result->fetch_array();
		$item_ID = $row['ID'];
		switch ($_SESSION['usrLevel']) {
			case 1:
				$set = "strKeteranganDIR=CONCAT(strKeteranganDIR, ', <br> Purchasing : " . $_POST['strKeterangan' . $i] . "'), ";
				break;
			case 2:
				$set = "strKeteranganMGR=CONCAT(strKeteranganMGR, ', <br> Purchasing : " . $_POST['strKeterangan' . $i] . "'), ";
				break;
			case 3:
				$set = "strKeteranganSPV=CONCAT(strKeteranganSPV, ', <br> Purchasing : " . $_POST['strKeterangan' . $i] . "'), ";
				break;
			case 4:
				$set = "strKeteranganREQ=CONCAT(strKeteranganREQ, ', <br> Purchasing : " . $_POST['strKeterangan' . $i] . "'), ";
				break;
		}
		$query = "UPDATE tpc_d_lpbj 
				SET item_ID='" . $item_ID . "', 
					item_strUnit='" . $strUnit . "', 
					" . $strNmFile . "
					dept_ID='" . $_POST['dept_ID' . $i] . "', 
					iJumlah='" . $_POST['iJumlah' . $i] . "', 
					iJumlahStok='" . $_POST['iJumlahStok' . $i] . "', 
					" . $set . " 
					dtDibutuhkan='" . $_POST['dtDibutuhkan' . $i] . "', 
					dtUpdate=NOW(), 
					usrUpdate='" . $_SESSION['strEmail'] . "' 
				WHERE h_lpbj_ID = '" . $_SESSION['h_lpbj_ID'] . "' AND 
					  ID = '" . $_POST['d_lpbj_ID' . $i] . "'
				  ";
		//		die($query);
		$MySQLi->query($query);
		if ($MySQLi->affected_rows == 1) {
			$stsEdit = 1;
			$strBuffer = str_replace('"', '`', str_replace("'", "`", $query));
			$query = "INSERT INTO tpc_log 
					SET strPCHostname='" . gethostbyaddr(getIPv4()) . "', 
						strIPv4='" . getIPv4() . "', 
						strPort='" . $_SERVER['REMOTE_PORT'] . "', 
						strTable='tpc_d_lpbj', 
						strQuery='" . $strBuffer . "', 
						strKeterangan='" . $strEmail . " membuat perubahan pesanan nomor : " . $_POST['d_lpbj_ID' . $i] . "', 
						dtCreate=NOW(), 
						usrCreate='" . $strEmail . "' 
					";
			$MySQLi->query($query);
		}
	}
	// if($stsEdit==1)
	// {
	$query = "SELECT 	D_LPBJ.ID, 
						D_LPBJ.iJumlah, 
						D_LPBJ.iJumlahStok, 
						D_LPBJ.strKeteranganREQ,
						D_LPBJ.strKeteranganDIR,
						D_LPBJ.strKeteranganMGR,
						D_LPBJ.strKeteranganSPV,
						D_LPBJ.dtDibutuhkan, 
						D_LPBJ.stsACCDIR, 
						ITEM.strKdItem, 
						ITEM.strDeskripsi, 
						ITEM.strUnit, 
						DEPT.strNmDept, 
						H_LPBJ.ID AS HEAD_ID, 
						H_LPBJ.iLevelREQ, 
						H_LPBJ.employee_Email AS strMailREQ, 
						H_LPBJ.strFullNameDIR, 
						H_LPBJ.strFullNameMGR, 
						H_LPBJ.strFullNameSPV, 
						H_LPBJ.strFullNameREQ, 
						H_LPBJ.strMailDIR, 
						H_LPBJ.strMailMGR, 
						H_LPBJ.strMailSPV, 
						H_LPBJ.dtCreate, 
						H_LPBJ.strNmDivisiRequestor AS strNmDivisiREQ, 
						STAFF.strKdLoc 
				FROM tpc_d_lpbj AS D_LPBJ 
				LEFT JOIN tpc_h_lpbj AS H_LPBJ 
					ON D_LPBJ.h_lpbj_ID=H_LPBJ.ID 
				LEFT JOIN item AS ITEM 
					ON D_LPBJ.item_ID = ITEM.ID 
				LEFT JOIN tpc_dept AS DEPT 
					ON DEPT.ID = D_LPBJ.dept_ID 
				LEFT JOIN employee AS STAFF 
					ON STAFF.Email=H_LPBJ.employee_Email 
				WHERE H_LPBJ.strKdLPBJ = '" . $_SESSION['strKdLPBJ'] . "' AND 
					H_LPBJ.stsAktif = 1 AND 
					D_LPBJ.stsAktif = 1 
				";
	$result = $MySQLi->query($query);
	$i = 1;
	$strIsiTable = "";

	while ($row = $result->fetch_array()) {
		if ($i == 1) {
			$iLevelREQ = $row['iLevelREQ'];
			$dtCreate = $row['dtCreate'];
			$strNmDivisi = $row['strNmDivisiREQ'];
			$strFullNameREQ = $row['strFullNameREQ'];
			$strFullNameSPV = $row['strFullNameSPV'];
			$strFullNameMGR = $row['strFullNameMGR'];
			$strFullNameDIR = $row['strFullNameDIR'];
			$strMailREQ = $row['strMailREQ'];
			$strMailSPV = $row['strMailSPV'];
			$strMailMGR = $row['strMailMGR'];
			$strMailDIR = $row['strMailDIR'];
			$strKdLoc = $row['strKdLoc'];
		}
		$i++;

		if ($row['stsACCDIR'] == 0)
			$stsACCFinal = "TOLAK";
		else $stsACCFinal = "OK";
		$strIsiTable = $strIsiTable . "<tr> 
							<td align='center'>" . $row['strKdItem'] . "</td> 
							<td align='center'>" . $row['strDeskripsi'] . "</td> 
							<td align='center'>" . $row['strNmDept'] . "</td> 
							<td align='center'>" . $row['iJumlah'] . "</td> 
							<td align='center'>" . $row['strUnit'] . "</td> 
							<td align='center'>" . $row['iJumlahStok'] . "</td> 
							<td>" . $row['strKeteranganREQ'] . "<br>" . $row['strKeteranganSPV'] . "<br>" . $row['strKeteranganMGR'] . "<br>" . $row['strKeteranganDIR'] . "</td> 
							<td align='center'>" . date("d/m/Y", strtotime($row['dtDibutuhkan'])) . "</td> 
							<td align='center'>" . $stsACCFinal . "</td> 
						</tr>";
	}
	$strTable_v1 = "  <table cellspacing='0' cellpadding='0' border='0'>
                        <tr>
                            <td>No LPBJ</td>
                            <td>&nbsp;:&nbsp;</td>
                            <td>" . $_SESSION['strKdLPBJ'] . "</td>
                        </tr>
                        <tr>
                            <td>Tanggal</td>
                            <td>&nbsp;:&nbsp;</td>
                            <td>" . $dtCreate . "</td>
                        </tr>
                        <tr>
                            <td>Bagian/Divisi</td>
                            <td>&nbsp;:&nbsp;</td>
                            <td>" . $strNmDivisi . "</td>
                        </tr>
                        <tr>
                            <td>Peminta</td>
                            <td>&nbsp;:&nbsp;</td>
                            <td>" . $strFullNameREQ . "</td>
                        </tr>
                        <tr>
                            <td>Supervisor</td>
                            <td>&nbsp;:&nbsp;</td>
                            <td>" . $strFullNameSPV . "</td>
                        </tr>
                        <tr>
                            <td>Manager</td>
                            <td>&nbsp;:&nbsp;</td>
                            <td>" . $strFullNameMGR . "</td>
                        </tr>
                        <tr>
                            <td>Direksi</td>
                            <td>&nbsp;:&nbsp;</td>
                            <td>" . $strFullNameDIR . "</td>
                        </tr>
                    </table><br>
                ";

	$strTable = "<table border='1' cellspacing='0' cellpadding='0'>
					<tr>
						<td>No</td>
						<td>Deskripsi</td>
						<td>Departement</td>
						<td>Jumlah</td>
						<td>Satuan</td>
						<td>Jumlah Stok</td>
						<td>Keterangan</td>
						<td>Prioritas</td>
						<td>Status</td>
					</tr>
					" . $strIsiTable . "
				</table>
				";
	list($strMailUserName, $strMailDomain) = explode("@", $strMailREQ);
	$strMailPurchasing = trim("purchasing@" . $strMailDomain);
	$strMailTo = [$strMailPurchasing . "#Purchasing"];
	$strMailCC = [$strMailDIR . "#" . $strFullNameDIR];
	$strMailBCC = [];

	$query = "SELECT 	FullName, 
						Email 
				FROM employee 
				WHERE strKdLoc='" . $strKdLoc . "' AND 
					  strJobPosition like '%Accurate%' 
				";
	$result = $MySQLi->query($query);

	while ($row = $result->fetch_array()) {
		$strMailTo[] = $row['Email'] . "#" . $row['FullName'];
		$strFullNameAccurate = $row['FullName'];
	}
	$strBody = "Dear PURCHASING dan " . $strFullNameAccurate . ",<br><br>

		Berikut saya ada persetujuan atas pemesanan barang yang ingin dibeli oleh :" . $strFullNameREQ . ", segera lakukan proses pembelian<br>
		" . $strTable_v1 . "
		" . $strTable . "<br><br>
		Demikian yang dapat saya sampaikan, terima kasih.<br><br>
		Best Regards,<br>
		" . $strFullNameREQ . "
		";

	switch ($iLevelREQ) {
		case 3:
			$strMailCC[] = $strMailMGR . "#" . $strFullNameMGR;
			break;
		case 4:
			$strMailCC[] = $strMailMGR . "#" . $strFullNameMGR;
			$strMailCC[] = $strMailSPV . "#" . $strFullNameSPV;
			break;
	}
	$strMailCC[] = $strMailREQ . "#" . $strFullNameREQ;
	$strSubject = "[LPBJ] Approval Request for LPBJ No :" . $_POST['strKdLPBJ'];
	// die($strHyperlink); 
	if (kirim_email($strMailTo, $strMailCC, $strMailBCC, $strSubject, $strBody) && filter_var($strMailREQ, FILTER_VALIDATE_EMAIL))
		alertpopup("Perubahan berhasil disimpan dan email telah di teruskan ke pihak terkait", "", "../../../index.php?menu=edit-lpbj&lpbj=" . $_SESSION['strKdLPBJ']);
	// }
	// die("hello");
	$strKdLPBJ = $_POST['strKdLPBJ'];
	echo '<script type="text/javascript">';
	echo 'location.href = \'http://' . $strNmDomain . '/home/index.php?menu=edit-lpbj&lpbj=' . $_SESSION['strKdLPBJ'] . '\';';
	echo '</script>';
}

// DONE LPBJ by purchasing ========================================================================
if (isset($_GET['opt']) && isset($_GET['id']) && $_GET['opt'] == "done") {
	$query = "UPDATE tpc_h_lpbj 
			SET stsDone=1, 
				dtUpdate=NOW(), 
				usrUpdate='" . $_SESSION['strEmail'] . "' 
			WHERE ID='" . $_GET['id'] . "' 
			";
	$MySQLi->query($query);
	if ($MySQLi->affected_rows == 1) {
		$strBuffer = str_replace('"', '`', str_replace("'", "`", $query));
		$query = "INSERT INTO tpc_log 
				SET strPCHostname='" . gethostbyaddr(getIPv4()) . "', 
					strIPv4='" . getIPv4() . "', 
					strPort='" . $_SERVER['REMOTE_PORT'] . "', 
					strTable='tpc_h_lpbj', 
					strQuery='" . $strBuffer . "', 
					strKeterangan='" . $_SESSION['strEmail'] . " klik done untuk nomor ID LPBJ : " . $_GET['id'] . "', 
					dtCreate=NOW(), 
					usrCreate='" . $_SESSION['strEmail'] . "' 
				";
		$MySQLi->query($query);
		echo '<script type="text/javascript">';
		echo 'alert(\'LPBJ Done\');';
		echo 'location.href = \'http://' . $strNmDomain . '/home/index.php?menu=laporan-lpbj\';';
		echo '</script>';
	}
}
