<?php
session_start(['gc_maxlifetime' => 14400, 'cookie_httponly' => true]); // Starting Session
include('member_session.php');
include('../coach/functions.php');
include("../coach/objects/class.member.php");
include '../coach/objects/food_journal.class.php';
include '../coach/objects/foodjournal_files.class.php';


$memberid = $_SESSION['memberid'];
if (!isset($_GET['food_journalId'])) {
    header('Location: foodjournal_list.php');
    exit();
}

$time = array(
    "12:00 AM" => "12:00 AM",
    "12:30 AM" => "12:30 AM",
    "01:00 AM" => "01:00 AM",
    "01:30 AM" => "01:30 AM",
    "02:00 AM" => "02:00 AM",
    "02:30 AM" => "02:30 AM",
    "03:00 AM" => "03:00 AM",
    "03:30 AM" => "03:30 AM",
    "04:00 AM" => "04:00 AM",
    "04:30 AM" => "04:30 AM",
    "05:00 AM" => "05:00 AM",
    "05:30 AM" => "05:30 AM",
    "06:00 AM" => "06:00 AM",
    "06:30 AM" => "06:30 AM",
    "07:00 AM" => "07:00 AM",
    "07:30 AM" => "07:30 AM",
    "08:00 AM" => "08:00 AM",
    "08:30 AM" => "08:30 AM",
    "09:00 AM" => "09:00 AM",
    "09:30 AM" => "09:30 AM",
    "10:00 AM" => "10:00 AM",
    "10:30 AM" => "10:30 AM",
    "11:00 AM" => "11:00 AM",
    "11:30 AM" => "11:30 AM",
    "12:00 PM" => "12:00 PM",
    "12:30 PM" => "12:30 PM",
    "01:00 PM" => "01:00 PM",
    "01:30 PM" => "01:30 PM",
    "02:00 PM" => "02:00 PM",
    "02:30 PM" => "02:30 PM",
    "03:00 PM" => "03:00 PM",
    "03:30 PM" => "03:30 PM",
    "04:00 PM" => "04:00 PM",
    "04:30 PM" => "04:30 PM",
    "05:00 PM" => "05:00 PM",
    "05:30 PM" => "05:30 PM",
    "06:00 PM" => "06:00 PM",
    "06:30 PM" => "06:30 PM",
    "07:00 PM" => "07:00 PM",
    "07:30 PM" => "07:30 PM",
    "08:00 PM" => "08:00 PM",
    "08:30 PM" => "08:30 PM",
    "09:00 PM" => "09:00 PM",
    "09:30 PM" => "09:30 PM",
    "10:00 PM" => "10:00 PM",
    "10:30 PM" => "10:30 PM",
    "11:00 PM" => "11:00 PM",
    "11:30 PM" => "11:30 PM"
);

include('member-header.php');
?>
<?php include('menu.php'); ?>
<?php
$category = array(
    "Breakfast" => "Breakfast",
    "Lunch" => "Lunch",
    "Dinner" => "Dinner",
    "Snack" => "Snack",
    "Extras" => "Extras"
);

$foodJournalFiles = new Foodjournal_files();
$message = '';
if (isset($_POST['id']) && $_POST['id']) {
    $existing = new Food_journal();
    $existing = $existing->Get((int)$_POST['id']);
    if (!$existing->food_journalId || (int)$existing->member_id !== (int)$memberid) {
        header('Location: foodjournal_list.php');
        exit();
    }
    $food_journal = new Food_journal();
    $food_journal->food_journalId = (int)$_POST['id'];
    $food_journal->title = $_POST['title'];
    $food_journal->date = date('Y-m-d H:i:s', strtotime($_POST['datetime'] . ' ' . $_POST['time']));
    $food_journal->category = $_POST['category'];
    $food_journal->notes = $_POST['notes'] ? $_POST['notes'] : '';
    $food_journal->member_id = $memberid;
    $food_journal->updated = date('Y-m-d H:i:s');
    $food_journal->Save();


    if (!file_exists('images/foods')) {
        mkdir('images/foods', 0777, true);
    }
    $target_dir = "images/foods/";
    foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
        if ($tmp_name) {
            $file_tmp = $_FILES['files']['tmp_name'][$key];
            $filename = time() . '_' . $_FILES["files"]["name"][$key];
            $target_file = $target_dir . basename($filename);
            move_uploaded_file($file_tmp, $target_file);
            $foodJournalFiles->foodjournal_id = $_POST['id'];
            $foodJournalFiles->file_name = $filename;
            $foodJournalFiles->SaveNew();
        }
    }
    echo "<script type='text/javascript'> document.location = 'foodjournal_list.php'; </script>";
}
$food_journal = new Food_journal();
$food_journal = $food_journal->Get((int)$_GET['food_journalId']);
if (!$food_journal->food_journalId || (int)$food_journal->member_id !== (int)$memberid) {
    header('Location: foodjournal_list.php');
    exit();
}

