<?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");

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

$member_object = new Member();
$member        = $member_object->Get($_SESSION['memberid']);
$meals_per_day = $member->meals_per_day;

// Initialise modal variables so they are always defined before any output.
$background_color_modal = "#87cefa";
$grade = "";
$icon  = "success";

if (empty($page_action)) {
    if (isset($_POST['meal_score_totals']) && isset($_POST['posting'])) {
        $meal_scor_tot = 0;
        $background_color_modal = "#87cefa";

        $signupweek = $_POST['log_date'];
        /* find Monday of the posted week */
        for ($i = 0; $i < 7; $i++) {
            $date    = date('Y-m-d', strtotime("-{$i}days", strtotime($signupweek)));
            $dayName = date('D', strtotime($date));
            if ($dayName == "Mon") { $start_date = $date; }
        }
        /* find Sunday of the posted week */
        for ($i = 0; $i < 7; $i++) {
            $date    = date('Y-m-d', strtotime("+{$i}days", strtotime($signupweek)));
            $dayName = date('D', strtotime($date));
            if ($dayName == "Sun") { $end_date = $date; }
        }

        $accountability_chart_data = $member->GetAccountability_chartList([
            ['log_date', '>=', $start_date],
            ['log_date', '<=', $end_date],
        ]);

        if ($_POST['type'] == "save") {
            $meal_scor_tot += $_POST['meal_score_totals'];
            $meal_scor_tot += $_POST['activity_total_score'];
        }
        foreach ($accountability_chart_data as $acc_value) {
            if ($acc_value->log_date == $_POST['log_date']) {
                if ($_POST['type'] == "update") {
                    $meal_scor_tot += $_POST['meal_score_totals'];
                    $meal_scor_tot += $_POST['activity_total_score'];
                }
            } else {
                $meal_scor_tot += $acc_value->meal_score_totals;
                $meal_scor_tot += $acc_value->activity_total_score;
            }
        }

        if ($_POST['posting'] == "meal_score") {
            $icon = "success";
            if ($meal_scor_tot == 0) {
                $grade = "A+ (Amazing Job!)";
            } elseif ($meal_scor_tot <= 2) {
                $grade = "A (Outstanding Job!)";
            } elseif ($meal_scor_tot <= 4) {
                $grade = "B+ (Excellent Job!)";
            } elseif ($meal_scor_tot <= 6) {
                $grade = "B (Great Job!)";
            } else {
                $grade = "You Can Do Better: NEVER GIVE UP!";
                $icon  = "error";
                $background_color_modal = "#f5cb55";
            }
        }
    }
    $page_action = isset($_POST['action']) ? $_POST['action'] : "";
    $memberid    = $_SESSION['memberid'];
}
if ($page_action == 'edit')   { $memberid = $_GET['memberid']; }
if ($page_action == 'update') { $memberid = $_POST['memberid']; }

$msg = 'Daily Log';

include('member-header.php');
?>

<!-- ── SweetAlert ──────────────────────────────────────────────────────────── -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

<!-- ── Bootstrap 5 + Icons ────────────────────────────────────────────────── -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">

