<?php
session_start();

// Database connection
$conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
$conn->set_charset("utf8");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get user details
$user = [];
if (isset($_GET['id'])) {
    $user_id = $conn->real_escape_string($_GET['id']);
    $sql = "SELECT * FROM `".$GLOBALS['arif_users']."` WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    
    if (!$user) {
        die("User not found");
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'];
    $user_name = $_POST['user_name'];
    $user_phone = $_POST['user_phone'];
    $type = $_POST['type'];
    $user_id = $_POST['user_id'];
    $comi_rate = $_POST['comi_rate'] ?? null;
    $profilePicPath = $user['profile_pic']; // default old pic
    
    // Validate inputs
    if (empty($user_name) || empty($user_phone) || empty($user_id)) {
        $error = "All fields are required except password";
    } elseif (!preg_match("/^[0-9]{10}$/", $user_phone)) {
        $error = "Invalid phone number format";
    } else {
        // --- Handle Profile Picture Upload ---
        if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . "/picture/";
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            $fileTmp = $_FILES['profile_pic']['tmp_name'];
            $fileName = time() . "_" . basename($_FILES['profile_pic']['name']);
            $filePath = $uploadDir . $fileName;

            if (move_uploaded_file($fileTmp, $filePath)) {
                $profilePicPath = "picture/" . $fileName;

                // Delete old file if exists
                if (!empty($user['profile_pic']) && file_exists(__DIR__ . "/" . $user['profile_pic'])) {
                    unlink(__DIR__ . "/" . $user['profile_pic']);
                }
            }
        }

        // Update query
        if (!empty($_POST['password'])) {
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $sql = "UPDATE `".$GLOBALS['arif_users']."` SET user_id = ?, user_name = ?, user_phone = ?, type = ?, comi_rate = ?, password = ?, profile_pic = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssssdssi", $user_id, $user_name, $user_phone, $type, $comi_rate, $password, $profilePicPath, $id);
        } else {
            $sql = "UPDATE `".$GLOBALS['arif_users']."` SET user_id = ?, user_name = ?, user_phone = ?, type = ?, comi_rate = ?, profile_pic = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssssdsi", $user_id, $user_name, $user_phone, $type, $comi_rate, $profilePicPath, $id);
        }
        
        if ($stmt->execute()) {
            $success = "User updated successfully!";
            // Refresh user data
            $sql = "SELECT * FROM `".$GLOBALS['arif_users']."` WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            $user = $result->fetch_assoc();
            $stmt->close();
        } else {
            $error = "Error updating user: " . $conn->error;
        }
    }
}
?>
<div>
    <div class="container">
        <h3>Edit User</h3>
        <hr>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <?php if (isset($success)): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        
        <?php if (!empty($user)): ?>
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="id" value="<?php echo htmlspecialchars($user['id']); ?>">
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group mb-3">
                            <label for="user_id" class="form-label">User ID</label>
                            <input type="text" class="form-control" id="user_id" name="user_id" value="<?php echo htmlspecialchars($user['user_id']); ?>" required>
                        </div>
                        
                        <div class="form-group mb-3">
                            <label for="user_name" class="form-label">Full Name</label>
                            <input type="text" class="form-control" id="user_name" name="user_name" 
                                   value="<?php echo htmlspecialchars($user['user_name']); ?>" required>
                        </div>

                        <div class="form-group mb-3">
                            <label for="profile_pic" class="form-label">Profile Picture</label><br>
                            <?php if (!empty($user['profile_pic'])): ?>
                                <img src="/CONTENT/ROOT_URI/Admin/<?php echo htmlspecialchars($user['profile_pic']); ?>" width="80" height="80" style="border-radius:50%; margin-bottom:10px;"><br>
                            <?php endif; ?>
                            <input type="file" class="form-control" id="profile_pic" name="profile_pic" accept="image/*">
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group mb-3">
                            <label for="user_phone" class="form-label">Phone Number</label>
                            <input type="tel" class="form-control" id="user_phone" name="user_phone" value="<?php echo htmlspecialchars($user['user_phone']); ?>" required>
                        </div>
                        
                        <div class="form-group mb-3">
                            <label for="type" class="form-label">User Type</label>
                            <select class="form-control" id="type" name="type" required onchange="toggleCommissionField()">
                                <option value="agent" <?php echo $user['type'] === 'agent' ? 'selected' : ''; ?>>Agent</option>
                                <option value="admin" <?php echo $user['type'] === 'admin' ? 'selected' : ''; ?>>Admin</option>
                                <option value="bm" <?php echo $user['type'] === 'bm' ? 'selected' : ''; ?>>Branch Manager</option>
                            </select>
                        </div>
                        
                        <div class="form-group mb-3" id="commission-field" style="<?php echo ($user['type'] === 'agent') ? '' : 'display: none;'; ?>">
                            <label for="comi_rate" class="form-label">Commission Rate (%)</label>
                            <input type="number" step="0.01" class="form-control" id="comi_rate" name="comi_rate" 
                                   value="<?php echo htmlspecialchars($user['comi_rate']); ?>" placeholder="Enter commission rate">
                        </div>
                    </div>
                </div>
                
                <div class="form-group mb-3">
                    <label for="password" class="form-label">New Password (leave blank to keep current)</label>
                    <input type="password" class="form-control" id="password" name="password">
                    <small class="text-muted">Password must be at least 8 characters long</small>
                </div>
                
                <div class="form-group mb-3">
                    <button type="submit" class="btn btn-primary">Update User</button>
                    <a href="/Admin/Settings_Agent" class="btn">Cancel</a>
                </div>
            </form>
        <?php else: ?>
            <div class="alert alert-danger">User not found</div>
        <?php endif; ?>
    </div>
</div>
<script>
    // Simple password strength check
    document.getElementById('password').addEventListener('input', function(e) {
        if (this.value.length > 0 && this.value.length < 8) {
            this.setCustomValidity("Password must be at least 8 characters");
        } else {
            this.setCustomValidity("");
        }
    });
    
    // Toggle commission field based on user type
    function toggleCommissionField() {
        const selectedUserType = document.getElementById('type').value;
        const commissionField = document.getElementById('commission-field');
        
        if (selectedUserType === 'agent') {
            commissionField.style.display = 'block';
            document.getElementById('comi_rate').setAttribute('required', 'required');
        } else {
            commissionField.style.display = 'none';
            document.getElementById('comi_rate').removeAttribute('required');
        }
    }
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        toggleCommissionField();
    });
</script>
<style>
    .container {
        max-width: 800px;
        margin-top: 30px;
    }
    img { border:1px solid #ccc; }
</style>
<?php $conn->close(); ?>