$foodJournalFiles = new Foodjournal_files();
$_fj_id = (int)$_GET['food_journalId'];
$params = array(array("foodjournal_id = $_fj_id"));
$images = $foodJournalFiles->GetList($params);
$count = count($images);
$limit = _foodImageLimit_;
$remainingCount = ($limit - $count);
?>
<?php if ($remainingCount > 1) { ?>
    <style>
        #files {width: 95%}
        #files1 {width: 95%}
    </style>
<?php } ?>
<style>
    .error { color: red; }
    .success { background-color: #ccffcc; }

    #daily_log_id { width: 75%; margin: 5px 0px 32px 0px; }

    .success { background-color: #4592e0; height: 25px; text-align: center; color: #ffffff;}
    #accountability_chart_form label.error { color: red; }
    #thd{
        text-align: center;
        font-weight: bold;
    }
    td{
        padding:10px 15px;
    }
    .text-center{
        text-align: center;
    }
    .text-upper{
        text-transform: uppercase;
    }
    .mandatory{
        color: red;
        font-size: 14px;
    }
    .btn {
        background-color: #c0c0c0;
    }


    @media (max-width: 768px) {
        #daily_log_id { width: 90%; margin: 5px 0px 52px 0px; }
        #files { width: 90% }
        #files1 { width: 90% }
    }    

    @media (max-width: 593px) {
        #time {
            margin-top: 10px;
        }
    } 

    @media (max-width: 384px) {
        .day {
            margin-top: 5px !important
        }
    } 

    @media (max-width: 275px) {
        .month {
            margin-top: 5px !important
        }
    }      



    .text_area {
        width: 99.5%;
        padding: 10px;
        margin-top: 8px;
        border: 1px solid #ccc;
        padding-left: 5px;
        font-size: 16px;
        font-family: raleway
    }

