<?php 
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    ini_set ("display_errors", "0");
    error_reporting(E_ALL);
    require("../connect.php");
    include './funcConvertToSecond.php';
    date_default_timezone_set('Asia/Jakarta');

	$stmtCekVKP = mysqli_query($conn, "SELECT COUNT(*) AS kpcek 
	FROM app_entity_61 WHERE field_921 = '".$_POST['kuponpanen']."';");
    $rowCekVKP = mysqli_fetch_assoc($stmtCekVKP);

    // Checking existing to prevent double data
	if ($rowCekVKP['kpcek'] == '0') {
	    
        // Preparing datetime and img filename
        $timeinterval = NULL;
        $harvestProgress = 0;
        $verifdate = strtotime($_POST['inputdate']);
        $harvestdate = strtotime($_POST['harvestdate']);
        $timeharvest = timeToSeconds($_POST['inputtime']);
        $timeharvestinterval = new DateTime($_POST['inputtime']);
        $filename_db = time()."_"."VKP".$_POST['addedby'].$_POST['harvester'].$_POST['tphid'].date("YmdHis",time()).".png";
        
        // Check status RKH
        $stmtExistRKH = mysqli_query($conn, "SELECT COUNT(*) AS existrkh FROM app_entity_45 
        WHERE field_750 = (SELECT parent_item_id FROM app_entity_43 WHERE id = ".$_POST['tphid'].") 
        AND FROM_UNIXTIME(field_751,'%Y-%m-%d') = '".$_POST['harvestdate']."';");
        $rowExistRKH = mysqli_fetch_assoc($stmtExistRKH);
        
        // Check status angkut
        $stmtExistSPB = mysqli_query($conn, "SELECT COUNT(*) existangkut 
        FROM app_entity_63 WHERE instr(field_1139, '".$_POST['kuponpanen']."')
		AND FROM_UNIXTIME(field_933,'%Y-%m-%d') >= '".$_POST['harvestdate']."';");
        $rowExistSPB = mysqli_fetch_assoc($stmtExistSPB);
        
        // Check status WB
        $stmtExistWB = mysqli_query($conn, "SELECT COUNT(*) existwb FROM app_entity_71
        WHERE field_1205 = (SELECT field_949 FROM app_entity_63 WHERE 
        instr(field_1139, '".$_POST['kuponpanen']."') 
        AND FROM_UNIXTIME(field_933,'%Y-%m-%d') >= '".$_POST['harvestdate']."' LIMIT 1);");
        $rowExistWB = mysqli_fetch_assoc($stmtExistWB);
        
        // Setting up Status Panen
        if ($rowExistRKH['existrkh'] == 0 && $rowExistSPB['existangkut'] == 0 && $rowExistWB['existwb'] == 0) {
            $harvestProgress = 237;
        } else if ($rowExistRKH['existrkh'] >= 1 && $rowExistSPB['existangkut'] == 0 && $rowExistWB['existwb'] == 0) {
            $harvestProgress = 238;
        } else if ($rowExistRKH['existrkh'] == 0 && $rowExistSPB['existangkut'] >= 1 && $rowExistWB['existwb'] == 0) {
            $harvestProgress = 240;
        } else if ($rowExistRKH['existrkh'] >= 1 && $rowExistSPB['existangkut'] >= 1 && $rowExistWB['existwb'] == 0) {
            $harvestProgress = 239;
        } else if ($rowExistRKH['existrkh'] == 0 && $rowExistWB['existwb'] >= 1) {
            $harvestProgress = 241;
        } else if ($rowExistRKH['existrkh'] >= 1 && $rowExistWB['existwb'] >= 1) {
            $harvestProgress = 242;
        }
        
        // Checkin time interval
        if ($timeharvestinterval >= new DateTime('06:00') && $timeharvestinterval <= new DateTime('07:00')) {
        	$timeinterval = 840;
        } else if ($timeharvestinterval > new DateTime('07:00') && $timeharvestinterval <= new DateTime('08:00')) {
            $timeinterval = 841;
        } else if ($timeharvestinterval > new DateTime('08:00') && $timeharvestinterval <= new DateTime('09:00')) {
            $timeinterval = 842;
        } else if ($timeharvestinterval > new DateTime('09:00') && $timeharvestinterval <= new DateTime('10:00')) {
            $timeinterval = 843;
        } else if ($timeharvestinterval > new DateTime('10:00') && $timeharvestinterval <= new DateTime('11:00')) {
            $timeinterval = 844;
        } else if ($timeharvestinterval > new DateTime('11:00') && $timeharvestinterval <= new DateTime('12:00')) {
            $timeinterval = 845;
        } else if ($timeharvestinterval > new DateTime('12:00') && $timeharvestinterval <= new DateTime('13:00')) {
            $timeinterval = 846;
        } else if ($timeharvestinterval > new DateTime('13:00') && $timeharvestinterval <= new DateTime('14:00')) {
            $timeinterval = 847;
        } else if ($timeharvestinterval > new DateTime('14:00') && $timeharvestinterval <= new DateTime('15:00')) {
            $timeinterval = 848;
        } else if ($timeharvestinterval > new DateTime('15:00') && $timeharvestinterval <= new DateTime('16:00')) {
            $timeinterval = 849;
        } else if ($timeharvestinterval > new DateTime('16:00') && $timeharvestinterval <= new DateTime('17:00')) {
            $timeinterval = 850;
        } else if ($timeharvestinterval > new DateTime('17:00') && $timeharvestinterval <= new DateTime('18:00')) {
            $timeinterval = 851;
        } else if ($timeharvestinterval > new DateTime('18:00') && $timeharvestinterval <= new DateTime('19:00')) {
            $timeinterval = 852;
        }
        
        // Inserting VKP data
        $queryInsertVKP = "INSERT INTO app_entity_61 (parent_item_id, date_added, 
        created_by, field_895, field_883, field_884, field_875, field_1259, 
        field_1130, field_881, field_885, field_886, field_887, field_888, 
        field_889, field_891, field_892, field_2000, field_893, field_921, 
        field_918, field_919, field_922, field_1367, field_1947, field_3027, field_1682) 
        VALUES (?, UNIX_TIMESTAMP(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        
        $stmtInsertVKP = mysqli_prepare($conn, $queryInsertVKP);
        mysqli_stmt_bind_param($stmtInsertVKP, 'iiiissssiiiiisssssssssiiii', 
        $_POST['tphid'], $_POST['uploadby'], $_POST['addedby'], $_POST['tphid'], 
        $_POST['tphqr'], $harvestdate, $verifdate, $timeharvest, $_POST['harvester'], 
        $_POST['jjgmatang'], $_POST['jjgmentah'], $_POST['jjgbusuk'], 
        $_POST['jjgtaskrasi'], $_POST['tangkaipjg'], $_POST['jjghama'], 
        $_POST['brondolan'], $_POST['jjglangsir'], $_POST['buahsusun'], 
        $_POST['kuponpanen'], $_POST['latvkp'], $_POST['longvkp'], 
        $filename_db, $_POST['worktype'], $_POST['tphinputmethod'], $timeinterval, $harvestProgress);
        
        if (mysqli_stmt_execute($stmtInsertVKP)) {
            echo json_encode(array("UPLOADVKP"=>"SUCCESS"));
            
            $lastInsertID = mysqli_insert_id($conn); // Getting last ID
            
            $stmtImgVKP = mysqli_query($conn, "SELECT field_922 FROM app_entity_61 WHERE id = ".$lastInsertID.";");
            $rowImgVKP = mysqli_fetch_assoc($stmtImgVKP);
            
            // Inserting to values app_entity_61_values
            mysqli_query($conn, "INSERT INTO app_entity_61_values (items_id, fields_id, value) VALUES (".$lastInsertID.", 3027, ".$timeinterval.");");
        
            // Upload image
            if (!is_dir($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m"))) {
                mkdir($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m"),0777,true);
                if (!is_dir($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m")."/".date("d"))) {
                    mkdir($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m")."/".date("d"),0777,true);
                    // Upload image
                    $fp = fopen($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m")."/".date("d")."/".$rowImgVKP['field_922'], "w+");
                    fwrite($fp, base64_decode($_POST['vkpimg']));
                } else if (is_dir($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m")."/".date("d"))) { 
                    // Upload image
                    $fp = fopen($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m")."/".date("d")."/".$rowImgVKP['field_922'], "w+");
                    fwrite($fp, base64_decode($_POST['vkpimg']));
                }
            } else if (is_dir($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m"))) {
                if (!is_dir($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m")."/".date("d"))) {
                    mkdir($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m")."/".date("d"),0777,true);
                    // Upload image
                    $fp = fopen($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m")."/".date("d")."/".$rowImgVKP['field_922'], "w+");
                    fwrite($fp, base64_decode($_POST['vkpimg']));
                } else if (is_dir($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m")."/".date("d"))) { 
                    // Upload image
                    $fp = fopen($_SERVER['DOCUMENT_ROOT']."/v1/uploads/attachments/".date("Y")."/".date("m")."/".date("d")."/".$rowImgVKP['field_922'], "w+");
                    fwrite($fp, base64_decode($_POST['vkpimg']));
                }
            }
            mysqli_close($conn);
        }
	    
	} else {
	    echo json_encode(array("UPLOADVKP"=>"SUCCESS"));
	    mysqli_close($conn);
    }
?>