<!-- ── Page Styles ────────────────────────────────────────────────────────── -->
<style>
.app-layout {
width: 100%;
}
.page-header-title, .page-header-subtitle{
padding: 0;
}
.save-notice {
font-size: 14px;
color: #DC2626;
font-weight: 600;
margin-bottom: 21px;
padding: 0;
}
.card-ds-header span {
color: var(--textSecondary);
}
.log-row-label span {
color: var(--textSecondary);
}
.log-row-label span.mandatory {
color: red;
}
.log-btn {
min-width: 15px;
padding: 0 10px;
height: 36px;
}
.log-btn svg {
width: 16px;
height: 16px;
color: #6B7280;
}
.log-btn:last-child svg {
width: 14px;
height: 14px;
color: #6B7280;
}
.mandatory-note {
font-size: 12px;
color: var(--textSecondary);
}
.how-to-use-btn {
line-height: 20px;
}
.how-to-use-btn-mobile {
background: transparent;
border: none;
}
.how-to-use-btn-mobile svg {
width: 20.5px;
height: 20.5px;
}
.mandatory-note .mandatory {
color: red;
}
    /* SweetAlert modal theming */
    /*.swal-footer { text-align: center; }*/
    /*.swal-button:focus { box-shadow: none; }*/
    /*.swal-icon--success:before,*/
    /*.swal-icon--success:after,*/
    /*.swal-icon--success__hide-corners,*/
    /*.swal-overlay--show-modal .swal-modal {*/
    /*    background: <?php echo $background_color_modal; ?> !important;*/
    /*}*/
    /*.swal-title { color:#fff; font-weight:1000; font-size:33px; padding-bottom:30px !important; }*/
    /*.swal-icon--success__ring { border:4px solid yellow; }*/
    /*.swal-icon--success__line { background-color:yellow; }*/
    /*.swal-button { background:#fff; color:rgba(0,0,0,.84); }*/
    /*.swal-icon--error      { border-color:#f13d3d; }*/
    /*.swal-icon--error__line { background-color:#f13d3d; }*/

    /* Layout */
    /*.app-layout   { display:flex; min-height:100vh; }*/
    /*.main-content { flex:1; display:flex; flex-direction:column; min-width:0; background:#f8f9fa; }*/

    /* Page header */
    /*.page-header         { background:#fff; border-bottom:1px solid #e5e7eb; padding:1.25rem 1.5rem; }*/
    /*.page-header-meta    { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:1rem; }*/
    /*.page-header-title   { font-size:1.4rem; font-weight:700; margin:0; line-height:1.2; }*/
    /*.page-header-subtitle{ font-size:.875rem; color:#6b7280; margin:0; }*/

    /* Date-picker widget */
    /*.date-picker-wrapper {*/
    /*    position:relative; display:inline-flex; align-items:center; gap:.5rem;*/
    /*    background:#fff; border:1.5px solid #d1d5db; border-radius:.5rem;*/
    /*    padding:.5rem .75rem; cursor:pointer; user-select:none; transition:border-color .15s;*/
    /*}*/
    /*.date-picker-wrapper:hover,*/
    /*.date-picker-wrapper.picker-open { border-color:#111; }*/
    /*.date-picker-main   { display:flex; align-items:center; gap:.5rem; font-size:.9rem; font-weight:600; white-space:nowrap; }*/
    /*.date-picker-chevron{ display:flex; align-items:center; }*/
    /*.date-picker-input  { position:absolute; inset:0; opacity:0; width:100%; height:100%; cursor:pointer; border:none; }*/

    /* Body */
    /*.body-content    { padding:1.5rem; flex:1; }*/
    /*.instruction-text{ font-size:.875rem; color:#374151; margin-bottom:1.25rem; }*/
    /*.save-notice     { font-size:.85rem; color:#dc2626; font-weight:600; margin-bottom:1rem; }*/

    /* Cards */
    /*.card-ds        { background:#fff; border:1px solid #e5e7eb; border-radius:.75rem; overflow:hidden; height:100%; }*/
    /*.card-ds-header {*/
    /*    display:flex; align-items:center; gap:.625rem;*/
    /*    padding:.875rem 1.25rem; background:#f9fafb;*/
    /*    border-bottom:1px solid #e5e7eb;*/
    /*    font-weight:700; font-size:.875rem; letter-spacing:.05em; text-transform:uppercase;*/
    /*}*/

    /* Log rows */
    /*.log-list { padding:.5rem 0; }*/
    /*.log-row  {*/
    /*    display:flex; align-items:center; justify-content:space-between;*/
    /*    padding:.625rem 1.25rem; border-bottom:1px solid #f3f4f6; gap:1rem; min-height:3rem;*/
    /*}*/
    /*.log-row:last-child { border-bottom:none; }*/
    /*.log-row-label {*/
    /*    display:flex; align-items:center; gap:.5rem;*/
    /*    font-size:.9rem; font-weight:500; color:#111827; min-width:7rem;*/
    /*}*/
    /*.log-row-label svg { flex-shrink:0; }*/

    /* Icon-button group */
    /*.log-row-controls { display:flex; align-items:center; gap:.25rem; }*/
    /*.log-btn {*/
    /*    display:inline-flex; align-items:center; justify-content:center;*/
    /*    width:2.25rem; height:2.25rem; border-radius:.5rem;*/
    /*    border:1.5px solid #e5e7eb; background:#fff;*/
    /*    cursor:pointer; transition:background .12s, border-color .12s; padding:0; flex-shrink:0;*/
    /*}*/
    /*.log-btn:hover { background:#f3f4f6; border-color:#9ca3af; }*/

    /* Active states */
    /*.log-btn.active-check { background:#d1fae5; border-color:#10b981; }*/
    /*.log-btn.active-check  svg path { fill:#10b981; }*/
    /*.log-btn.active-plus  { background:#dbeafe; border-color:#3b82f6; }*/
    /*.log-btn.active-plus   svg path { fill:#3b82f6; }*/
    /*.log-btn.active-minus { background:#fee2e2; border-color:#ef4444; }*/
    /*.log-btn.active-minus  svg path { fill:#ef4444; }*/
    /*.log-btn.active-zero  { background:#fef9c3; border-color:#eab308; }*/
    /*.log-btn.active-zero   svg path { fill:#eab308; }*/

    /* The real <select> elements from accountability_chart.php stay hidden —
       the icon buttons above drive their values via JS.                       */
    /*.log-row-controls select,*/
    select.custom-select { display:none !important; }

    /* Validation error labels (rendered by accountability_chart.php) */
    /*label.error { color:#dc2626; font-size:.78rem; display:block; margin-top:.15rem; }*/

    /* Action bar */
    /*.action-bar      { display:flex; align-items:center; justify-content:space-between; padding:1rem 1.5rem; background:#fff; border-top:1px solid #e5e7eb; gap:.75rem; flex-wrap:wrap; }*/
    /*.btn-ds-primary  { background:#111; color:#fff; border:none; border-radius:.5rem; padding:.625rem 1.5rem; font-size:.9rem; font-weight:600; cursor:pointer; transition:background .15s; }*/
    /*.btn-ds-primary:hover { background:#333; }*/
    /*.how-to-use-btn,*/
    /*.how-to-use-btn-mobile {*/
    /*    display:inline-flex; align-items:center; gap:.4rem;*/
    /*    font-size:.875rem; font-weight:500; color:#374151;*/
    /*    background:none; border:1.5px solid #d1d5db; border-radius:.5rem;*/
    /*    padding:.5rem 1rem; cursor:pointer; text-decoration:none;*/
    /*    transition:border-color .15s, background .15s;*/
    /*}*/
    /*.how-to-use-btn:hover,*/
    /*.how-to-use-btn-mobile:hover { border-color:#9ca3af; background:#f9fafb; }*/

    /* Help panel */
    #help-panel { display:none; background:#d5eafe; border-radius:.5rem; padding:1rem 1.25rem; margin-top:1rem; font-size:.8rem; line-height:1.6; }
    #help-panel p { margin-bottom:.5rem; }

    /* Mandatory note */
    /*.mandatory-note { font-size:.8rem; color:#374151; margin-top:1rem; }*/
    /*.mandatory { color:red; font-weight:700; }*/

    /* accountability_chart.php renders a <table> + .button wrapper —
       hide those structural elements; only the <select> values matter.  */
    /*#accountability-form-fields table,*/
    /*#accountability-form-fields .button,*/
    /*#accountability-form-fields .text-upper,*/
    /*#accountability-form-fields input[type="submit"] { display:none !important; }*/

    /* But keep all hidden inputs visible to the DOM (they POST fine) */
    /*#accountability-form-fields input[type="hidden"] { display:block !important; height:0; overflow:hidden; margin:0; padding:0; }*/

    /*@media (max-width:768px) {*/
    /*    .body-content { padding:1rem; }*/
    /*    .action-bar   { padding:.75rem 1rem; }*/
    /*    .page-header  { padding:1rem; }*/
    /*}*/
</style>



<div class="app-layout">
    <?php include('sidebar.php'); ?>
