CPanel Migration Guide for Auto Field Presets Feature
==========================================================

## SQL Changes

1. Copy the content from `cpanel_migration.sql` 
2. Go to your cPanel phpMyAdmin
3. Select your database
4. Click on "SQL" tab
5. Paste the SQL code and execute

## File Changes

### 1. NEW FILE: admin/auto_fields.php
This is a new file that manages auto field presets.

### 2. NEW FILE: admin/auto_fields_api.php
This is a new API file that returns auto field presets as JSON.

### 3. MODIFIED FILE: admin/students.php
This file was modified to:
- Add "Auto Field" links to Add Student and Edit Student sections
- Add quick selection containers (divs) under relevant fields
- Add JavaScript to load and display auto field presets
- Fix JavaScript syntax error

## File Contents

All file contents are provided below. Copy each file's content to the corresponding file on your cPanel.

---

## File: admin/auto_fields.php (NEW FILE)

<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';

// Allow admin, school login, or head teacher login
$is_admin = isset($_SESSION['user']) && $_SESSION['user']['role'] === 'admin';
$is_school_login = isset($_SESSION['school_logged_in']) && $_SESSION['school_logged_in'] === true;
$is_head_teacher_login = isset($_SESSION['head_teacher_logged_in']) && $_SESSION['head_teacher_logged_in'] === true;

if (!$is_admin && !$is_school_login && !$is_head_teacher_login) {
    require_any_login();
}

// Get current school context
$school_id = isset($_SESSION['current_school_id']) ? (int)$_SESSION['current_school_id'] : 0;
if (isset($_GET['school_id'])) {
    $school_id = (int)$_GET['school_id'];
    $_SESSION['current_school_id'] = $school_id;
}

// Get class_id from URL if provided
$class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;

// Handle add new preset
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_preset') {
    $name = trim($_POST['name'] ?? '');
    $field_name = trim($_POST['field_name'] ?? '');
    $field_value = trim($_POST['field_value'] ?? '');
    
    if ($name !== '' && $field_name !== '' && $field_value !== '') {
        if ($school_id > 0) {
            $stmt = $mysqli->prepare('INSERT INTO auto_field_presets (name, field_name, field_value, school_id) VALUES (?, ?, ?, ?)');
            $stmt->bind_param('sssi', $name, $field_name, $field_value, $school_id);
        } else {
            $stmt = $mysqli->prepare('INSERT INTO auto_field_presets (name, field_name, field_value) VALUES (?, ?, ?)');
            $stmt->bind_param('sss', $name, $field_name, $field_value);
        }
        
        if ($stmt->execute()) {
            $redirect = $school_id > 0 ? "/att/admin/auto_fields.php?class_id=$class_id&school_id=$school_id&success=added" : "/att/admin/auto_fields.php?class_id=$class_id&success=added";
            header("Location: $redirect");
            exit;
        }
    }
}

// Handle delete preset
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $mysqli->prepare('DELETE FROM auto_field_presets WHERE id=?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $redirect = $school_id > 0 ? "/att/admin/auto_fields.php?class_id=$class_id&school_id=$school_id&deleted=1" : "/att/admin/auto_fields.php?class_id=$class_id&deleted=1";
    header("Location: $redirect");
    exit;
}

// Define available student fields
$student_fields = [
    'name' => 'Full Name',
    'father_name' => 'Father Name',
    'father_id' => 'Father ID',
    'gender' => 'Gender',
    'mobile' => 'Mobile',
    'dob' => 'Date of Birth',
    'address' => 'Address',
    'date_of_admission' => 'Date of Admission',
    'bform' => 'B-form #',
    'student_id' => 'Student ID'
];

// Fetch existing presets - include both school-specific and global presets
if ($school_id > 0) {
    $presets_result = $mysqli->query("SELECT * FROM auto_field_presets WHERE school_id = $school_id OR school_id IS NULL ORDER BY field_name, name");
} else {
    $presets_result = $mysqli->query("SELECT * FROM auto_field_presets ORDER BY field_name, name");
}
$presets = $presets_result ? $presets_result->fetch_all(MYSQLI_ASSOC) : [];

// Group presets by field_name
$presets_by_field = [];
foreach ($presets as $preset) {
    $presets_by_field[$preset['field_name']][] = $preset;
}
?>
<?php include __DIR__ . '/../includes/header.php'; ?>
<div class="flex items-center justify-between mb-4">
  <div>
    <h1 class="text-2xl font-semibold">Auto Field Presets</h1>
    <p class="text-sm text-gray-600">Quick selection values for student fields</p>
  </div>
  <div class="flex gap-2">
    <?php if ($class_id > 0): ?>
      <a href="/att/admin/students.php?class_id=<?php echo $class_id; ?><?php echo $school_id > 0 ? "&school_id=$school_id" : ""; ?>" class="text-blue-600">Back to Students</a>
    <?php else: ?>
      <a href="/att/admin/dashboard.php" class="text-blue-600">Back to Dashboard</a>
    <?php endif; ?>
  </div>
