<?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';

$page_action = isset($_POST['action']) ? $_POST['action'] : "";

$memberid = $_SESSION['memberid'];
?>
<?php
include('member-header.php');

$category = array(
    "Breakfast" => "Breakfast",
    "Lunch" => "Lunch",
    "Dinner" => "Dinner",
    "Snack" => "Snack",
    "Extras" => "Extras"
);
$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"
);
?>
<style>

    /* === EXISTING FUNCTIONAL STYLES ONLY — DO NOT REMOVE === */
    .error { color: red; }
    .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; }
    #files { width: 95%; }
    #files1 { width: 95%; }

    @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;
    }
    .upload-text {
padding: 0;
}
.app-layout {
width: 100%;
}
.page-header-title, .page-header-subtitle {
padding: 0;
}
@media (max-width:767px) {
.datetime-row .date-picker-wrapper:first-child {
max-width: 292px;
width: 100%;
min-width: auto;
}
}

    /* === NEW DESIGN CLASSES — ASSUMED IN MASTER style.css === */
    /* .form-card, .datetime-row, .date-picker-wrapper, .date-picker-main,
       .date-picker-chevron, .date-picker-input, .form-group-ds, .form-label-ds,
       .notes-hint, .select-ds, .upload-area, .upload-default, .upload-icon,
       .upload-text, .upload-preview-wrap, .upload-preview, .upload-remove,
       .textarea-ds, .btn-save, .btn-ds-primary, .page-header, .page-header-title,
       .page-header-subtitle, .page-header-meta, .mobile-top-bar, .app-layout,
       .main-content, .body-content, .sidebar-placeholder, .mobile-nav-placeholder */
</style>

<?php
$foodJournalFiles = new Foodjournal_files();
$message = '';
if (isset($_POST['action']) && $_POST['action'] == 'add_foodjournal') {
    $food_journal = new Food_journal();
    $_safe_date = date('Y-m-d', strtotime($_POST['datetime'] ?? 'now'));
    $stmt = mysqli_prepare($connection,
        "SELECT COUNT(*) as count FROM food_journal WHERE member_id = ? AND DATE(date) = DATE(?)");
    mysqli_stmt_bind_param($stmt, 'is', $memberid, $_safe_date);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $row = mysqli_fetch_assoc($result);
    mysqli_stmt_close($stmt);
    if ($row['count'] < _foodEntryLimit_) {
        $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->created = date('Y-m-d H:i:s');
        $food_journal->updated = date('Y-m-d H:i:s');
        $id = $food_journal->Save();
        if ($id) {
            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 = $id;
                    $foodJournalFiles->file_name = $filename;
                    $foodJournalFiles->SaveNew();
                }
            }
        }

        echo "<script type='text/javascript'> document.location = 'foodjournal_list.php'; </script>";
    } else {
        $message = "<p style='text-align:center;color:red;font-weight:Bold;'>You can not add more than " . _foodEntryLimit_ . " item.</p>";
    }
}
?>

    <!-- Mobile Top Bar (logo centered) -->
    <div class="mobile-top-bar">
        <img src="./assets/images/logo.png" alt="Brand Logo">
    </div>

    <div class="app-layout">
        <!-- Desktop Sidebar -->

<?php include('menu.php'); ?>