<main class="main-content">

    <!-- ── Page Header ──────────────────────────────────────────────────────── -->
    <header class="page-header">
        <div class="page-header-meta">
            <div>
                <h1 class="page-header-title">Daily Log</h1>
                <p class="page-header-subtitle">Track Meals &amp; Activity For The Day</p>
            </div>

            <!-- Date-picker widget (visual replacement for the old .datepicker dropdown) -->
            <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"><?php echo date('F d, Y'); ?></span>
                </div>
                <div class="date-picker-chevron">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M6 9L12 15L18 9" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </div>
                <!--
                    id="log_date_calendar" + class="datepicker" must be preserved:
                    the AJAX handler in the original code reads .datepicker's value.
                -->
                <input type="date"
                       class="date-picker-input datepicker"
                       id="log_date_calendar"
                       value="<?php echo date('Y-m-d'); ?>"
                       aria-label="Select date">
            </div>
        </div>
    </header>

    <!-- ── Body ─────────────────────────────────────────────────────────────── -->
    <div class="body-content">
        <p class="save-notice">
            Please click <strong>"Save Entry"</strong> to save your data. If you don't press it, your work will not be saved.
        </p>
        <p class="instruction-text">Select one status for each meal and activity, then save your entry.</p>

        <!--
        ╔══════════════════════════════════════════════════════════════════════╗
        ║  FORM — accountability_chart.php is included inside #accountability- ║
        ║  form-fields. That include renders all <select> fields, all hidden   ║
        ║  inputs (log_date, member_id, type, posting, meal_score_totals,      ║
        ║  activity_total_score, accountability_chart_id) and the submit       ║
        ║  button. CSS above hides the table/button wrappers; JS below reads   ║
        ║  each select's value to highlight the matching icon button, and      ║
        ║  writes back to the select when an icon button is clicked.           ║
        ╚══════════════════════════════════════════════════════════════════════╝
        -->
        <form method="POST"
              id="accountability_chart_form"
              name="accountability_chart_form"
              action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'); ?>">

            <!-- accountability_chart.php echoes ALL form fields + hidden inputs -->
            <div id="accountability-form-fields">
                <?php include('accountability_chart.php'); ?>
            </div>

            <!-- ── NEW CARD UI ─────────────────────────────────────────────── -->
            <div class="cards-area mt-3">
                <div class="row g-4">

                    <!-- ═══════════════ MEALS CARD ═══════════════ -->
                    <div class="col-12 col-xl-6">
                        <div class="card-ds">
                            <div class="card-ds-header">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <g clip-path="url(#c1)">
                                        <path d="M7 2V22" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        <path d="M21 15V2C19.6739 2 18.4021 2.52678 17.4645 3.46447C16.5268 4.40215 16 5.67392 16 7V13C16 14.1 16.9 15 18 15H21ZM21 15V22" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                    </g>
                                    <defs><clipPath id="c1"><rect width="24" height="24" fill="white"/></clipPath></defs>
                                </svg>
                                <span>MEALS</span>
                            </div>
                            <div class="log-list">

                                <!-- Breakfast -->
                                <div class="log-row">
                                    <div class="log-row-label">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M11.5 16C13.433 16 15 14.433 15 12.5C15 10.567 13.433 9 11.5 9C9.567 9 8 10.567 8 12.5C8 14.433 9.567 16 11.5 16Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M3 8C3 4.5 5.5 2 9.5 2C14.5 2 14.33 5 17 7C19.67 9 22 9 22 13C22 17.5 19.5 19.5 15 19.5C12.5 19.5 12.5 22 9 22C5.5 22 2 20 2 16.5C2 13.5 3.5 13.5 3.5 11.5C3.5 10 3 9 3 8Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span>Breakfast <span class="mandatory">*</span></span>
                                    </div>
                                    <div class="log-row-controls" data-field="breakfast">
                                        <?php echo renderLogBtns('breakfast'); ?>
                                    </div>
                                </div>

                                <!-- Snack 1 (visibility driven by meals_per_day; required rule set in JS) -->
                                <div class="log-row" id="row_snack1">
                                    <div class="log-row-label">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M12 6.528V3C12 2.73478 12.1054 2.48043 12.2929 2.29289C12.4804 2.10536 12.7348 2 13 2" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M18.237 21C20.6763 18.2415 22.0156 14.6822 22 11C22 9.84175 21.6647 8.70827 21.0347 7.73637C20.4047 6.76448 19.5068 5.99571 18.4495 5.52287C17.3921 5.05003 16.2205 4.89333 15.0761 5.07169C13.9317 5.25004 12.8633 5.75583 12 6.52799C11.1367 5.75583 10.0684 5.25004 8.92395 5.07169C7.77952 4.89333 6.60793 5.05003 5.55059 5.52287C4.49326 5.99571 3.59539 6.76448 2.96535 7.73637C2.33531 8.70827 2.00005 9.84175 2.00002 11C1.99371 14.6805 3.33188 18.2367 5.76302 21C6.21073 21.5009 6.81359 21.837 7.47503 21.9545C8.13647 22.0719 8.81821 21.964 9.41102 21.648C10.2078 21.2229 11.097 21.0005 12 21.0005C12.9031 21.0005 13.7923 21.2229 14.589 21.648C15.1818 21.964 15.8636 22.0719 16.525 21.9545C17.1865 21.837 17.7893 21.5009 18.237 21Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span>Snack 1 <span class="mandatory">*</span></span>
                                    </div>
                                    <div class="log-row-controls" data-field="snack1">
                                        <?php echo renderLogBtns('snack1'); ?>
                                    </div>
                                </div>

                                <!-- Lunch -->
                                <div class="log-row">
                                    <div class="log-row-label">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M2.37 11.223L10.742 4.44601C11.098 4.15797 11.5421 4.00082 12 4.00082C12.4579 4.00082 12.902 4.15797 13.258 4.44601L21.629 11.223" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M21 15C21.2652 15 21.5196 15.1054 21.7071 15.2929C21.8946 15.4804 22 15.7348 22 16V18C22 18.2652 21.8946 18.5196 21.7071 18.7071C21.5196 18.8946 21.2652 19 21 19H15.75" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M3 15C2.73478 15 2.48043 15.1054 2.29289 15.2929C2.10536 15.4804 2 15.7348 2 16V18C2 18.2652 2.10536 18.5196 2.29289 18.7071C2.48043 18.8946 2.73478 19 3 19H12" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M6.67004 15L12.8 19.6C13.0102 19.7576 13.2493 19.8722 13.5037 19.9374C13.7581 20.0026 14.0229 20.017 14.2829 19.9799C14.5429 19.9428 14.793 19.8548 15.019 19.7209C15.245 19.5871 15.4425 19.4101 15.6 19.2L18.75 15" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M21 11H3C2.44772 11 2 11.4477 2 12V14C2 14.5523 2.44772 15 3 15H21C21.5523 15 22 14.5523 22 14V12C22 11.4477 21.5523 11 21 11Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span>Lunch <span class="mandatory">*</span></span>
                                    </div>
                                    <div class="log-row-controls" data-field="lunch">
                                        <?php echo renderLogBtns('lunch'); ?>
                                    </div>
                                </div>

                                <!-- Snack 2 -->
                                <div class="log-row" id="row_snack2">
                                    <div class="log-row-label">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M12 6.528V3C12 2.73478 12.1054 2.48043 12.2929 2.29289C12.4804 2.10536 12.7348 2 13 2" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M18.237 21C20.6763 18.2415 22.0156 14.6822 22 11C22 9.84175 21.6647 8.70827 21.0347 7.73637C20.4047 6.76448 19.5068 5.99571 18.4495 5.52287C17.3921 5.05003 16.2205 4.89333 15.0761 5.07169C13.9317 5.25004 12.8633 5.75583 12 6.52799C11.1367 5.75583 10.0684 5.25004 8.92395 5.07169C7.77952 4.89333 6.60793 5.05003 5.55059 5.52287C4.49326 5.99571 3.59539 6.76448 2.96535 7.73637C2.33531 8.70827 2.00005 9.84175 2.00002 11C1.99371 14.6805 3.33188 18.2367 5.76302 21C6.21073 21.5009 6.81359 21.837 7.47503 21.9545C8.13647 22.0719 8.81821 21.964 9.41102 21.648C10.2078 21.2229 11.097 21.0005 12 21.0005C12.9031 21.0005 13.7923 21.2229 14.589 21.648C15.1818 21.964 15.8636 22.0719 16.525 21.9545C17.1865 21.837 17.7893 21.5009 18.237 21Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span>Snack 2</span>
                                    </div>
                                    <div class="log-row-controls" data-field="snack2">
                                        <?php echo renderLogBtns('snack2'); ?>
                                    </div>
                                </div>

                                <!-- Dinner -->
                                <div class="log-row">
                                    <div class="log-row-label">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M12 3V2" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M15.4 17.4L18.6 14.6C18.7904 14.4161 19.0152 14.2716 19.2615 14.1746C19.5077 14.0776 19.7707 14.0301 20.0354 14.0347C20.3 14.0394 20.5611 14.0961 20.8039 14.2017C21.0466 14.3072 21.2662 14.4596 21.45 14.65C21.6339 14.8404 21.7784 15.0652 21.8754 15.3114C21.9724 15.5577 22.0199 15.8207 22.0153 16.0853C22.0106 16.35 21.9539 16.6111 21.8483 16.8539C21.7428 17.0966 21.5904 17.3161 21.4 17.5L17.8 20.8C17.1 21.6 16.1 22 15 22H11C9.9 22 8.9 21.6 8.2 20.8L6.898 19.336C6.80426 19.2304 6.68923 19.1459 6.56048 19.088C6.43173 19.0301 6.29218 19.0001 6.151 19H5" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M2 14H14C14.5304 14 15.0391 14.2107 15.4142 14.5858C15.7893 14.9609 16 15.4696 16 16C16 16.5304 15.7893 17.0391 15.4142 17.4142C15.0391 17.7893 14.5304 18 14 18H12" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M4 10H20" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M5 10C5 8.14348 5.7375 6.36301 7.05025 5.05025C8.36301 3.7375 10.1435 3 12 3C13.8565 3 15.637 3.7375 16.9497 5.05025C18.2625 6.36301 19 8.14348 19 10" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M5 14V20C5 20.2652 4.89464 20.5196 4.70711 20.7071C4.51957 20.8946 4.26522 21 4 21H2" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span>Dinner <span class="mandatory">*</span></span>
                                    </div>
                                    <div class="log-row-controls" data-field="dinner">
                                        <?php echo renderLogBtns('dinner'); ?>
                                    </div>
                                </div>

                                <!-- Snack 3 -->
                                <div class="log-row" id="row_snack3">
                                    <div class="log-row-label">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M12 6.528V3C12 2.73478 12.1054 2.48043 12.2929 2.29289C12.4804 2.10536 12.7348 2 13 2" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M18.237 21C20.6763 18.2415 22.0156 14.6822 22 11C22 9.84175 21.6647 8.70827 21.0347 7.73637C20.4047 6.76448 19.5068 5.99571 18.4495 5.52287C17.3921 5.05003 16.2205 4.89333 15.0761 5.07169C13.9317 5.25004 12.8633 5.75583 12 6.52799C11.1367 5.75583 10.0684 5.25004 8.92395 5.07169C7.77952 4.89333 6.60793 5.05003 5.55059 5.52287C4.49326 5.99571 3.59539 6.76448 2.96535 7.73637C2.33531 8.70827 2.00005 9.84175 2.00002 11C1.99371 14.6805 3.33188 18.2367 5.76302 21C6.21073 21.5009 6.81359 21.837 7.47503 21.9545C8.13647 22.0719 8.81821 21.964 9.41102 21.648C10.2078 21.2229 11.097 21.0005 12 21.0005C12.9031 21.0005 13.7923 21.2229 14.589 21.648C15.1818 21.964 15.8636 22.0719 16.525 21.9545C17.1865 21.837 17.7893 21.5009 18.237 21Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span>Snack 3</span>
                                    </div>
                                    <div class="log-row-controls" data-field="snack3">
                                        <?php echo renderLogBtns('snack3'); ?>
                                    </div>
                                </div>

                                <!-- Extras -->
                                <div class="log-row">
                                    <div class="log-row-label">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M19 3H5C3.89543 3 3 3.89543 3 5V19C3 20.1046 3.89543 21 5 21H19C20.1046 21 21 20.1046 21 19V5C21 3.89543 20.1046 3 19 3Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M8 12H16" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M12 8V16" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span>Extras</span>
                                    </div>
                                    <div class="log-row-controls" data-field="extras">
                                        <?php echo renderLogBtns('extras'); ?>
                                    </div>
                                </div>

                            </div><!-- /.log-list -->
                        </div><!-- /.card-ds -->
                    </div><!-- /.col Meals -->

                    <!-- ═══════════════ ACTIVITY CARD ═══════════════ -->
                    <div class="col-12 col-xl-6">
                        <div class="card-ds">
                            <div class="card-ds-header">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M15 10.42L19.8 5.34998" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                    <path d="M19 18H22" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                    <path d="M9.5 22L21.414 9.41499C21.6168 9.21238 21.7736 8.96855 21.8739 8.70003C21.9742 8.4315 22.0156 8.14456 21.9953 7.85863C21.975 7.57271 21.8935 7.29449 21.7563 7.04282C21.6191 6.79116 21.4294 6.57193 21.2 6.39999L15.59 2.19199C15.4409 2.08301 15.2645 2.01747 15.0804 2.00262C14.8963 1.98778 14.7116 2.02422 14.547 2.1079C14.3823 2.19158 14.244 2.31922 14.1475 2.47669C14.0509 2.63415 13.9999 2.81528 14 2.99999V4.99999C14 5.42451 13.8649 5.83802 13.6143 6.18068C13.3637 6.52333 13.0106 6.77736 12.606 6.90599L8.677 8.05299C8.47943 8.12042 8.30791 8.24799 8.1865 8.41782C8.06509 8.58765 7.99987 8.79122 8 8.99999C7.845 15.393 5.918 18 4 18C3.46957 18 2.96086 18.2107 2.58579 18.5858C2.21071 18.9608 2 19.4696 2 20C2 20.5304 2.21071 21.0391 2.58579 21.4142C2.96086 21.7893 3.46957 22 4 22H18" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                                <span>ACTIVITY LEVEL</span>
                            </div>
                            <div class="log-list">

                                <!-- Cardio -->
                                <div class="log-row">
                                    <div class="log-row-label">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M2 9.50001C2.00002 8.38721 2.33759 7.30059 2.96813 6.38367C3.59867 5.46675 4.49252 4.76267 5.53161 4.36441C6.5707 3.96615 7.70616 3.89245 8.78801 4.15305C9.86987 4.41365 10.8472 4.99629 11.591 5.82401C11.6434 5.88002 11.7067 5.92468 11.7771 5.95521C11.8474 5.98574 11.9233 6.00149 12 6.00149C12.0767 6.00149 12.1526 5.98574 12.2229 5.95521C12.2933 5.92468 12.3566 5.88002 12.409 5.82401C13.1504 4.99091 14.128 4.40338 15.2116 4.13961C16.2952 3.87585 17.4335 3.94836 18.4749 4.34749C19.5163 4.74663 20.4114 5.45346 21.0411 6.37391C21.6708 7.29436 22.0053 8.38477 22 9.50001C22 11.79 20.5 13.5 19 15L13.508 20.313C13.3217 20.527 13.0919 20.6989 12.834 20.8173C12.5762 20.9357 12.296 20.9979 12.0123 20.9997C11.7285 21.0015 11.4476 20.9428 11.1883 20.8277C10.9289 20.7126 10.697 20.5436 10.508 20.332L5 15C3.5 13.5 2 11.8 2 9.50001Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M3.21997 13H9.49997L9.99997 12L12 16.5L14 9.5L15.5 13H20.77" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span>Cardio</span>
                                    </div>
                                    <div class="log-row-controls" data-field="cardio">
                                        <?php echo renderLogBtns('cardio'); ?>
                                    </div>
                                </div>

                                <!-- Resistance -->
                                <div class="log-row">
                                    <div class="log-row-label">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M17.596 12.768C17.9712 13.1432 18.48 13.3539 19.0105 13.3539C19.5411 13.3539 20.0499 13.1432 20.425 12.768C20.8002 12.3929 21.0109 11.884 21.0109 11.3535C21.0109 10.823 20.8002 10.3142 20.425 9.93901L18.657 8.17201C19.0322 8.54702 19.5409 8.75765 20.0714 8.75756C20.334 8.75751 20.5941 8.70573 20.8367 8.60518C21.0794 8.50462 21.2998 8.35726 21.4855 8.17151C21.6712 7.98575 21.8185 7.76524 21.919 7.52257C22.0194 7.27989 22.0711 7.0198 22.0711 6.75715C22.071 6.4945 22.0192 6.23443 21.9187 5.99179C21.8181 5.74915 21.6708 5.5287 21.485 5.34301L18.657 2.51501C18.282 2.13986 17.7733 1.92905 17.2429 1.92896C16.7124 1.92886 16.2037 2.13949 15.8285 2.51451C15.4534 2.88952 15.2426 3.39821 15.2425 3.92865C15.2424 4.4591 15.453 4.96786 15.828 5.34301L14.061 3.57501C13.8753 3.38925 13.6547 3.2419 13.412 3.14137C13.1693 3.04084 12.9092 2.9891 12.6465 2.9891C12.3838 2.9891 12.1237 3.04084 11.881 3.14137C11.6383 3.2419 11.4178 3.38925 11.232 3.57501C11.0463 3.76076 10.8989 3.98128 10.7984 4.22398C10.6979 4.46669 10.6461 4.72681 10.6461 4.98951C10.6461 5.2522 10.6979 5.51233 10.7984 5.75503C10.8989 5.99773 11.0463 6.21825 11.232 6.40401L17.596 12.768Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M2.5 21.5001L3.9 20.1001" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M20.1 3.9L21.5 2.5" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M5.34301 21.4849C5.71802 21.8601 6.22671 22.0709 6.75715 22.071C7.0198 22.071 7.27989 22.0193 7.52257 21.9188C7.76524 21.8184 7.98575 21.6711 8.17151 21.4854C8.35726 21.2997 8.50462 21.0793 8.60518 20.8366C8.70573 20.594 8.75751 20.3339 8.75756 20.0713C8.7576 19.8086 8.70592 19.5485 8.60545 19.3058C8.50498 19.0632 8.3577 18.8427 8.17201 18.6569L9.93901 20.4249C10.3142 20.8 10.823 21.0108 11.3535 21.0108C11.884 21.0108 12.3929 20.8 12.768 20.4249C13.1432 20.0498 13.3539 19.5409 13.3539 19.0104C13.3539 18.4799 13.1432 17.9711 12.768 17.5959L6.40401 11.2319C6.21825 11.0461 5.99773 10.8988 5.75503 10.7983C5.51233 10.6977 5.2522 10.646 4.98951 10.646C4.72681 10.646 4.46669 10.6977 4.22398 10.7983C3.98128 10.8988 3.76076 11.0461 3.57501 11.2319C3.38925 11.4177 3.2419 11.6382 3.14137 11.8809C3.04084 12.1236 2.9891 12.3837 2.9891 12.6464C2.9891 12.9091 3.04084 13.1692 3.14137 13.4119C3.2419 13.6546 3.38925 13.8751 3.57501 14.0609L5.34301 15.8279C4.96786 15.4529 4.4591 15.2423 3.92865 15.2423C3.39821 15.2424 2.88952 15.4533 2.51451 15.8284C2.13949 16.2035 1.92886 16.7123 1.92896 17.2428C1.92905 17.7732 2.13986 18.2819 2.51501 18.6569L5.34301 21.4849Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M9.59998 14.4001L14.4 9.6001" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span>Resistance</span>
                                    </div>
                                    <div class="log-row-controls" data-field="resistance">
                                        <?php echo renderLogBtns('resistance'); ?>
                                    </div>
                                </div>

                                <!-- Homework -->
                                <div class="log-row">
                                    <div class="log-row-label">
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M12 21V7" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M16 12L18 14L22 10" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M22 6V4C22 3.73478 21.8946 3.48043 21.7071 3.29289C21.5196 3.10536 21.2652 3 21 3H16C14.9391 3 13.9217 3.42143 13.1716 4.17157C12.4214 4.92172 12 5.93913 12 7C12 5.93913 11.5786 4.92172 10.8284 4.17157C10.0783 3.42143 9.06087 3 8 3H3C2.73478 3 2.48043 3.10536 2.29289 3.29289C2.10536 3.48043 2 3.73478 2 4V17C2 17.2652 2.10536 17.5196 2.29289 17.7071C2.48043 17.8946 2.73478 18 3 18H9C9.79565 18 10.5587 18.3161 11.1213 18.8787C11.6839 19.4413 12 20.2044 12 21C12 20.2044 12.3161 19.4413 12.8787 18.8787C13.4413 18.3161 14.2044 18 15 18H21C21.2652 18 21.5196 17.8946 21.7071 17.7071C21.8946 17.5196 22 17.2652 22 17V15.7" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span>Homework</span>
                                    </div>
                                    <div class="log-row-controls" data-field="homework">
                                        <?php echo renderLogBtns('homework'); ?>
                                    </div>
                                </div>

                            </div><!-- /.log-list -->
                        </div><!-- /.card-ds -->
                    </div><!-- /.col Activity -->

                </div><!-- /.row -->

                <!-- Mandatory note -->
                <p class="mandatory-note mt-2"><span class="mandatory">*</span> indicates mandatory fields.</p>

                <!-- Help panel -->
                <div id="help-panel">
                    <p><strong>Here is how the Accountability Chart works:</strong></p>
                    <p><strong>Scoring System:</strong><br>
                        Check = 0 pts &nbsp;|&nbsp; Minus (less than) = 1 pt &nbsp;|&nbsp; Plus (more than) = 1 pt &nbsp;|&nbsp; "0" (skipped) = 1 pt
                    </p>
                    <p><strong>Meal Portion:</strong><br>
                        Ate exactly as planned → Check. Ate less → Minus. Ate more → Plus. Skipped → 0.<br>
                        Any food above your plan → Plus in Extras. Nothing extra → leave Extras blank.
                    </p>
                    <p><strong>Activity Level:</strong><br>
                        Completed as planned → Check. Did more → Plus. Did less → Minus. Skipped → 0.
                    </p>
                </div>

                <!-- Mobile action bar -->
                <div class="action-bar d-xl-none mt-3 action-bar-mobile" style="border-radius:.75rem;">
                    <button type="button" class="how-to-use-btn-mobile" id="helpToggleMobile">
                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.99996 18.3333C14.6023 18.3333 18.3333 14.6023 18.3333 9.99996C18.3333 5.39759 14.6023 1.66663 9.99996 1.66663C5.39759 1.66663 1.66663 5.39759 1.66663 9.99996C1.66663 14.6023 5.39759 18.3333 9.99996 18.3333Z" stroke="#212529" stroke-opacity="0.7" stroke-width="0.696226" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10 13.3333V10" stroke="#212529" stroke-opacity="0.7" stroke-width="0.696226" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10 6.66663H10.0083" stroke="#212529" stroke-opacity="0.7" stroke-width="0.696226" stroke-linecap="round" stroke-linejoin="round"/>