</div>

<?php if (isset($_GET['success'])): ?>
  <div class="mb-4 p-4 bg-green-100 text-green-700 rounded">
    Preset added successfully!
  </div>
<?php endif; ?>

<?php if (isset($_GET['deleted'])): ?>
  <div class="mb-4 p-4 bg-green-100 text-green-700 rounded">
    Preset deleted successfully!
  </div>
<?php endif; ?>

<div class="grid md:grid-cols-2 gap-6 mb-6">
  <div class="bg-white shadow rounded p-4">
    <h2 class="font-semibold mb-4">Add New Preset</h2>
    <form method="post" class="space-y-4">
      <input type="hidden" name="action" value="add_preset" />
      <?php if ($school_id > 0): ?>
        <input type="hidden" name="school_id" value="<?php echo $school_id; ?>" />
      <?php endif; ?>
      <div>
        <label class="block text-sm font-medium mb-1">Preset Name</label>
        <input name="name" class="border rounded px-3 py-2 w-full" placeholder="e.g., Common Names" required />
      </div>
      <div>
        <label class="block text-sm font-medium mb-1">Select Field</label>
        <select name="field_name" class="border rounded px-3 py-2 w-full" required>
          <option value="">Select a field</option>
          <?php foreach ($student_fields as $field_key => $field_label): ?>
            <option value="<?php echo $field_key; ?>"><?php echo $field_label; ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="block text-sm font-medium mb-1">Quick Selection Values (comma separated)</label>
        <textarea name="field_value" rows="4" class="border rounded px-3 py-2 w-full" placeholder="e.g., John, Ali, Ahmed, Muhammad" required></textarea>
        <p class="text-xs text-gray-500 mt-1">Enter multiple values separated by commas</p>
      </div>
      <button class="bg-blue-600 text-white px-4 py-2 rounded">Add Preset</button>
    </form>
  </div>
</div>

<div class="bg-white shadow rounded p-4">
  <h2 class="font-semibold mb-4">Existing Presets</h2>
  <?php if (empty($presets_by_field)): ?>
    <p class="text-gray-500">No presets found. Add your first preset above.</p>
  <?php else: ?>
    <?php foreach ($student_fields as $field_key => $field_label): ?>
      <?php if (isset($presets_by_field[$field_key]) && !empty($presets_by_field[$field_key])): ?>
        <div class="mb-6">
          <h3 class="font-medium text-gray-700 mb-3 border-b pb-2"><?php echo $field_label; ?></h3>
          <div class="space-y-3">
            <?php foreach ($presets_by_field[$field_key] as $preset): ?>
              <div class="bg-gray-50 rounded p-3">
                <div class="flex justify-between items-start">
                  <div class="flex-1">
                    <p class="font-medium text-sm"><?php echo htmlspecialchars($preset['name']); ?></p>
                    <div class="mt-2 flex flex-wrap gap-1">
                      <?php 
                      $values = explode(',', $preset['field_value']);
                      foreach ($values as $value): 
                        $trimmed_value = trim($value);
                        if ($trimmed_value): 
                      ?>
                        <button type="button" onclick="copyValue('<?php echo htmlspecialchars($trimmed_value); ?>')" class="px-2 py-1 bg-blue-100 hover:bg-blue-200 text-blue-700 rounded text-xs"><?php echo htmlspecialchars($trimmed_value); ?></button>
                      <?php 
                        endif;
                      endforeach; 
                      ?>
                    </div>
                  </div>
                  <a href="/att/admin/auto_fields.php?delete=<?php echo $preset['id']; ?><?php echo $school_id > 0 ? "&school_id=$school_id" : ""; ?><?php echo $class_id > 0 ? "&class_id=$class_id" : ""; ?>" class="text-red-600 text-sm ml-4" onclick="return confirm('Delete this preset?')">Delete</a>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
      <?php endif; ?>
    <?php endforeach; ?>
  <?php endif; ?>
</div>