<?php if ($foodJournal == 0) { ?>
    <script>
        window.location.href = "member_homepage.php";
    </script>
<?php } ?>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Page Header -->
            <header class="page-header">
                <div class="page-header-meta">
                    <div>
                        <h1 class="page-header-title">Food Journal Entry</h1>
                        <p class="page-header-subtitle">Log Your Meals With A Photo</p>
                    </div>
                </div>
            </header>

            <div class="body-content">

                <div id="daily_log_id">
                    <b><div class="text-upper"><?= $message ?></div></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-card">

                            <!-- Date & Time Row -->
                            <div class="datetime-row">
                                <!-- Date Picker -->
                                <div class="date-picker-wrapper" id="datePickerWrapper">
                                    <div class="date-picker-main">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M8 2V6" stroke="black" stroke-linecap="round" stroke-linejoin="round" />
                                            <path d="M16 2V6" stroke="black" stroke-linecap="round" stroke-linejoin="round" />
                                            <path d="M19 4H5C3.89543 4 3 4.89543 3 6V20C3 21.1046 3.89543 22 5 22H19C20.1046 22 21 21.1046 21 20V6C21 4.89543 20.1046 4 19 4Z" stroke="black" stroke-linecap="round" stroke-linejoin="round" />
                                            <path d="M3 10H21" stroke="black" stroke-linecap="round" stroke-linejoin="round" />
                                            <path d="M9 16L11 18L15 14" stroke="black" stroke-linecap="round" stroke-linejoin="round" />
                                        </svg>
                                        <span id="dateDisplay"><?= date('F d, Y') ?></span>
                                    </div>
                                    <div class="date-picker-chevron">
                                        <i class="bi bi-chevron-down"></i>
                                    </div>
                                    <!-- Original hidden date input for dropdownDatepicker plugin and form submission -->
                                    <input type="text" id="date" name="datetime" data-field="datetime" value="<?= date('Y-m-d') ?>" readonly class="text" style="display: none;">
                                </div>

                                <!-- Time Picker -->
                                <div class="date-picker-wrapper" id="timePickerWrapper">
                                    <div class="date-picker-main">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="black" stroke-linecap="round" stroke-linejoin="round" />
                                            <path d="M12 6V12L16 14" stroke="black" stroke-linecap="round" stroke-linejoin="round" />
                                        </svg>
                                        <?php
                                        $minutes = (date('i') < 30) ? "00" : "30";
                                        $current_time_display = date('h:' . $minutes . ' A');
                                        ?>
                                        <span id="timeDisplay"><?= $current_time_display ?></span>
                                    </div>
                                    <div class="date-picker-chevron">
                                        <i class="bi bi-chevron-down"></i>
                                    </div>
                                    <!-- Original hidden select for form submission -->
                                    <select id="time" name="time" style="display: none;">
                                        <?php
                                        foreach ($time as $key => $time_val) {
                                            $selected = (date('h:' . $minutes . ' A') == $key) ? 'selected="selected"' : '';
                                            ?>
                                            <option <?= $selected ?> value="<?= $key ?>"><?= $time_val ?></option>
                                        <?php } ?>
                                    </select>
                                </div>
                            </div>

                            <!-- Meal Title -->
                            <div class="form-group-ds">
                                <label class="form-label-ds" for="category">Meal Title<sub style="color:red; font-size: 30px;"> *</sub></label>
                                <select name="category" id="category" class="select-ds">
                                    <option value="">Select</option>
                                    <?php foreach ($category as $key => $cat) { ?>
                                    <option <?php if (isset($_POST['category']) && $_POST['category'] == $key) { ?> selected="yes" <?php } ?> value="<?= $key ?>"><?= $cat ?></option>
                                    <?php } ?>
                                </select>
                                <label id="category-error" class="error" for="category"></label>
                            </div>

                            <!-- Photo Upload -->
                            <div class="form-group-ds">
                                <label class="form-label-ds">Upload Food Journal Entry</label>
                                <div class="upload-area" id="uploadArea">
                                    <input type="file" name="files[]" id="files" accept="image/*" style="display: none;">

                                    <!-- Default state -->
                                    <div class="upload-default" id="uploadDefault">
                                        <div class="upload-icon">
                                            <svg width="70" height="70" viewBox="0 0 70 70" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M55.1023 8.70032H14.5007C11.2973 8.70032 8.70044 11.2972 8.70044 14.5005V55.1022C8.70044 58.3055 11.2973 60.9024 14.5007 60.9024H55.1023C58.3057 60.9024 60.9025 58.3055 60.9025 55.1022V14.5005C60.9025 11.2972 58.3057 8.70032 55.1023 8.70032Z" stroke="black" stroke-width="1.45425" stroke-linecap="round" stroke-linejoin="round" />
                                                <path d="M26.101 31.9012C29.3044 31.9012 31.9012 29.3044 31.9012 26.101C31.9012 22.8976 29.3044 20.3008 26.101 20.3008C22.8976 20.3008 20.3008 22.8976 20.3008 26.101C20.3008 29.3044 22.8976 31.9012 26.101 31.9012Z" stroke="black" stroke-width="1.45425" stroke-linecap="round" stroke-linejoin="round" />
                                                <path d="M60.9024 43.5017L51.9526 34.552C50.8649 33.4646 49.3899 32.8538 47.8518 32.8538C46.3138 32.8538 44.8388 33.4646 43.7511 34.552L17.4006 60.9024" stroke="black" stroke-width="1.45425" stroke-linecap="round" stroke-linejoin="round" />
                                            </svg>
                                        </div>
                                        <p class="upload-text">Drag & drop photo or</p>
                                        <p class="upload-text">click to upload</p>
                                    </div>

                                    <!-- Preview state -->
                                    <div class="upload-preview-wrap" id="uploadPreviewWrap" style="display: none;">
                                        <img class="upload-preview" id="uploadPreview" alt="Food photo preview">
                                        <button type="button" class="upload-remove" id="uploadRemove" aria-label="Remove photo">
                                            <i class="bi bi-x-lg"></i>
                                        </button>
                                    </div>
                                </div>
                                <div class="field_wrapper" style="display: none;">
                                    <a href="javascript:void(0);" class="add_button" title="Add field"><i class="fa fa-plus-circle" style="font-size: 25px"></i></a>
                                </div>
                                <label id="file-error" class="error" for="file"></label>
                            </div>

                            <!-- Notes -->
                            <div class="form-group-ds">
                                <label class="form-label-ds" for="notes">
                                    Notes <span class="notes-hint">(Are you hungry? Are you stressed? Are you bored?)</span>
                                </label>
                                <textarea name="notes" id="notes" class="textarea-ds" placeholder="Add your notes here..."><?php echo isset($_POST['notes']) ? htmlspecialchars($_POST['notes'], ENT_QUOTES, 'UTF-8') : '' ?></textarea>
                            </div>

                            <!-- Hidden Fields -->
                            <input type="hidden" name="action" value="add_foodjournal">
                            <input type="hidden" name="memberid" value="<?php print $memberid ?>">

                            <!-- Save Button -->
                            <button type="submit" name="submit" class="btn-save btn-ds-primary">Save Entry</button>

                        </div>

                    </form>
                </div>

            </div>
        </main>
    </div>

    <!-- Mobile Bottom Navigation -->
    <div id="mobile-nav-placeholder"></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="./js/layout.js"></script>

