<?php
/**
 * accountability_chart.php
 *
 * WHAT THIS FILE DOES
 * ───────────────────
 * 1. Handles save / update / edit / change_log_date actions (ALL original logic preserved).
 * 2. Echoes TWO things into #accountability-form-fields:
 *      a) Hidden inputs  — carry POST values (log_date, member_id, type, posting,
 *                          meal_score_totals, activity_total_score, accountability_chart_id).
 *      b) Visible <select> elements — hidden via CSS (.custom-select { display:none })
 *                          but present in the DOM so jQuery Validate and the
 *                          icon-button JS bridge can read / write them normally.
 *
 * WHAT THIS FILE NO LONGER DOES
 * ──────────────────────────────
 * • Renders any visible table / row / submit button HTML.
 *   The card UI lives entirely in member_homepage.php.
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start(['gc_maxlifetime' => 14400, 'cookie_httponly' => true]);
}
include_once('configuration.php');

/* ── Input resolution ───────────────────────────────────────────────────── */
$get_log_date = (isset($_POST['get_log_date']) && $_POST['get_log_date'] != '')
    ? $_POST['get_log_date']
    : ((isset($_GET['get_log_date']) && $_GET['get_log_date'] != '')
        ? $_GET['get_log_date']
        : date('Y-m-d'));

// NOTE: member_id is intentionally NOT read from GET/POST — every save/update
// below is scoped to $_SESSION['memberid'] to prevent one member from writing
// to or reading another member's accountability chart (IDOR).

$type = (isset($_POST['type']) && $_POST['type'] != '')
    ? $_POST['type']
    : ((isset($_GET['type']) && $_GET['type'] != '')
        ? $_GET['type']
        : ($get_log_date != '' ? 'edit' : ''));

$accountability_chart_id = (isset($_POST['accountability_chart_id']) && $_POST['accountability_chart_id'] != '')
    ? $_POST['accountability_chart_id']
    : (isset($_GET['accountability_chart_id']) ? $_GET['accountability_chart_id'] : '');

// SECURITY FIX: only allow redirect to known internal pages (open-redirect / XSS guard).
$_raw_form_action  = $_POST['form_action'] ?? $_GET['form_action'] ?? '';
$_allowed_pages    = ['member_homepage.php', 'accountability_chart.php'];
$form_action       = in_array(basename($_raw_form_action), $_allowed_pages, true)
    ? basename($_raw_form_action)
    : htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8');

/* ── meals_per_day — needed for snack visibility and JS rules ───────────── */
// When called as an AJAX partial (change_log_date) the member object must be
// bootstrapped here; on a full page load it is already available from
// member_homepage.php, but re-fetching is harmless.
if (!isset($meals_per_day)) {
    if (!class_exists('Member')) {
        include('member_session.php');
        include('../coach/functions.php');
        include('../coach/objects/class.member.php');
    }
    $member_object = new Member();
    $member_obj    = $member_object->Get($_SESSION['memberid']);
    $meals_per_day = $member_obj->meals_per_day;
}

/* ── Message placeholder (used by save / update handlers) ───────────────── */
$message = '';

/* ══════════════════════════════════════════════════════════════════════════
   UPDATE — save edited entry
   ══════════════════════════════════════════════════════════════════════════ */
if ($type == 'update') {
    // IDOR guard: the record being edited must already belong to the logged-in member.
    $existing_chart = new Accountability_chart();
    $existing_chart->Get($accountability_chart_id);
    if ($accountability_chart_id == '' || (int)$existing_chart->memberId !== (int)$_SESSION['memberid']) {
        http_response_code(403);
        exit('Access denied.');
    }

    $accountability_chart_add           = new Accountability_chart();
    $accountability_chart_add->memberId = $_SESSION['memberid'];
    $member_det                         = $accountability_chart_add->GetMember();
    $accountability_chart_add->SetMember($member_det);

    $accountability_chart_add->log_date             = date('Y-m-d', strtotime($_POST['log_date']));
    $accountability_chart_add->breakfast            = $_POST['breakfast'];
    $accountability_chart_add->snack1               = $_POST['snack1'];
    $accountability_chart_add->lunch                = $_POST['lunch'];
    $accountability_chart_add->snack2               = $_POST['snack2'];
    $accountability_chart_add->dinner               = $_POST['dinner'];
    $accountability_chart_add->snack3               = $_POST['snack3'];
    $accountability_chart_add->extras               = $_POST['extras'];
    $accountability_chart_add->activity_level       = isset($_POST['activity_level']) ? $_POST['activity_level'] : '';
    $accountability_chart_add->cardio               = $_POST['cardio'];
    $accountability_chart_add->resistance           = $_POST['resistance'];
    $accountability_chart_add->homework             = $_POST['homework'];
    $accountability_chart_add->meal_score_totals    = $_POST['meal_score_totals'];
    $accountability_chart_add->activity_total_score = $_POST['activity_total_score'];
    $accountability_chart_add->updated_on           = date('Y-m-d H:i:s');

    if ($_POST['accountability_chart_id'] != '') {
        $accountability_chart_add->accountability_chartId = $_POST['accountability_chart_id'];
    }

    if ($accountability_chart_add->Save()) {
        $message                 = "<p class='ac-msg ac-msg--success'>" . success_text() . "</p>";
        $type                    = 'edit';
        $accountability_chart_id = $accountability_chart_add->accountability_chartId;
        $get_log_date            = date('Y-m-d', strtotime($accountability_chart_add->log_date));
    } else {
        $message                 = "<p class='ac-msg ac-msg--error'>Accountability chart not updated. Please try again.</p>";
        $type                    = 'edit';
        $accountability_chart_id = $_POST['accountability_chart_id'];
        $get_log_date            = date('Y-m-d', strtotime($_POST['log_date']));
    }
}