</svg>How To Use
                    </button>
                    <button type="button" class="btn-ds-primary" id="saveEntryMobile">Save Entry</button>
                </div>

            </div><!-- /.cards-area -->
        </form><!-- /#accountability_chart_form -->
    </div><!-- /.body-content -->

    <!-- Desktop action bar -->
    <div class="action-bar d-none d-xl-flex">
        <button type="button" class="how-to-use-btn" id="helpToggleDesktop">How To Use</button>
        <button type="button" class="btn-ds-primary" id="saveEntryDesktop">Save Entry</button>
    </div>

</main>
</div><!-- /.app-layout -->


<!-- ── Scripts ─────────────────────────────────────────────────────────────── -->
<script src="../coach/js/jquery.js"></script>
<script src="../coach/js/jquery.validate.js"></script>
<script src="../coach/js/jquery-dropdown-datepicker.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
// ================================================================
// ICON-BUTTON ↔ SELECT BRIDGE
// Each .log-row-controls[data-field] sits beside the hidden
// <select name="fieldName"> that accountability_chart.php rendered.
// Values: 1=check, 2=plus, 3=minus, 4=zero
// ================================================================
var BTN_MAP    = { check:1, plus:2, minus:3, zero:4 };
var ACTIVE_CLS = { 1:'active-check', 2:'active-plus', 3:'active-minus', 4:'active-zero' };

