<?php

use Mtc\Shop\Assessment\BmiEthnicity;
use Mtc\Shop\Assessment\AssessmentEthnicity;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

$display_form = true;
$errors = [];

init_request_values([
    'record_id' => null,
    'action' => null,
]);

// Check if table is empty and create default records
if (BmiEthnicity::count() === 0) {
    BmiEthnicity::createDefaultBmiEthnicityRecords();
}

if ($_REQUEST['action'] === 'delete' && is_numeric($_REQUEST['delete_id'])) {
    $record = BmiEthnicity::find($_REQUEST['delete_id']);
    if ($record) {
        $record->delete();
    }
    header('location: manage.bmi_ethnicity.php');
    exit;
}

$record = $_REQUEST['record_id'] ? BmiEthnicity::find($_REQUEST['record_id']) : new BmiEthnicity();
$addedit = $_REQUEST['record_id'] ? 'Update' : 'Add';

$page_meta['title'] = $addedit . ' BMI Ethnicity Record';

if ($_REQUEST['action'] === 'save') {
    $request = $_POST;

    // Validation
    if (empty($request['bmi_category'])) {
        $errors[] = 'BMI Category is required';
    }
    if (empty($request['ethnicity_id'])) {
        $errors[] = 'Ethnicity is required';
    }

    if (empty($errors)) {
        $request['is_active'] = empty($request['is_active']) ? '0' : '1';

        // Convert empty strings to null for float fields
        $request['cutoff_low'] = empty($request['cutoff_low']) ? null : floatval($request['cutoff_low']);
        $request['cutoff_high'] = empty($request['cutoff_high']) ? null : floatval($request['cutoff_high']);

        $record->fill($request);
        $record->save();

        if (!empty($_REQUEST['save_and_back'])) {
            header('location: manage.bmi_ethnicity.php');
        } elseif (!empty($_REQUEST['save_and_add'])) {
            header('location: manage.bmi_ethnicity.php?action=add');
        } else {
            header('location: manage.bmi_ethnicity.php?record_id=' . $record->id);
        }
        exit;
    }
}

require_once $path . 'core/admin/templates/adminheader.html.php';
?>

<ul class="breadcrumbs el">
    <li>
        <a href="/admin/">Home</a>
        /</li>
    <li>
        <a href="manage.forms.php">Assessment Forms</a>
        /</li>
    <li>
        <a href="manage.bmi_ethnicity.php">Manage BMI Ethnicity Records</a>
        /</li>
    <li class="end"><?= clean_page($page_meta['title']) ?></li>
</ul>

<h1><?= $page_meta['title']; ?></h1>

<?php
if (count($errors) > 0) {
    showerrors($errors);
}

if (!$_REQUEST['record_id'] && $_REQUEST['action'] !== 'add') {
    // Show listing page
    $records = BmiEthnicity::with('ethnicity')->orderBy('ethnicity_id')->orderBy('bmi_category')->get();
    ?>

    <div style="margin-bottom: 20px;">
        <a href="manage.bmi_ethnicity.php?action=add" class="button btn">Add New BMI Ethnicity Record</a>
    </div>

    <table class="manage-items">
        <thead>
            <tr>
                <th>ID</th>
                <th>Ethnicity</th>
                <th>BMI Category</th>
                <th>Low Cutoff</th>
                <th>High Cutoff</th>
                <th>Message</th>
                <th>Active</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($records as $r): ?>
                <tr>
                    <td><?= $r->id ?></td>
                    <td><?= clean_page($r->ethnicity?->name ?? 'Unknown') ?></td>
                    <td><?= clean_page($r->bmi_category) ?></td>
                    <td><?= $r->cutoff_low ?? '-' ?></td>
                    <td><?= $r->cutoff_high ?? '-' ?></td>
                    <td><?= clean_page(substr($r->message ?? '', 0, 50)) ?>
                        <?= strlen($r->message ?? '') > 50 ? '...' : '' ?>
                    </td>
                    <td>
                        <?= $r->is_active ? 'Yes' : 'No' ?>
                    </td>
                    <td>
                        <a href="manage.bmi_ethnicity.php?record_id=<?= $r->id ?>">
                            Edit</a>
                        |
                        <a href="manage.bmi_ethnicity.php?action=delete&delete_id=<?= $r->id ?>" onclick="return confirm('Are you sure you want to delete this record?')">Delete</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <?php
} else {
    // Show add/edit form
    $ethnicities = AssessmentEthnicity::getActiveEthnicities();
    $bmiCategories = BmiEthnicity::BMI_CATEGORIES;
    ?>

    <form action="" method="post" class="style">
        <fieldset class="show">
            <h1>
                <a
                    class="show el">
                    <?= $page_meta['title']; ?>
                    <i class="fa fa-caret-right"></i>
                </a>
            </h1>

            <div class="row">
                <label for="ethnicity_id">Ethnicity *</label>
                <select name="ethnicity_id" id="ethnicity_id" required>
                    <option value="">-- Select Ethnicity --</option>
                    <?php foreach ($ethnicities as $ethnicity): ?>
                        <option
                            value="<?= $ethnicity->id ?>" <?= $record->ethnicity_id == $ethnicity->id ? 'selected' : '' ?>><?= clean_page($ethnicity->name) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="row">
                <label for="bmi_category">BMI Category *</label>
                <select name="bmi_category" id="bmi_category" required>
                    <option value="">-- Select Category --</option>
                    <?php foreach ($bmiCategories as $category): ?>
                        <option
                            value="<?= $category ?>" <?= $record->bmi_category === $category ? 'selected' : '' ?>><?= $category ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="row">
                <label for="cutoff_low">Low Cutoff (BMI)</label>
                <input type="number" name="cutoff_low" id="cutoff_low" step="0.1" min="0" value="<?= $record->cutoff_low ?>"/>
                <div class="defaultValue">
                    <span>Minimum BMI required for treatment eligibility</span>
                </div>
            </div>

            <div class="row">
                <label for="cutoff_high">High Cutoff (BMI)</label>
                <input type="number" name="cutoff_high" id="cutoff_high" step="0.1" min="0" value="<?= $record->cutoff_high ?>"/>
                <div class="defaultValue">
                    <span>Maximum BMI for treatment eligibility (optional)</span>
                </div>
            </div>

            <div class="row">
                <label for="message">Message</label>
                <textarea name="message" id="message" rows="4"><?= clean_page($record->message) ?></textarea>
                <div class="defaultValue">
                    <span>Message to display when BMI is outside acceptable range</span>
                </div>
            </div>

            <div class="row">
                <label for="is_active">Active</label>
                <input type="checkbox" name="is_active" id="is_active" value="1" class="" <?= $record->is_active ? 'checked' : ''; ?>/>
            </div>

        </fieldset>

        <fieldset>
            <div class="save-button">
                <input
                type="hidden" name="action" value="save"/>
                <?php if ($record->id): ?>
                    <input
                    type="hidden" name="record_id" value="<?= $record->id ?>"/>
                <?php endif; ?>
                <input type="submit" name="save" value="Save"/>
                <input type="submit" name="save_and_back" class="saveAndAdd" value="Save &amp; Back"/>
                <input type="submit" name="save_and_add" class="saveAndAdd" value="Save &amp; Add Next"/>
                <a href="manage.bmi_ethnicity.php" class="button btn btn-grey saveAndAdd">Cancel</a>
            </div>
        </fieldset>
    </form><?php
}

require_once $path . 'core/admin/templates/adminfooter.html.php';
?>