/* ══════════════════════════════════════════════════════════════════════════
   SAVE — create new entry
   ══════════════════════════════════════════════════════════════════════════ */
if ($type == 'save') {
    $accountability_chart_add           = new Accountability_chart();
    $accountability_chart_add->memberId = $_SESSION['memberid'];
    $member_det                         = $accountability_chart_add->GetMember();
    $accountability_chart_add->SetMember($member_det);

    $accountability_chart_add->log_date             = date('Y-m-d', strtotime($_POST['log_date']));
    $accountability_chart_add->breakfast            = $_POST['breakfast'];
    $accountability_chart_add->snack1               = $_POST['snack1'];
    $accountability_chart_add->lunch                = $_POST['lunch'];
    $accountability_chart_add->snack2               = $_POST['snack2'];
    $accountability_chart_add->dinner               = $_POST['dinner'];
    $accountability_chart_add->snack3               = $_POST['snack3'] ?? '';
    $accountability_chart_add->extras               = $_POST['extras'];
    $accountability_chart_add->activity_level       = isset($_POST['activity_level']) ? $_POST['activity_level'] : '';
    $accountability_chart_add->cardio               = $_POST['cardio'];
    $accountability_chart_add->resistance           = $_POST['resistance'];
    $accountability_chart_add->homework             = $_POST['homework'];
    $accountability_chart_add->created_on           = date('Y-m-d H:i:s');
    $accountability_chart_add->updated_on           = date('Y-m-d H:i:s');
    $accountability_chart_add->meal_score_totals    = $_POST['meal_score_totals'];
    $accountability_chart_add->activity_total_score = $_POST['activity_total_score'];

    if ($accountability_chart_add->save()) {
        $accountability_chart_id = $accountability_chart_add->accountability_chartId;
        $get_log_date            = date('Y-m-d', strtotime($accountability_chart_add->log_date));
        $message                 = "<p class='ac-msg ac-msg--success'>" . success_text() . "</p>";
        $type                    = 'edit';
    } else {
        $message = "<p class='ac-msg ac-msg--error'>Accountability chart not saved. Please try again.</p>";
        $type    = 'add';
    }
}

/* ══════════════════════════════════════════════════════════════════════════
   EDIT / CHANGE_LOG_DATE — load existing entry for the chosen date
   ══════════════════════════════════════════════════════════════════════════ */
if ($type == 'edit' || $type == 'change_log_date') {

    if ($get_log_date) {
        $memberData           = new Member();
        $memberData->memberId = $_SESSION['memberid'];
        $accountability_chart_data = $memberData->GetAccountability_chartList([
            ['log_date', '=', date('Y-m-d', strtotime($get_log_date))],
        ]);
        $accountability_chart_list = isset($accountability_chart_data[0]) ? $accountability_chart_data[0] : '';
        $accountability_chart_id   = isset($accountability_chart_list->accountability_chartId)
            ? $accountability_chart_list->accountability_chartId : '';
    }

    if (!$get_log_date) {
        $accountability_chart      = new Accountability_chart();
        $accountability_chart_list = $accountability_chart->Get($accountability_chart_id);
    }

    $get_log_date   = (isset($accountability_chart_list->log_date) && $accountability_chart_list->log_date != '')
        ? date('Y-m-d', strtotime($accountability_chart_list->log_date))
        : date('Y-m-d', strtotime($get_log_date));

    $breakfast      = isset($accountability_chart_list->breakfast)   ? $accountability_chart_list->breakfast   : '';
    $snack1         = isset($accountability_chart_list->snack1)       ? $accountability_chart_list->snack1       : '';
    $lunch          = isset($accountability_chart_list->lunch)         ? $accountability_chart_list->lunch         : '';
    $snack2         = isset($accountability_chart_list->snack2)       ? $accountability_chart_list->snack2       : '';
    $dinner         = isset($accountability_chart_list->dinner)       ? $accountability_chart_list->dinner       : '';
    $snack3         = isset($accountability_chart_list->snack3)       ? $accountability_chart_list->snack3       : '';
    $extras         = isset($accountability_chart_list->extras)       ? $accountability_chart_list->extras       : '';
    $activity_level = isset($accountability_chart_list->activity_level) ? $accountability_chart_list->activity_level : '';
    $cardio         = isset($accountability_chart_list->cardio)       ? $accountability_chart_list->cardio       : '';
    $resistance     = isset($accountability_chart_list->resistance)   ? $accountability_chart_list->resistance   : '';
    $homework       = isset($accountability_chart_list->homework)     ? $accountability_chart_list->homework     : '';

    if ($accountability_chart_id == '') {
        $type = '';
    } else {
        $type = 'edit';
    }

} else {
    /* No matching action — blank slate */
    $breakfast = $snack1 = $lunch = $snack2 = $dinner = $snack3 = '';
    $extras = $activity_level = $cardio = $resistance = $homework = '';
}

