<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');

// Start session
session_start();

// Check if user is logged in and has admin privileges
if (!isset($_SESSION['user_id']) || !in_array(strtolower($_SESSION['role']), ['superadmin', 'admin'])) {
    header('Location: login.php');
    exit();
}

// Verify CSRF token
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die("CSRF token validation failed");
}

// Include database configuration
require_once 'config.php';

// Get form data
$user_id = isset($_POST['user_id']) ? trim($_POST['user_id']) : '';
$field_name = isset($_POST['field_name']) ? trim($_POST['field_name']) : '';
$field_value = isset($_POST['field_value']) ? trim($_POST['field_value']) : '';

// Validate inputs
if (empty($user_id) || empty($field_name)) {
    die("Invalid request parameters");
}

// List of allowed fields that can be updated
$allowed_fields = [
    'first_name', 'last_name', 'gender', 'date_of_birth', 'marital_status',
    'spouse_name', 'no_of_children', 'mother_name', 'father_name', 'username',
    'mobileno', 'address', 'pancard', 'aadharcard', 'role', 'is_superadmin',
    'designation', 'department', 'level', 'position', 'appointment_type',
    'location', 'reporting_manager', 'responsibilities', 'role_id',
    'date_of_joining', 'status', 'resignation_date', 'rejoin_date',
    'performance', 'basic_salary', 'bank_name', 'account_number',
    'ifsc_code', 'uan_no', 'esic_no', 'qualification', 'previous_experience',
    'company_name', 'total_experience_years', 'previous_salary', 'bloodgroup'
];

// Validate field name
if (!in_array($field_name, $allowed_fields)) {
    die("Invalid field name");
}

try {
    // Prepare update statement
    $stmt = $conn->prepare("UPDATE users SET $field_name = ? WHERE id = ?");
    if (!$stmt) {
        throw new Exception("Database error: Unable to prepare statement");
    }
    
    // Bind parameters based on field type
    if (in_array($field_name, ['no_of_children', 'performance', 'role_id', 'total_experience_years'])) {
        $stmt->bind_param("ii", (int)$field_value, (int)$user_id);
    } elseif (in_array($field_name, ['basic_salary', 'previous_salary'])) {
        $stmt->bind_param("di", (float)$field_value, (int)$user_id);
    } elseif ($field_name === 'is_superadmin') {
        $bool_value = strtolower($field_value) === 'yes' ? 1 : 0;
        $stmt->bind_param("ii", $bool_value, (int)$user_id);
    } else {
        $stmt->bind_param("si", $field_value, (int)$user_id);
    }

    // Execute the update
    if ($stmt->execute()) {
        // Redirect back with success message
        header("Location: view_user_details.php?id=$user_id&message=Field+updated+successfully");
        exit();
    } else {
        throw new Exception("Database error: Unable to execute update");
    }
} catch (Exception $e) {
    error_log("Error updating user field: " . $e->getMessage());
    header("Location: view_user_details.php?id=$user_id&error=" . urlencode($e->getMessage()));
    exit();
}