<?php

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 (AssessmentEthnicity::count() === 0) {
    AssessmentEthnicity::createDefaultEthnicities();
}

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

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

$page_meta['title'] = $addedit . ' Assessment Ethnicity';

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

    // Validation
    if (empty($request['name'])) {
        $errors[] = 'Ethnicity Name is required';
    }

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

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

        if (!empty($_REQUEST['save_and_back'])) {
            header('location: manage.ethnicities.php?success=Ethnicity saved successfully');
        } elseif (!empty($_REQUEST['save_and_add'])) {
            header('location: manage.ethnicities.php?action=add&success=Ethnicity saved successfully');
        } else {
            header('location: manage.ethnicities.php?record_id=' . $record->id . '&success=Ethnicity saved successfully');
        }
        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.ethnicities.php">Manage Assessment Ethnicities</a>
        /</li>
    <li class="end"><?= clean_page($page_meta['title']) ?></li>
</ul>

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

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

$success = $_REQUEST['success'] ?? null;
if ($success) {
    echo '<div class="el success msg">' . $success . '<i class="fa fa-check-circle"></i></div>';
}

if (!$_REQUEST['record_id'] && $_REQUEST['action'] !== 'add') {
    // Show listing page
    $records = AssessmentEthnicity::orderBy('sort_order')->orderBy('name')->get();
    ?>

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

    <table class="manage-items">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Description</th>
                <th>Sort Order</th>
                <th>Active</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($records as $r): ?>
                <tr>
                    <td><?= $r->id ?></td>
                    <td><?= clean_page($r->name) ?></td>
                    <td><?= clean_page(substr($r->description ?? '', 0, 50)) ?>
                        <?= strlen($r->description ?? '') > 50 ? '...' : '' ?>
                    </td>
                    <td><?= $r->sort_order ?></td>
                    <td>
                        <?= $r->is_active ? 'Yes' : 'No' ?>
                    </td>
                    <td>
                        <a href="manage.ethnicities.php?record_id=<?= $r->id ?>">
                            Edit</a>
                        |
                        <a href="manage.ethnicities.php?action=delete&delete_id=<?= $r->id ?>" onclick="return confirm('Are you sure you want to delete this ethnicity? This will also delete associated BMI ethnicity records.')">Delete</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <?php
} else {
    // Show add/edit form
    ?>

    <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="name">Ethnicity Name *</label>
                <input type="text" name="name" id="name" value="<?= clean_page($record->name) ?>" required/>
                <div class="defaultValue">
                    <span>Name of the ethnicity group (e.g., "White or Hispanic", "South Asian")</span>
                </div>
            </div>

            <div class="row">
                <label for="description">Description</label>
                <textarea name="description" id="description" rows="3"><?= clean_page($record->description) ?></textarea>
                <div class="defaultValue">
                    <span>Optional description of the ethnicity group</span>
                </div>
            </div>

            <div class="row">
                <label for="sort_order">Sort Order</label>
                <input type="number" name="sort_order" id="sort_order" value="<?= $record->sort_order ?? 0 ?>" min="0" step="1"/>
                <div class="defaultValue">
                    <span>Order in which this ethnicity appears (lower numbers appear first)</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.ethnicities.php" class="button btn btn-grey saveAndAdd">Cancel</a>
            </div>
        </fieldset>
    </form><?php
}

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