/**
 * Read every hidden <select> (rendered by accountability_chart.php)
 * and highlight the matching icon button.
 * Called on page-load and after every AJAX date-change refresh.
 */
function syncButtonsFromSelects() {
    document.querySelectorAll('.log-row-controls[data-field]').forEach(function (ctrl) {
        var field = ctrl.getAttribute('data-field');
        var sel   = document.getElementById(field);
        if (!sel) return;

        // Clear all active states first
        ctrl.querySelectorAll('.log-btn').forEach(function (b) {
            Object.values(ACTIVE_CLS).forEach(function (c) { b.classList.remove(c); });
        });

        var val = parseInt(sel.value, 10);
        if (!val || !ACTIVE_CLS[val]) return;

        // Map select value back to data-btn attribute
        var btnTypeMap = { 1:'check', 2:'plus', 3:'minus', 4:'zero' };
        var btn = ctrl.querySelector('[data-btn="' + btnTypeMap[val] + '"]');
        if (btn) btn.classList.add(ACTIVE_CLS[val]);
    });
}

// Clicking an icon button → update the hidden select
$(document).on('click', '.log-btn', function () {
    var $btn   = $(this);
    var btnKey = $btn.data('btn');            // 'check'|'plus'|'minus'|'zero'
    var $ctrl  = $btn.closest('.log-row-controls');
    var field  = $ctrl.data('field');
    var $sel   = $('#' + field);
    var newVal = BTN_MAP[btnKey];

    // Toggle off if already active
    if ($btn.hasClass(ACTIVE_CLS[newVal])) {
        $btn.removeClass(ACTIVE_CLS[newVal]);
        $sel.val('');
        return;
    }

    // Deactivate siblings
    $ctrl.find('.log-btn').each(function () {
        Object.values(ACTIVE_CLS).forEach(function (c) { $(this).removeClass(c); }.bind(this));
    });

    $btn.addClass(ACTIVE_CLS[newVal]);
    $sel.val(newVal);
});