</style>
<?php if ($foodJournal == 0) { ?>
    <script>
        window.location.href = "member_homepage.php";
    </script>
<?php } ?>
<div id="daily_log_id">
    <b><br><div class="text-upper"><?= $message ?></div><p style="text-align: center;font-weight: bold;"><div class="success" >Food Journal Entry</div></p></b><div></br></div>
    <form class="form-horizontal" enctype='multipart/form-data' method="POST" name="foodjournal_entry" id="foodjournal_entry" action="<?= htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') ?>">
        <div class="form-group">

            <label class="textlabel" for="category">Meal Title<sub style="color:red; font-size: 30px;"> *</sub></label>
            <select name="category" id="category" class="text_area">
                <option value="">Select</option>
                <?php foreach ($category as $key => $cat) { ?>
                    <option <?php if ($food_journal->category == $key) { ?> selected="yes" <?php } ?> value="<?= $key ?>"><?= $cat ?></option>
                <?php } ?>
            </select>
            <label id="category-error" class="error" for="category"></label>
            <span>&nbsp;</span><br/>

            <label class="textlabel" for="date">Date<sub style="color:red; font-size: 30px;"> *</sub></label><br>
            <div class="container1" style="float: left">
                <input type="text" id="date" name="datetime"  data-field="datetime" value="<?= date('Y-m-d', strtotime($food_journal->date)) ?>" readonly class="text" style="display: none;">
            </div>
            <div style="float: left" class="container1">
                <select id="time" name="time" class="text" id="time">
                    <?php foreach ($time as $key => $time) { ?>
                        <option <?php if (date('h:i A', strtotime($food_journal->date)) == $key) { ?> selected="yes" <?php } ?>value="<?= $key ?>"><?= $time ?></option>
                    <?php } ?>
                </select>
            </div><br>
            <label id="date-error" class="error" for="date"></label>
            <span>&nbsp;</span><br/><br/>
            <div class="clearfix" style="clear: both"></div>

            <?php if ($remainingCount > 0) { ?>
                <label class="textlabel" for="file">Image</label>
                <div class="field_wrapper">
                    <input type="file" name="files[]" id="files" class="text_area" accept="image/*"/>
                    <?php if ($remainingCount > 1) { ?>
                        <a href="javascript:void(0);" class="add_button" title="Add field"><i class="fa fa-plus-circle" style="font-size: 25px"></i></a>
                    <?php } ?>
                </div>
                <label id="file-error" class="error" for="file"></label>
            <?php } ?>
            <i style="color: green"><b><?= $count ?> food journal photos uploaded</b></i>
            <span>&nbsp;</span><br/><br/>

            <label class="textlabel" for="notes">Notes: (Are you hungry? Are you stressed? Are you board?)</label><br/>
            <textarea  name="notes" id="notes" class="text_area"><?php echo $food_journal->notes ?></textarea>

            <div></br></div>
            <input type="hidden" id="id" name="id" value="<?= (int)$_GET['food_journalId'] ?>">
            <input type="hidden" name="memberid" value="<?php print $memberid ?>">

            <div class="button"><input type="submit" name="submit" value="Submit" class="submit"/></div> 
        </div>
    </form>
</div>
<script src="../coach/js/jquery.js"></script>
<script src="../coach/js/jquery.validate.js"></script>
<script>
        var validator = $("#foodjournal_entry").validate({
            rules: {
                date: {
                    required: true
                },
                category: {
                    required: true
                }
            },
            messages: {
                date: {
                    required: "Please select the date"
                },
                category: {
                    required: "Please enter the category"
                }
            },
            submitHandler: function (form) {
                form.submit();
            }
        });

        $(function () {
            $('#date').dropdownDatepicker({
                defaultDateFormat: 'yyyy-mm-dd',
                displayFormat: 'mdy',
                submitFormat: 'yyyy-mm-dd'
            });
        });

        var maxField = <?php echo $remainingCount ?>; //Input fields increment limitation
        var addButton = $('.add_button'); //Add button selector
        var wrapper = $('.field_wrapper'); //Input field wrapper
        var fieldHTML = '<div><input type="file" name="files[]" id="files1"  class="text_area" accept="image/*"/> <a href="javascript:void(0);" class="remove_button"><i class="fa fa-times-circle-o" aria-hidden="true" style="font-size: 25px"></i></a></div>'; //New input field html 
        var x = 1; //Initial field counter is 1
        //Once add button is clicked
        $(addButton).click(function () {
            //Check maximum number of input fields
            if (x < maxField) {
                x++; //Increment field counter
                $(wrapper).append(fieldHTML); //Add field html
            }
        });

        //Once remove button is clicked
        $(wrapper).on('click', '.remove_button', function (e) {
            e.preventDefault();
            $(this).parent('div').remove(); //Remove field html
            x--; //Decrement field counter
        });
</script>
<!-- jQuery First -->
<script src="../coach/js/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<!-- Or from a CDN -->
<script src="../coach/js/jquery-dropdown-datepicker.min.js"></script>
<style>
    .container1 select {
        padding: 10px;
        background: #ffffff;
        border: 1px solid #CCCCCC;
        border-radius: 3px;
        margin: 0 3px;
    }
</style>
<?php
include('member-footer.php');
?>