<?php
/**
 * Branch Admin — Student Form View (Create / Edit)
 *
 * Shared form for creating and editing students.
 * When $student is set, the form is in edit mode; otherwise create mode.
 * Fee is auto-populated from branch_fees if available, otherwise from course default fee.
 * All amounts in &#8377; (Indian Rupee).
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$isEdit = !empty($student);
$formAction = $isEdit
    ? $bp . '/branch/students/' . (int) ($student['id'] ?? 0)
    : $bp . '/branch/students';

// Build branch fees lookup for JS auto-populate
$branchFeesJson = [];
if (!empty($branchFees) && is_array($branchFees)) {
    foreach ($branchFees as $courseId => $fee) {
        $branchFeesJson[(int) $courseId] = (float) $fee;
    }
}

// Build course default fees lookup for JS
$courseFeesJson = [];
if (!empty($courses) && is_array($courses)) {
    foreach ($courses as $course) {
        $courseFeesJson[(int) ($course['id'] ?? 0)] = (float) ($course['fee'] ?? 0);
    }
}
?>

<div class="admin-card">
    <div class="admin-card-header">
        <h2 class="admin-card-title"><?= $isEdit ? 'Edit Student' : 'Add New Student' ?></h2>
        <a href="<?= $bp ?>/branch/students" class="admin-btn admin-btn-secondary">&larr; Back to Students</a>
    </div>
    <div class="admin-card-body">
        <form method="POST" action="<?= htmlspecialchars($formAction, ENT_QUOTES, 'UTF-8') ?>" class="admin-form" id="studentForm">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8') ?>">

            <div class="admin-form-row" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <div class="admin-form-group">
                    <label class="admin-form-label" for="name">Name <span style="color:#e74c3c;">*</span></label>
                    <input type="text" name="name" id="name" class="admin-form-input" required
                           value="<?= htmlspecialchars($student['name'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                           placeholder="Enter student name">
                </div>
                <div class="admin-form-group">
                    <label class="admin-form-label" for="email">Email <span style="color:#e74c3c;">*</span></label>
                    <input type="email" name="email" id="email" class="admin-form-input" required
                           value="<?= htmlspecialchars($student['email'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                           placeholder="Enter email address">
                </div>
            </div>

            <div class="admin-form-row" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <div class="admin-form-group">
                    <label class="admin-form-label" for="phone">Phone</label>
                    <input type="tel" name="phone" id="phone" class="admin-form-input"
                           value="<?= htmlspecialchars($student['phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                           placeholder="Enter phone number">
                </div>
                <div class="admin-form-group">
                    <label class="admin-form-label" for="password"><?= $isEdit ? 'Password (leave blank to keep current)' : 'Password <span style="color:#e74c3c;">*</span>' ?></label>
                    <input type="password" name="password" id="password" class="admin-form-input"
                           <?= $isEdit ? '' : 'required' ?>
                           placeholder="<?= $isEdit ? 'Leave blank to keep current' : 'Set login password' ?>">
                </div>
            </div>

            <div class="admin-form-row" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <div class="admin-form-group">
                    <label class="admin-form-label" for="course_id">Course <span style="color:#e74c3c;">*</span></label>
                    <select name="course_id" id="course_id" class="admin-form-input" required>
                        <option value="">-- Select Course --</option>
                        <?php if (!empty($courses) && is_array($courses)): ?>
                            <?php foreach ($courses as $course): ?>
                            <option value="<?= (int) ($course['id'] ?? 0) ?>"
                                <?= ((int) ($student['course_id'] ?? 0) === (int) ($course['id'] ?? 0)) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($course['name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                            </option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>
                <div class="admin-form-group">
                    <label class="admin-form-label" for="fee_display">Course Fee</label>
                    <div style="position:relative;">
                        <span style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#888;">&#8377;</span>
                        <input type="text" id="fee_display" class="admin-form-input" style="padding-left:28px;"
                               readonly
                               value="<?= $isEdit ? number_format((float) ($student['fee_total'] ?? 0), 2) : '' ?>"
                               placeholder="Auto-populated from course fee">
                    </div>
                    <?php if ($isEdit): ?>
                    <input type="hidden" name="fee_total" id="fee_total" value="<?= (float) ($student['fee_total'] ?? 0) ?>">
                    <?php endif; ?>
                </div>
            </div>

            <div class="admin-form-row" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <div class="admin-form-group">
                    <label class="admin-form-label" for="fee_paid">Fee Paid &#8377;</label>
                    <div style="position:relative;">
                        <span style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#888;">&#8377;</span>
                        <input type="number" name="fee_paid" id="fee_paid" class="admin-form-input" style="padding-left:28px;"
                               step="0.01" min="0"
                               value="<?= htmlspecialchars($student['fee_paid'] ?? '0', ENT_QUOTES, 'UTF-8') ?>"
                               placeholder="0.00">
                    </div>
                </div>
                <div class="admin-form-group">
                    <label class="admin-form-label" for="dob">Date of Birth</label>
                    <input type="date" name="dob" id="dob" class="admin-form-input"
                           value="<?= htmlspecialchars($student['dob'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                </div>
            </div>

            <div class="admin-form-group">
                <label class="admin-form-label" for="address">Address</label>
                <textarea name="address" id="address" class="admin-form-input" rows="3"
                          placeholder="Enter address"><?= htmlspecialchars($student['address'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
            </div>

            <div class="admin-form-row" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <div class="admin-form-group">
                    <label class="admin-form-label" for="guardian_name">Guardian Name</label>
                    <input type="text" name="guardian_name" id="guardian_name" class="admin-form-input"
                           value="<?= htmlspecialchars($student['guardian_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                           placeholder="Enter guardian name">
                </div>
                <div class="admin-form-group">
                    <label class="admin-form-label" for="guardian_phone">Guardian Phone</label>
                    <input type="tel" name="guardian_phone" id="guardian_phone" class="admin-form-input"
                           value="<?= htmlspecialchars($student['guardian_phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                           placeholder="Enter guardian phone">
                </div>
            </div>

            <?php if ($isEdit): ?>
            <div class="admin-form-group">
                <label class="admin-form-label" for="status">Status</label>
                <select name="status" id="status" class="admin-form-input">
                    <option value="active" <?= (($student['status'] ?? '') === 'active') ? 'selected' : '' ?>>Active</option>
                    <option value="partial" <?= (($student['status'] ?? '') === 'partial') ? 'selected' : '' ?>>Partial Payment</option>
                    <option value="pending" <?= (($student['status'] ?? '') === 'pending') ? 'selected' : '' ?>>Pending</option>
                    <option value="inactive" <?= (($student['status'] ?? '') === 'inactive') ? 'selected' : '' ?>>Inactive</option>
                </select>
            </div>
            <?php endif; ?>

            <div style="margin-top:20px;display:flex;gap:12px;">
                <button type="submit" class="admin-btn admin-btn-primary">
                    <?= $isEdit ? 'Update Student' : 'Add Student' ?>
                </button>
                <a href="<?= $bp ?>/branch/students" class="admin-btn admin-btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
// Auto-populate fee when course is selected
(function() {
    const branchFees = <?= json_encode($branchFeesJson) ?>;
    const courseFees = <?= json_encode($courseFeesJson) ?>;
    const courseSelect = document.getElementById('course_id');
    const feeDisplay = document.getElementById('fee_display');
    const feeTotalInput = document.getElementById('fee_total');

    if (courseSelect) {
        courseSelect.addEventListener('change', function() {
            const courseId = parseInt(this.value);
            let fee = 0;

            // Check branch_fees first, then fall back to course default fee
            if (courseId && branchFees[courseId] !== undefined) {
                fee = branchFees[courseId];
            } else if (courseId && courseFees[courseId] !== undefined) {
                fee = courseFees[courseId];
            }

            if (feeDisplay) {
                feeDisplay.value = fee > 0 ? fee.toFixed(2) : '';
            }
            if (feeTotalInput) {
                feeTotalInput.value = fee;
            }
        });
    }
})();
</script>