<script src="../coach/js/jquery.js"></script>
<script src="../coach/js/jquery.validate.js"></script>

<script>
    var validator = $("#foodjournal_entry").validate({
        rules: {
            category: {
                required: true
            },
            datetime: {
                required: true
            }
        },
        messages: {
            category: {
                required: "Please select Meal Title"
            },
            datetime: {
                required: "Please select the date"
            }
        },
        submitHandler: function (form) {
            form.submit();
        }
    });

    // =========================================================
    // DATE PICKER — INTEGRATED WITH DROPDOWNDATEPICKER PLUGIN
    // =========================================================
    const dateInput = document.getElementById('date');
    const dateDisplay = document.getElementById('dateDisplay');
    const datePickerWrapper = document.getElementById('datePickerWrapper');

    function formatDate(dateString) {
        const date = new Date(dateString + 'T00:00:00');
        return date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: '2-digit' });
    }

    datePickerWrapper.addEventListener('click', function () {
        datePickerWrapper.classList.add('picker-open');
        try { dateInput.click(); } catch (e) { }
    });

    dateInput.addEventListener('change', function () {
        if (this.value) {
            dateDisplay.textContent = formatDate(this.value);
        }
        datePickerWrapper.classList.remove('picker-open');
    });

    $(document).on('dateChanged', '#date', function() {
        dateDisplay.textContent = formatDate(dateInput.value);
        datePickerWrapper.classList.remove('picker-open');
    });

    dateDisplay.textContent = formatDate(dateInput.value);

    // =========================================================
    // TIME PICKER — INTEGRATED WITH EXISTING SELECT
    // =========================================================
    const timeSelect = document.getElementById('time');
    const timeDisplay = document.getElementById('timeDisplay');
    const timePickerWrapper = document.getElementById('timePickerWrapper');

    timePickerWrapper.addEventListener('click', function () {
        timePickerWrapper.classList.add('picker-open');
        var tempSelect = document.createElement('select');
        tempSelect.innerHTML = timeSelect.innerHTML;
        tempSelect.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;opacity:0;cursor:pointer;';
        timePickerWrapper.appendChild(tempSelect);
        tempSelect.focus();
        tempSelect.addEventListener('change', function() {
            timeSelect.value = this.value;
            timeDisplay.textContent = this.value;
            timePickerWrapper.classList.remove('picker-open');
            this.remove();
        });
        tempSelect.addEventListener('blur', function() {
            timePickerWrapper.classList.remove('picker-open');
            this.remove();
        });
        try { tempSelect.showPicker(); } catch (e) { tempSelect.click(); }
    });

    timeDisplay.textContent = timeSelect.value;

    // =========================================================
    // PHOTO UPLOAD LOGIC (Drag & Drop + Click + Remove)
    // =========================================================
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('files');
    const uploadDefault = document.getElementById('uploadDefault');
    const uploadPreviewWrap = document.getElementById('uploadPreviewWrap');
    const uploadPreview = document.getElementById('uploadPreview');
    const uploadRemove = document.getElementById('uploadRemove');

    uploadArea.addEventListener('click', function (e) {
        if (e.target !== fileInput && !e.target.closest('.upload-remove')) {
            fileInput.click();
        }
    });

    fileInput.addEventListener('change', function () {
        handleFile(this.files[0]);
    });

    uploadArea.addEventListener('dragover', function (e) {
        e.preventDefault();
        uploadArea.classList.add('drag-over');
    });

    uploadArea.addEventListener('dragleave', function () {
        uploadArea.classList.remove('drag-over');
    });

    uploadArea.addEventListener('drop', function (e) {
        e.preventDefault();
        uploadArea.classList.remove('drag-over');
        handleFile(e.dataTransfer.files[0]);
    });

    uploadRemove.addEventListener('click', function (e) {
        e.stopPropagation();
        clearUpload();
    });

    function handleFile(file) {
        if (file && file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function (e) {
                uploadPreview.src = e.target.result;
                uploadDefault.style.display = 'none';
                uploadPreviewWrap.style.display = 'block';
                uploadArea.classList.add('has-file');
            };
            reader.readAsDataURL(file);
        }
    }

    function clearUpload() {
        fileInput.value = '';
        uploadPreview.src = '';
        uploadDefault.style.display = 'block';
        uploadPreviewWrap.style.display = 'none';
        uploadArea.classList.remove('has-file');
    }

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

    // =========================================================
    // EXISTING DYNAMIC FILE FIELD ADD/REMOVE
    // =========================================================
    var maxField = <?= _foodImageLimit_ ?>;
    var addButton = $('.add_button');
    var wrapper = $('.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>';
    var x = 1;

    $(addButton).click(function () {
        if (x < maxField) {
            x++;
            $(wrapper).append(fieldHTML);
        }
    });

    $(wrapper).on('click', '.remove_button', function (e) {
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    });
</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');
?>