// ================================================================
// DATE PICKER — syncs new widget with #log_date_id (hidden input
// rendered by accountability_chart.php) and fires the AJAX reload
// ================================================================
(function () {
    var dateInput = document.getElementById('log_date_calendar');
    var dateDisp  = document.getElementById('dateDisplay');
    var wrapper   = document.getElementById('datePickerWrapper');

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

    // Initialise display from the PHP-rendered date
    var existingDate = $('#log_date_id').val();
    if (existingDate) {
        dateInput.value       = existingDate;
        dateDisp.textContent  = formatDate(existingDate);
    } else if (dateInput.value) {
        dateDisp.textContent  = formatDate(dateInput.value);
    }

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

    dateInput.addEventListener('change', function () {
        if (!this.value) {
            var t  = new Date();
            this.value = t.getFullYear() + '-'
                       + String(t.getMonth()+1).padStart(2,'0') + '-'
                       + String(t.getDate()).padStart(2,'0');
        }
        dateDisp.textContent = formatDate(this.value);
        wrapper.classList.remove('picker-open');

        // AJAX reload — identical to original code
        var url = "accountability_chart.php?type=change_log_date&get_log_date="
                + encodeURIComponent(this.value)
                + "&form_action=<?php echo urlencode(htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8')); ?>";
        var html = jQuery.ajax({ type:"POST", url:url, async:false }).responseText;
        html = html.replace(/^[\s]+/g, "");
        $('#accountability-form-fields').html(html);

        // Re-sync icon buttons after AJAX refresh
        syncButtonsFromSelects();
        applySnackVisibility();
    });

    dateInput.addEventListener('blur', function () {
        wrapper.classList.remove('picker-open');
    });
})();

