<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Include DB connection
include __DIR__ . '/../inc/db.php'; // Adjust path if necessary

header('Content-Type: application/json');

// Get action from request
$action = $_REQUEST['action'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get POST data
    $id       = $_POST['id'] ?? null;
    $name     = $_POST['name'] ?? '';
    $email    = $_POST['email'] ?? '';
    $phone    = $_POST['phone'] ?? '';
    $username = $_POST['username'] ?? '';
    $role     = $_POST['role'] ?? 'sales';
    $password = $_POST['password'] ?? '';
    $status   = $_POST['status'] ?? 'active';

    // CREATE
    if ($action === 'Create') {
        if (empty($name) || empty($email) || empty($phone) || empty($username) || empty($password)) {
            echo json_encode(["status" => "error", "message" => "All fields are required"]);
            exit;
        }

        // Check if email or username already exists
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ? OR username = ?");
        $stmt->bind_param("ss", $email, $username);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            echo json_encode(["status" => "error", "message" => "Email or Username already exists"]);
            exit;
        }

        // Hash the password
        $hash = password_hash($password, PASSWORD_BCRYPT);

        // Insert new user into database
        $stmt = $conn->prepare("INSERT INTO users (name, email, phone, username, password, role, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssss", $name, $email, $phone, $username, $hash, $role, $status);

        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "User created successfully"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to execute query", "error" => $stmt->error]);
        }
        exit;
    }

    // UPDATE
    if ($action === 'Update' && $id) {
        if (empty($name) || empty($email) || empty($phone) || empty($username)) {
            echo json_encode(["status" => "error", "message" => "All fields are required"]);
            exit;
        }

        // Check if user exists
        $stmt = $conn->prepare("SELECT id FROM users WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            echo json_encode(["status" => "error", "message" => "User not found"]);
            exit;
        }

        // Prepare SQL for update
        if (!empty($password)) {
            $hash = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("UPDATE users SET name=?, email=?, phone=?, username=?, password=?, role=?, status=? WHERE id=?");
            $stmt->bind_param("sssssssi", $name, $email, $phone, $username, $hash, $role, $status, $id);
        } else {
            $stmt = $conn->prepare("UPDATE users SET name=?, email=?, phone=?, username=?, role=?, status=? WHERE id=?");
            $stmt->bind_param("ssssssi", $name, $email, $phone, $username, $role, $status, $id);
        }

        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "User updated successfully"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to execute update", "error" => $stmt->error]);
        }
        exit;
    }

    // DELETE
    if ($action === 'Delete' && $id) {
        // Check if user exists
        $stmt = $conn->prepare("SELECT id FROM users WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            echo json_encode(["status" => "error", "message" => "User not found"]);
            exit;
        }

        // Delete user from database
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "User deleted successfully"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to delete user", "error" => $stmt->error]);
        }
        exit;
    }

	// SELECT
if ($action === 'Select' && $id) {
    $stmt = $conn->prepare("SELECT id, name, email, phone, username, role, status FROM users WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(["status" => "error", "message" => "User not found"]);
        exit;
    }

    $user = $result->fetch_assoc();
    echo json_encode($user);
    exit;
}

    // TOGGLE STATUS
    if ($action === 'ToggleStatus' && $id) {
        // Check if user exists
        $stmt = $conn->prepare("SELECT status FROM users WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();

        if (!$result) {
            echo json_encode(["status" => "error", "message" => "User not found"]);
            exit;
        }

        // Toggle user status
        $new_status = ($result['status'] === 'active') ? 'inactive' : 'active';
        $stmt = $conn->prepare("UPDATE users SET status = ? WHERE id = ?");
        $stmt->bind_param("si", $new_status, $id);

        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "User status updated", "new_status" => $new_status]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to toggle user status", "error" => $stmt->error]);
        }
        exit;
    }
}



?>
