<?php
// Weka header za JSON
header("Content-Type: application/json");

include '../../config.php';

// Hakikisha method ni POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Pata data kutoka kwa POST
    $id = isset($_POST['id']) ? intval($_POST['id']) : null;
    $firstname = $_POST['firstname'] ?? null;
    $lastname = $_POST['lastname'] ?? null;
    $email = $_POST['email'] ?? null;
    $phone = $_POST['phone'] ?? null;
    $branch_id = $_POST['branch_id'] ?? null;

    // Hakikisha fields zote muhimu zipo
    if (!$id || !$firstname || !$lastname || !$email || !$phone || !$branch_id) {
        echo json_encode([
            'success' => false,
            'message' => 'Missing required fields.'
        ]);
        exit;
    }

    // Andaa query ya update kwenye meza ya 'users'
    $query = "UPDATE users SET firstname = ?, lastname = ?, email = ?, phone = ?, branch_id = ? WHERE id = ?";

    if ($stmt = $conn->prepare($query)) {
        // Bind parameters: "ssssii" inamaanisha string, string, string, string, integer, integer
        $stmt->bind_param("ssssii", $firstname, $lastname, $email, $phone, $branch_id, $id);

        // Endesha statement
        if ($stmt->execute()) {
            echo json_encode([
                'success' => true,
                'message' => 'Staff updated successfully.'
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Failed to update staff.'
            ]);
        }
        $stmt->close();
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to prepare statement.'
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method.'
    ]);
}
?>