// ================================================================
// SNACK ROW VISIBILITY
// accountability_chart.php conditionally omits snack2/snack3
// <select> elements based on meals_per_day. Mirror that here by
// showing/hiding the card rows based on select presence.
// ================================================================
function applySnackVisibility() {
    // A snack row is visible only when its <select> exists in the DOM
    // (accountability_chart.php only renders snack2 when meals_per_day!=4
    //  and snack3 when meals_per_day!=4 && meals_per_day!=5)
    var hasSnack1 = document.getElementById('snack1') !== null;
    var hasSnack2 = document.getElementById('snack2') !== null;
    var hasSnack3 = document.getElementById('snack3') !== null;

    var r1 = document.getElementById('row_snack1');
    var r2 = document.getElementById('row_snack2');
    var r3 = document.getElementById('row_snack3');

    if (r1) r1.style.display = hasSnack1 ? '' : 'none';
    if (r2) r2.style.display = hasSnack2 ? '' : 'none';
    if (r3) r3.style.display = hasSnack3 ? '' : 'none';
}

// ================================================================
// FORM VALIDATION + SCORE CALCULATION (identical logic to original)
// ================================================================
var validator = $("#accountability_chart_form").validate({
    rules: {
        breakfast : { required: true },
        snack1    : { required: $("#snack1").length > 0 },
        lunch     : { required: true },
        snack2    : { required: false },   // optional per plan
        dinner    : { required: true },
        snack3    : { required: false }    // optional per plan
    },
    messages: {
        breakfast : { required: "Please select Breakfast" },
        snack1    : { required: "Please select Snack 1" },
        lunch     : { required: "Please select Lunch" },
        dinner    : { required: "Please select Dinner" }
    },
    submitHandler: function (form) {
        var meal_scor     = 0;
        var activity_scor = 0;

        if ($('#breakfast').val()  != 1) { meal_scor++; }
        if ($('#snack1').length && $('#snack1').val() != 1 && $('#snack1').val() !== '') { meal_scor++; }
        if ($('#lunch').val()      != 1) { meal_scor++; }
        if ($('#snack2').length && $('#snack2').val() != '' && $('#snack2').val() != 1)  { meal_scor++; }
        if ($('#dinner').val()     != 1) { meal_scor++; }
        if ($('#snack3').length && $('#snack3').val() != '' && $('#snack3').val() != 1)  { meal_scor++; }

        var extrasVal = $('#extras').val();
        if (extrasVal == 2 || extrasVal == 3 || extrasVal == 4) { meal_scor++; }

        $('#meal_score_totals').val(meal_scor);

        var cardioVal = $('#cardio').val();
        var hwVal     = $('#homework').val();
        var resVal    = $('#resistance').val();
        if (cardioVal == 2 || cardioVal == 3 || cardioVal == 4) { activity_scor++; }
        if (hwVal     == 2 || hwVal     == 3 || hwVal     == 4) { activity_scor++; }
        if (resVal    == 2 || resVal    == 3 || resVal    == 4) { activity_scor++; }

        $('#activity_total_score').val(activity_scor);
        form.submit();
    }
});