<script>
function copyValue(value) {
  navigator.clipboard.writeText(value).then(function() {
    alert('Copied: ' + value);
  }).catch(function(err) {
    alert('Failed to copy: ' + err);
  });
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>

---

## File: admin/auto_fields_api.php (NEW FILE)

<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';

// Allow admin, school login, or head teacher login
$is_admin = isset($_SESSION['user']) && $_SESSION['user']['role'] === 'admin';
$is_school_login = isset($_SESSION['school_logged_in']) && $_SESSION['school_logged_in'] === true;
$is_head_teacher_login = isset($_SESSION['head_teacher_logged_in']) && $_SESSION['head_teacher_logged_in'] === true;

if (!$is_admin && !$is_school_login && !$is_head_teacher_login) {
    http_response_code(403);
    exit('Access denied');
}

// Get current school context
$school_id = isset($_SESSION['current_school_id']) ? (int)$_SESSION['current_school_id'] : 0;
if (isset($_GET['school_id'])) {
    $school_id = (int)$_GET['school_id'];
}

// Fetch existing presets - include both school-specific and global presets
if ($school_id > 0) {
    $presets_result = $mysqli->query("SELECT * FROM auto_field_presets WHERE school_id = $school_id OR school_id IS NULL ORDER BY field_name, name");
} else {
    $presets_result = $mysqli->query("SELECT * FROM auto_field_presets ORDER BY field_name, name");
}
$presets = $presets_result ? $presets_result->fetch_all(MYSQLI_ASSOC) : [];

// Group presets by field_name
$presets_by_field = [];
foreach ($presets as $preset) {
    $field_name = $preset['field_name'];
    $values = array_map('trim', explode(',', $preset['field_value']));
    $values = array_filter($values, function($v) { return $v !== ''; });
    
    if (!isset($presets_by_field[$field_name])) {
        $presets_by_field[$field_name] = [];
    }
    $presets_by_field[$field_name] = array_merge($presets_by_field[$field_name], $values);
}

// Remove duplicates within each field
foreach ($presets_by_field as $field => $values) {
    $presets_by_field[$field] = array_unique($values);
}

header('Content-Type: application/json');
echo json_encode($presets_by_field);
?>

---

## File: admin/students.php (MODIFIED)

Key changes in students.php:

1. Added "Auto Field" links to Add Student and Edit Student sections
2. Added quick selection containers with IDs under relevant fields
3. Added JavaScript to load and display auto field presets
4. Fixed JavaScript syntax error

IMPORTANT: You need to manually add these changes to your existing students.php file, or replace the entire file with your updated version.

Key sections to modify:

### In Add Student section (around line 983):
```php
<div class="bg-white shadow rounded p-4">
  <div class="flex justify-between items-center mb-4">
    <h2 class="font-semibold">Add Student</h2>
    <a href="/att/admin/auto_fields.php?class_id=<?php echo $class_id; ?><?php echo $school_id > 0 ? "&school_id=$school_id" : ""; ?>" class="text-purple-600 hover:text-purple-800 text-sm font-medium">Auto Field</a>
  </div>
```

### In Edit Student section (around line 1047):
```php
<div class="bg-white shadow rounded p-4">
  <div class="flex justify-between items-center mb-4">
    <h2 class="font-semibold">Edit Student</h2>
    <a href="/att/admin/auto_fields.php?class_id=<?php echo $class_id; ?><?php echo $school_id > 0 ? "&school_id=$school_id" : ""; ?>" class="text-purple-600 hover:text-purple-800 text-sm font-medium">Auto Field</a>
  </div>
```

### Add quick selection containers to fields:
```php
// For Student ID field
<input name="student_id" id="student_id_field" ... />
<div class="mt-2" id="student_id_quick_select"></div>

// For Name field
<input name="name" id="name_field" ... />
<div class="mt-2" id="name_quick_select"></div>

// For Father Name field
<input name="father_name" id="father_name_field" ... />
<div class="mt-2" id="father_name_quick_select"></div>

// For Mobile field
<input name="mobile" id="mobile_field" ... />
<div class="mt-2" id="mobile_quick_select"></div>

// For Address field
<textarea name="address" id="address_field" ... ></textarea>
<div class="mt-2" id="address_quick_select"></div>
```

### Add similar containers to Edit form fields with "edit_" prefix:
```php
<input name="student_id" id="edit_student_id_field" ... />
<div class="mt-2" id="edit_student_id_quick_select"></div>

<input name="name" id="edit_name_field" ... />
<div class="mt-2" id="edit_name_quick_select"></div>

<input name="father_name" id="edit_father_name_field" ... />
<div class="mt-2" id="edit_father_name_quick_select"></div>

<input name="mobile" id="edit_mobile_field" ... />
<div class="mt-2" id="edit_mobile_quick_select"></div>

<textarea name="address" id="edit_address_field" ... ></textarea>
<div class="mt-2" id="edit_address_quick_select"></div>
```

### Add JavaScript at the end of the file (before footer include):
```javascript
// Load auto field presets and display quick selection buttons
function loadAutoFieldPresets() {
  console.log('Loading auto field presets for school_id: <?php echo $school_id; ?>');
  fetch('/att/admin/auto_fields_api.php?school_id=<?php echo $school_id; ?>')
    .then(response => response.json())
    .then(fieldPresets => {
      console.log('Received field presets:', fieldPresets);
      displayQuickSelection(fieldPresets);
    })
    .catch(error => console.error('Error loading auto field presets:', error));
}

function displayQuickSelection(fieldPresets) {
  // Add quick selection for name field
  const nameQuickSelect = document.getElementById('name_quick_select');
  const editNameQuickSelect = document.getElementById('edit_name_quick_select');
  
  if (nameQuickSelect && fieldPresets['name']) {
    const namePresets = fieldPresets['name'];
    if (namePresets.length > 0) {
      nameQuickSelect.innerHTML = '<p class="text-xs text-gray-500 mb-2">Quick select:</p><div class="flex flex-wrap gap-1">' +
        namePresets.map(v => `<button type="button" onclick="setFieldValue('name_field', '${v}')" class="px-2 py-1 bg-green-100 hover:bg-green-200 text-green-700 rounded text-xs">${v}</button>`).join('') +
        '</div>';
    }
  }
  
  if (editNameQuickSelect && fieldPresets['name']) {
    const namePresets = fieldPresets['name'];
    if (namePresets.length > 0) {
      editNameQuickSelect.innerHTML = '<p class="text-xs text-gray-500 mb-2">Quick select:</p><div class="flex flex-wrap gap-1">' +
        namePresets.map(v => `<button type="button" onclick="setFieldValue('edit_name_field', '${v}')" class="px-2 py-1 bg-green-100 hover:bg-green-200 text-green-700 rounded text-xs">${v}</button>`).join('') +
        '</div>';
    }
  }
  
  // Add quick selection for father name field
  const fatherNameQuickSelect = document.getElementById('father_name_quick_select');
  const editFatherNameQuickSelect = document.getElementById('edit_father_name_quick_select');
  
  if (fatherNameQuickSelect && fieldPresets['father_name']) {
    const fatherNamePresets = fieldPresets['father_name'];
    if (fatherNamePresets.length > 0) {
      fatherNameQuickSelect.innerHTML = '<p class="text-xs text-gray-500 mb-2">Quick select:</p><div class="flex flex-wrap gap-1">' +
        fatherNamePresets.map(v => `<button type="button" onclick="setFieldValue('father_name_field', '${v}')" class="px-2 py-1 bg-blue-100 hover:bg-blue-200 text-blue-700 rounded text-xs">${v}</button>`).join('') +
        '</div>';
    }
  }
  
  if (editFatherNameQuickSelect && fieldPresets['father_name']) {
    const fatherNamePresets = fieldPresets['father_name'];
    if (fatherNamePresets.length > 0) {
      editFatherNameQuickSelect.innerHTML = '<p class="text-xs text-gray-500 mb-2">Quick select:</p><div class="flex flex-wrap gap-1">' +
        fatherNamePresets.map(v => `<button type="button" onclick="setFieldValue('edit_father_name_field', '${v}')" class="px-2 py-1 bg-blue-100 hover:bg-blue-200 text-blue-700 rounded text-xs">${v}</button>`).join('') +
        '</div>';
    }
  }
  
  // Add quick selection for mobile field
  const mobileQuickSelect = document.getElementById('mobile_quick_select');
  const editMobileQuickSelect = document.getElementById('edit_mobile_quick_select');
  
  if (mobileQuickSelect && fieldPresets['mobile']) {
    const mobilePresets = fieldPresets['mobile'];
    if (mobilePresets.length > 0) {
      mobileQuickSelect.innerHTML = '<p class="text-xs text-gray-500 mb-2">Quick select:</p><div class="flex flex-wrap gap-1">' +
        mobilePresets.map(v => `<button type="button" onclick="setFieldValue('mobile_field', '${v}')" class="px-2 py-1 bg-purple-100 hover:bg-purple-200 text-purple-700 rounded text-xs">${v}</button>`).join('') +
        '</div>';
    }
  }
  
  if (editMobileQuickSelect && fieldPresets['mobile']) {
    const mobilePresets = fieldPresets['mobile'];
    if (mobilePresets.length > 0) {
      editMobileQuickSelect.innerHTML = '<p class="text-xs text-gray-500 mb-2">Quick select:</p><div class="flex flex-wrap gap-1">' +
        mobilePresets.map(v => `<button type="button" onclick="setFieldValue('edit_mobile_field', '${v}')" class="px-2 py-1 bg-purple-100 hover:bg-purple-200 text-purple-700 rounded text-xs">${v}</button>`).join('') +
        '</div>';
    }
  }
  
  // Add quick selection for student_id field
  const studentIdQuickSelect = document.getElementById('student_id_quick_select');
  const editStudentIdQuickSelect = document.getElementById('edit_student_id_quick_select');
  
  if (studentIdQuickSelect && fieldPresets['student_id']) {
    const studentIdPresets = fieldPresets['student_id'];
    if (studentIdPresets.length > 0) {
      studentIdQuickSelect.innerHTML = '<p class="text-xs text-gray-500 mb-2">Quick select:</p><div class="flex flex-wrap gap-1">' +
        studentIdPresets.map(v => `<button type="button" onclick="setFieldValue('student_id_field', '${v}')" class="px-2 py-1 bg-orange-100 hover:bg-orange-200 text-orange-700 rounded text-xs">${v}</button>`).join('') +
        '</div>';
    }
  }
  
  if (editStudentIdQuickSelect && fieldPresets['student_id']) {
    const studentIdPresets = fieldPresets['student_id'];
    if (studentIdPresets.length > 0) {
      editStudentIdQuickSelect.innerHTML = '<p class="text-xs text-gray-500 mb-2">Quick select:</p><div class="flex flex-wrap gap-1">' +
        studentIdPresets.map(v => `<button type="button" onclick="setFieldValue('edit_student_id_field', '${v}')" class="px-2 py-1 bg-orange-100 hover:bg-orange-200 text-orange-700 rounded text-xs">${v}</button>`).join('') +
        '</div>';
    }
  }
  
  // Add quick selection for address field
  const addressQuickSelect = document.getElementById('address_quick_select');
  const editAddressQuickSelect = document.getElementById('edit_address_quick_select');
  
  console.log('Address elements:', addressQuickSelect, editAddressQuickSelect);
  console.log('Address presets:', fieldPresets['address']);
  
  if (addressQuickSelect && fieldPresets['address']) {
    const addressPresets = fieldPresets['address'];
    if (addressPresets.length > 0) {
      addressQuickSelect.innerHTML = '<p class="text-xs text-gray-500 mb-2">Quick select:</p><div class="flex flex-wrap gap-1">' +
        addressPresets.map(v => `<button type="button" onclick="setTextareaValue('address_field', '${v}')" class="px-2 py-1 bg-teal-100 hover:bg-teal-200 text-teal-700 rounded text-xs">${v}</button>`).join('') +
        '</div>';
      console.log('Address quick select added for add form');
    }
  }
  
  if (editAddressQuickSelect && fieldPresets['address']) {
    const addressPresets = fieldPresets['address'];
    if (addressPresets.length > 0) {
      editAddressQuickSelect.innerHTML = '<p class="text-xs text-gray-500 mb-2">Quick select:</p><div class="flex flex-wrap gap-1">' +
        addressPresets.map(v => `<button type="button" onclick="setTextareaValue('edit_address_field', '${v}')" class="px-2 py-1 bg-teal-100 hover:bg-teal-200 text-teal-700 rounded text-xs">${v}</button>`).join('') +
        '</div>';
      console.log('Address quick select added for edit form');
    }
  }
}

function setFieldValue(fieldId, value) {
  const field = document.getElementById(fieldId);
  if (field) {
    field.value = value;
    field.focus();
  }
}

// Function to set textarea value
function setTextareaValue(fieldId, value) {
  const field = document.getElementById(fieldId);
  if (field) {
    field.value = value;
    field.focus();
  }
}

// Load presets when page loads
document.addEventListener('DOMContentLoaded', function() {
  loadAutoFieldPresets();
});
```

---

## Summary of Files to Upload

1. **admin/auto_fields.php** (NEW - create this file)
2. **admin/auto_fields_api.php** (NEW - create this file)  
3. **admin/students.php** (MODIFIED - update existing file with changes above)

## Migration Steps

1. Backup your existing files and database
2. Run the SQL code in phpMyAdmin
3. Upload the two new files to your admin folder
4. Update your existing students.php file with the changes shown above
5. Test the feature by accessing auto_fields.php

---

## Alternative: Replace Entire File

If you prefer, you can replace your entire students.php file with the updated version from your local development environment. Just download the current working version from C:\xampp\htdocs\att\admin\students.php and upload it to your cPanel.