/* ══════════════════════════════════════════════════════════════════════════
   OUTPUT
   Emits ONLY:
     • An optional status message <p> (styled via CSS in member_homepage.php)
     • One hidden input per data field   → carries POST value on submit
     • One hidden <select> per field     → read/written by JS icon-button bridge
                                           and jQuery Validate
   The visible card UI (rows, labels, icon buttons) lives in member_homepage.php.
   ══════════════════════════════════════════════════════════════════════════ */

/* Helper: build a <select> whose options match the original markup exactly,
   but the element itself is hidden (CSS: select.custom-select { display:none }).
   The icon-button JS bridge reads .value and writes .value on this element.    */
function _ac_select(string $name, string $current, bool $has_zero = true): string
{
    $opts = [
        ''  => 'Select',
        '1' => '✓',   // Check
        '2' => '+',   // More
        '3' => '−',   // Less',
    ];
    if ($has_zero) {
        $opts['4'] = '0';   // Skip
    }

    $html = sprintf('<select name="%s" id="%s" class="custom-select">', $name, $name);
    foreach ($opts as $val => $label) {
        $sel   = ((string)$current === (string)$val) ? ' selected' : '';
        $html .= sprintf('<option value="%s"%s>%s</option>', $val, $sel, htmlspecialchars($label));
    }
    $html .= '</select>';
    return $html;
}

/* ── Snack conditionals (identical logic to original) ─────────────────── */
// snack1 is always rendered (visibility toggled by JS / CSS in the homepage)
// snack2 shown when meals_per_day != 4
// snack3 shown when meals_per_day != 4 AND != 5
$show_snack1 = true;
$show_snack2 = ($meals_per_day != 4);
$show_snack3 = ($meals_per_day != 4 && $meals_per_day != 5);

/* ── Determine save vs update ─────────────────────────────────────────── */
$form_type = ($type == '') ? 'save' : 'update';

/* ── Build output ─────────────────────────────────────────────────────── */
?>
<?php if ($message): ?>
    <div class="ac-message"><?php echo $message; ?></div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════
     HIDDEN SCALAR INPUTS
     All carry POST values; none are visible.
     ═══════════════════════════════════════════════ -->
<input type="hidden" id="log_date_id"             name="log_date"                value="<?php echo htmlspecialchars(date('Y-m-d', strtotime($get_log_date))); ?>">
<input type="hidden" id="posting"                 name="posting"                 value="meal_score">
<input type="hidden" id="meal_score_totals"       name="meal_score_totals"       value="">
<input type="hidden" id="activity_total_score"    name="activity_total_score"    value="">
<input type="hidden"                              name="type"                    value="<?php echo $form_type; ?>">
<input type="hidden"                              name="member_id"               value="<?php echo htmlspecialchars($_SESSION['memberid']); ?>">
<input type="hidden"                              name="accountability_chart_id" value="<?php echo htmlspecialchars($accountability_chart_id); ?>">
<input type="hidden"                              name="form_action"             value="<?php echo htmlspecialchars($form_action); ?>">

<!-- ═══════════════════════════════════════════════
     FIELD SELECTS  (hidden via CSS)
     Values are read and written by the icon-button
     JS bridge in member_homepage.php.
     ═══════════════════════════════════════════════ -->

<?php /* Meals */ ?>
<?php echo _ac_select('breakfast', $breakfast); ?>
<?php if ($show_snack1): ?>
    <?php echo _ac_select('snack1', $snack1); ?>
<?php endif; ?>
<?php echo _ac_select('lunch', $lunch); ?>
<?php if ($show_snack2): ?>
    <?php echo _ac_select('snack2', $snack2); ?>
<?php endif; ?>
<?php echo _ac_select('dinner', $dinner); ?>
<?php if ($show_snack3): ?>
    <?php echo _ac_select('snack3', $snack3); ?>
<?php endif; ?>

<?php /* Extras — original only had a "plus" option; keep that restriction */ ?>
<select name="extras" id="extras" class="custom-select">
    <option value=""<?php echo ($extras == '')  ? ' selected' : ''; ?>>Select</option>
    <option value="2"<?php echo ($extras == '2') ? ' selected' : ''; ?>>+</option>
</select>

<?php /* Activity */ ?>
<?php echo _ac_select('cardio',     $cardio); ?>
<?php echo _ac_select('resistance', $resistance); ?>
<?php echo _ac_select('homework',   $homework); ?>

<!-- activity_level textarea preserved (was commented out in original; keep hidden) -->
<textarea name="activity_level" id="activity_level" style="display:none"><?php echo htmlspecialchars(isset($activity_level) ? $activity_level : ''); ?></textarea>