// ================================================================
// HELP PANEL TOGGLE
// ================================================================
function toggleHelp() {
    var p = document.getElementById('help-panel');
    p.style.display = (p.style.display === 'block') ? 'none' : 'block';
}
document.getElementById('helpToggleDesktop').addEventListener('click', toggleHelp);
document.getElementById('helpToggleMobile').addEventListener('click', toggleHelp);

// Desktop "Save Entry" triggers form validation + submit
document.getElementById('saveEntryDesktop').addEventListener('click', function () {
    $('#accountability_chart_form').submit();
});
document.getElementById('saveEntryMobile').addEventListener('click', function () {
    $('#accountability_chart_form').submit();
});

// ================================================================
// ON DOM READY — restore state from accountability_chart.php output
// ================================================================
$(document).ready(function () {
    syncButtonsFromSelects();
    applySnackVisibility();
});
</script>

<?php if (isset($_POST['meal_score_totals']) && isset($_POST['posting'])) : ?>
<style>#main-header { z-index: unset !important; }</style>
<script>
    $(document).ready(function () {
        swal({
            title  : '<?php echo addslashes($grade); ?>',
            icon   : '<?php echo $icon; ?>',
            timer  : 4000,
            buttons: false
        });
    });
</script>
<?php endif; ?>

<?php
/**
 * renderLogBtns($field)
 * Renders the four icon-buttons (check / plus / minus / zero) for a
 * given field name. PHP function declarations are hoisted so calling
 * this above the declaration is safe.
 */
function renderLogBtns(string $field): string
{
    static $icons = [
        'check' => [
            'vb' => '0 0 20 20', 'sz' => '20',
            'path' => '<path fill-rule="evenodd" clip-rule="evenodd" d="M17.1249 5.23747C17.5124 5.57997 17.5487 6.17247 17.2062 6.56247L10.0187 14.6875C9.93567 14.7813 9.8347 14.8576 9.72172 14.9118C9.60874 14.9659 9.48604 14.9969 9.36089 15.0028C9.23574 15.0088 9.11066 14.9896 8.99306 14.9464C8.87545 14.9031 8.7677 14.8368 8.67618 14.7512L3.98868 10.3762C3.80835 10.2063 3.70264 9.97186 3.69464 9.7242C3.68665 9.47654 3.77703 9.23579 3.94602 9.05457C4.11501 8.87335 4.34888 8.76641 4.59649 8.75711C4.8441 8.74782 5.08533 8.83693 5.26743 9.00497L9.25493 12.7175L15.8049 5.31747C15.9857 5.14972 16.0965 5.09569 16.2074 5.04166 16.4508 5.00259C16.5739 4.99516 16.6973 5.01208 16.8138 5.05238C16.9303 5.09269 17.0377 5.15558 17.1299 5.23747H17.1249Z" fill="#6B7280"/>',
        ],
        'plus' => [
            'vb' => '0 0 20 20', 'sz' => '20',
            'path' => '<path d="M15.8334 10.8317H10.8334V15.8317H9.16669V10.8317H4.16669V9.16501H9.16669V4.16501H10.8334V9.16501H15.8334V10.8317Z" fill="#6B7280"/>',
        ],
        'minus' => [
            'vb' => '0 0 20 20', 'sz' => '20',
            'path' => '<path d="M15.8334 10.8334H4.16675V9.16669H15.8334V10.8334Z" fill="#6B7280"/>',
        ],
        'zero' => [
            'vb' => '0 0 16 16', 'sz' => '16',
            'path' => '<path d="M8 15C4.14 15 1 11.86 1 7.99997C1 4.13997 4.14 0.999969 8 0.999969C11.86 0.999969 15 4.13997 15 7.99997C15 11.86 11.86 15 8 15ZM8 1.99997C4.69 1.99997 2 4.68997 2 7.99997C2 11.31 4.69 14 8 14C11.31 14 14 11.31 14 7.99997C14 4.68997 11.31 1.99997 8 1.99997Z" fill="#6B7280"/>',
        ],
    ];

    $labels = ['check' => 'Check', 'plus' => 'More (+)', 'minus' => 'Less (−)', 'zero' => 'Skip (0)'];
    $html   = '';
    foreach ($icons as $type => $def) {
        $html .= sprintf(
            '<button type="button" class="log-btn" data-btn="%s" aria-label="%s: %s">'
            . '<svg width="%s" height="%s" viewBox="%s" fill="none" xmlns="http://www.w3.org/2000/svg">%s</svg>'
            . '</button>',
            $type,
            htmlspecialchars($labels[$type]),
            htmlspecialchars($field),
            $def['sz'], $def['sz'], $def['vb'],
            $def['path']
        );
    }
    return $html;
}
?>

<?php include('member-footer.php'); ?>